From 099af21102989111757b1d8c2039526dff2cc77c Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Thu, 19 Nov 2026 18:13:17 -0800 Subject: [PATCH 01/20] Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- Justfile | 30 + docs/observability.md | 3 + docs/scale-testing.md | 62 ++ k8s/observability.yaml | 2 +- scripts/fixtures/scale-workload/Dockerfile | 13 + scripts/scale-test.py | 712 +++++++++++++++++++++ scripts/tests/test_scale_test.py | 266 ++++++++ 7 files changed, 1087 insertions(+), 1 deletion(-) create mode 100644 docs/scale-testing.md create mode 100644 scripts/fixtures/scale-workload/Dockerfile create mode 100644 scripts/scale-test.py create mode 100644 scripts/tests/test_scale_test.py diff --git a/Justfile b/Justfile index 3e2e54a..4e4c1f5 100644 --- a/Justfile +++ b/Justfile @@ -15,6 +15,7 @@ exe-suffix := if os() == "windows" { ".exe" } else { "" } # Kind release installed by `just install-kind` in every workflow (CI, release # gates, Copilot); providers/kind/templates/kind-config.yaml pins its node image. kind-version := "v0.33.0" +oha-version := "1.17.0" default: @just --list @@ -205,6 +206,18 @@ install-mm: mkdir -p "{{repo-root}}/build/tools"; \ tar --extract --gzip --file "$dir/mm.tar.gz" --directory "{{repo-root}}/build/tools" mm +# Install the pinned oha load generator used by opt-in scale tests. +install-oha: + if [ -x "{{repo-root}}/build/tools/oha" ] && \ + [ "$("{{repo-root}}/build/tools/oha" --version)" = "oha {{oha-version}}" ]; then exit 0; fi; \ + [ "$(uname -sm)" = "Linux x86_64" ] || { echo "install-oha supports linux-amd64 only" >&2; exit 1; }; \ + mkdir -p "{{repo-root}}/build/tools"; \ + curl --fail --silent --show-error --location --output "{{repo-root}}/build/tools/oha.tmp" \ + "https://github.com/hatoo/oha/releases/download/v{{oha-version}}/oha-linux-amd64"; \ + echo "85c6eb98066b8c8bd513b2dd96fafd8f9863249ea653606bae1ca2e3a75c43d2 {{repo-root}}/build/tools/oha.tmp" | sha256sum --check; \ + chmod 0755 "{{repo-root}}/build/tools/oha.tmp"; \ + mv "{{repo-root}}/build/tools/oha.tmp" "{{repo-root}}/build/tools/oha" + prepare-workspace: build-ly if [[ ! -f build/workspace/lampyr.workspace.yaml ]]; then build/ly scaffold workspace build/workspace; fi @@ -346,6 +359,23 @@ release-disruption-gate service url: --service "{{service}}" \ --url "{{url}}" +# Build the normal Kubernetes image from the same Go source as the Lampyr example. +[positional-arguments] +scale-baseline-image image: + docker build --tag "$1" --file scripts/fixtures/scale-workload/Dockerfile . + +# Compare Lampyr with a normal Kubernetes Deployment using platform telemetry. +[positional-arguments] +scale-test context service lampyr-url baseline-image duration="30s" concurrency="1,4,16,64" output="build/scale-results.json": install-oha + python3 scripts/scale-test.py \ + --context "$1" \ + --service "$2" \ + --lampyr-url "$3" \ + --baseline-image "$4" \ + --duration "$5" \ + --concurrency "$6" \ + --output "$7" + # Run the repository test suites used in CI. test: test-unit test-cli examples-check test-preview-release cli::test cli::test-intent helper::test azure::test kind::test k3d::test test-examples-local test-kind-integration test-k3d-integration test-existing-kind-integration test-knative-portability test-walkthrough diff --git a/docs/observability.md b/docs/observability.md index c4bfe2e..1b678a5 100644 --- a/docs/observability.md +++ b/docs/observability.md @@ -59,6 +59,9 @@ Uninstall disables fiber-router trace export before it removes Jaeger. Remove the add-on before `ly cluster uninstall` when retaining the Kubernetes cluster; the platform uninstall does not remove optional add-ons. +The [scale framework](scale-testing.md) uses these metrics for repeatable +Lampyr and Kubernetes comparisons. + ## Platform metrics | Metric | Type | Meaning | diff --git a/docs/scale-testing.md b/docs/scale-testing.md new file mode 100644 index 0000000..749e028 --- /dev/null +++ b/docs/scale-testing.md @@ -0,0 +1,62 @@ +--- +title: Scale testing +description: Compare Lampyr with the same application in a Kubernetes Deployment. +--- + +# Scale testing + +The opt-in scale framework compares a Lampyr Service with the same Go +application in a normal Kubernetes Deployment. It uses oha for client latency +and throughput, and queries the optional observability add-on for platform +metrics. It does not run in CI. + +Install the add-on and deploy the committed Go standalone example through +Lampyr. Build and publish the normal Kubernetes image from the same source: + +```bash +just scale-baseline-image REGISTRY/IMAGE:TAG +docker push REGISTRY/IMAGE:TAG +docker buildx imagetools inspect REGISTRY/IMAGE:TAG +``` + +Pass the digest-pinned image and the Lampyr URL: + +```bash +just scale-test \ + CONTEXT \ + SERVICE \ + https://LAMPYR_URL \ + REGISTRY/IMAGE@sha256:DIGEST +``` + +The default sweep runs each target for 30 seconds at concurrency 1, 4, 16, +and 64. The framework: + +- creates a temporary one-replica Kubernetes Deployment and Service; +- warms both targets; +- runs the same client against Lampyr and Kubernetes; +- queries Prometheus for request, Fiber, CPU, and memory measurements; +- writes `build/scale-results.json` after every scenario; and +- writes a concise Markdown comparison beside it. + +The Kubernetes target uses a local Service port-forward, while the Lampyr URL +uses its configured ingress. Record that path difference when interpreting +results. The result metadata records both paths. The framework monitors the +port-forward and stops if it exits, but the tunnel can still limit high +concurrency results. This framework is for repeatable comparisons, not a claim +that the two network paths have identical overhead. + +The report calculates HTTP success from response status codes and transport +errors. Its latency columns include only successful HTTP responses. Platform +error and shed counts come from Lampyr metrics. The runner waits for a final +Prometheus scrape after each load interval. If needed, it waits for up to five +more scrape intervals so short smoke tests still have enough cAdvisor samples. +CPU measurements include that collection interval. + +Use the Lampyr Platform Grafana dashboard while a run is active. The JSON +result remains the source for comparisons across commits or machines. It +records the image digest, namespace, replica count, oha version, Git state, and +a limited node summary without node addresses or machine identifiers. + +Keep the node type, cluster configuration, workload image, Lampyr settings, +duration, and concurrency sweep unchanged when comparing revisions. diff --git a/k8s/observability.yaml b/k8s/observability.yaml index cfd63d3..53798e7 100644 --- a/k8s/observability.yaml +++ b/k8s/observability.yaml @@ -273,7 +273,7 @@ spec: image: registry.k8s.io/kube-state-metrics/kube-state-metrics:v2.20.0@sha256:42cfe3723a5f058171c627537fb57a3ea0f26e4380fa18555a95cb1a1b4cfc5b args: - --resources=deployments,namespaces,nodes,pods - - --metric-labels-allowlist=pods=[lampyr.dev/home] + - --metric-labels-allowlist=pods=[lampyr.dev/home,serving.knative.dev/revision] ports: - name: metrics containerPort: 8080 diff --git a/scripts/fixtures/scale-workload/Dockerfile b/scripts/fixtures/scale-workload/Dockerfile new file mode 100644 index 0000000..c0a8c05 --- /dev/null +++ b/scripts/fixtures/scale-workload/Dockerfile @@ -0,0 +1,13 @@ +# syntax=docker/dockerfile:1 +FROM golang:1.26.7-bookworm@sha256:e8c859f5632dcfde7b32d2012b4351728f6437930887c2f6a91ea242459e5514 AS build +WORKDIR /src +COPY docs/examples/hello-go-standalone/go.mod docs/examples/hello-go-standalone/go.sum ./ +RUN go mod download +COPY docs/examples/hello-go-standalone/application.go docs/examples/hello-go-standalone/main.go ./ +RUN CGO_ENABLED=0 go build -mod=readonly -trimpath -ldflags="-s -w" -o /service . + +FROM scratch +COPY --from=build /service /service +ENV PORT=8080 +USER 65532:65532 +ENTRYPOINT ["/service"] diff --git a/scripts/scale-test.py b/scripts/scale-test.py new file mode 100644 index 0000000..e28c3a7 --- /dev/null +++ b/scripts/scale-test.py @@ -0,0 +1,712 @@ +#!/usr/bin/env python3 + +import argparse +import contextlib +import datetime +import json +import math +import os +from pathlib import Path +import re +import socket +import subprocess +import sys +import tempfile +import time +import urllib.parse + + +BASELINE = "lampyr-scale-baseline" +PROMETHEUS_PROXY = ( + "/api/v1/namespaces/lampyr-observability/" + "services/http:prometheus:9090/proxy/api/v1/query" +) + + +def command(*args): + return subprocess.check_output(args, text=True).strip() + + +def duration_seconds(value): + match = re.fullmatch(r"([1-9][0-9]*)(s|m)", value) + if not match: + raise ValueError("duration must be a positive number of seconds or minutes") + amount = int(match.group(1)) + return amount * (60 if match.group(2) == "m" else 1) + + +def active_revision(context, service, namespace): + value = json.loads( + command( + "kubectl", + "--context", + context, + "--namespace", + namespace, + "get", + "service.serving.knative.dev", + service, + "--output", + "json", + ) + ) + revisions = { + target["revisionName"] + for target in value.get("status", {}).get("traffic", []) + if target.get("percent", 0) > 0 + } + if len(revisions) != 1: + raise RuntimeError( + f"service must have exactly one active Revision, got {len(revisions)}" + ) + return next(iter(revisions)) + + +def prometheus_query(context, query, evaluation_time=None): + parameters = {"query": query} + if evaluation_time is not None: + parameters["time"] = f"{evaluation_time:.3f}" + path = PROMETHEUS_PROXY + "?" + urllib.parse.urlencode(parameters) + result = json.loads(command("kubectl", "--context", context, "get", "--raw", path)) + if result.get("status") != "success": + raise RuntimeError(f"Prometheus query failed: {result}") + values = result["data"]["result"] + if not values: + return None + if len(values) != 1: + raise RuntimeError(f"Prometheus query returned {len(values)} series: {query}") + value = float(values[0]["value"][1]) + return value if math.isfinite(value) else None + + +def metric_queries(namespace, revision, window, baseline, window_seconds=30): + revision_match = f'namespace="{namespace}",revision="{revision}"' + running_home = ( + '* on(namespace,pod) group_left() ' + f'(kube_pod_status_phase{{namespace="{namespace}",phase="Running"}} == 1)' + ) + running_router = ( + '* on(namespace,pod) group_left() ' + '(kube_pod_status_phase{namespace="lampyr-system",phase="Running"} == 1)' + ) + home = ( + '* on(namespace,pod) group_left() ' + f'(kube_pod_labels{{namespace="{namespace}",label_lampyr_dev_home="true",' + f'label_serving_knative_dev_revision="{revision}"}} {running_home})' + ) + baseline_pods = f'namespace="{namespace}",pod=~"{baseline}-.*"' + return { + "lampyrRequests": ( + "sum(lampyr_router_request_duration_seconds_count" + f"{{{revision_match}}})" + ), + "lampyrErrors": ( + "sum(lampyr_router_request_duration_seconds_count" + f'{{{revision_match},code!~"2..|3.."}})' + ), + "lampyrRequestP95Seconds": ( + "histogram_quantile(0.95,sum by(le)(increase(" + f"lampyr_router_request_duration_seconds_bucket{{{revision_match}}}" + f"[{window}])))" + ), + "lampyrAcquireP95Seconds": ( + "histogram_quantile(0.95,sum by(le)(increase(" + f"lampyr_router_fiber_acquire_seconds_bucket{{{revision_match}}}" + f"[{window}])))" + ), + "lampyrShed": ( + "sum(lampyr_router_shed_total" f"{{{revision_match}}})" + ), + "lampyrRetries": ( + "sum(lampyr_router_clone_retries_total" f"{{{revision_match}}})" + ), + "lampyrPeakBusyFibers": ( + "max_over_time((sum(lampyr_router_fibers_busy" + f"{{{revision_match}}}))[{window}:5s])" + ), + "lampyrPeakInFlight": ( + "max_over_time((sum(lampyr_router_requests_in_flight" + f"{{{revision_match}}}))[{window}:5s])" + ), + "lampyrRouterCPU": ( + "sum(increase(container_cpu_usage_seconds_total" + f'{{namespace="lampyr-system",container="router"}}[{window}])' + f" {running_router}" + ")" + f" / {window_seconds:.3f}" + ), + "lampyrRouterMemoryBytes": ( + "max_over_time((sum(container_memory_working_set_bytes" + '{namespace="lampyr-system",container="router"} ' + f"{running_router}))" + f"[{window}:5s])" + ), + "lampyrHomeCPU": ( + "(sum(increase(container_cpu_usage_seconds_total" + f'{{namespace="{namespace}",container="fiberd"}}[{window}]) ' + f"{home})) / {window_seconds:.3f}" + ), + "lampyrHomeMemoryBytes": ( + "max_over_time((sum(container_memory_working_set_bytes" + f'{{namespace="{namespace}",container="fiberd"}} {home}))[{window}:5s])' + ), + "baselineCPU": ( + "sum(increase(container_cpu_usage_seconds_total" + f"{{{baseline_pods},container=\"app\"}}[{window}])" + f" {running_home}" + ")" + f" / {window_seconds:.3f}" + ), + "baselineMemoryBytes": ( + "max_over_time((sum(container_memory_working_set_bytes" + f"{{{baseline_pods},container=\"app\"}} {running_home}))" + f"[{window}:5s])" + ), + } + + +COUNTER_METRICS = { + "lampyrRequests", + "lampyrErrors", + "lampyrShed", + "lampyrRetries", +} + + +def counter_snapshot(context, queries): + return { + name: prometheus_query(context, query) + for name, query in queries.items() + if name in COUNTER_METRICS + } + + +def collect_metrics(context, queries, before, evaluation_time): + collected = {} + for name, query in queries.items(): + value = prometheus_query(context, query, evaluation_time) + if name not in COUNTER_METRICS: + collected[name] = value + continue + if name == "lampyrRequests" and (before[name] is None or value is None): + raise RuntimeError( + "Lampyr request metrics are missing; check the observability add-on " + "and requested namespace" + ) + previous = before[name] or 0 + current = value or 0 + if current < previous: + raise RuntimeError(f"Prometheus counter reset during scenario: {name}") + collected[name] = current - previous + return collected + + +def baseline_manifest(image, replicas, namespace): + labels = {"app": BASELINE} + return { + "apiVersion": "v1", + "kind": "List", + "items": [ + { + "apiVersion": "apps/v1", + "kind": "Deployment", + "metadata": {"name": BASELINE, "namespace": namespace}, + "spec": { + "replicas": replicas, + "selector": {"matchLabels": labels}, + "template": { + "metadata": {"labels": labels}, + "spec": { + "automountServiceAccountToken": False, + "securityContext": { + "runAsNonRoot": True, + "runAsUser": 65532, + "runAsGroup": 65532, + "seccompProfile": {"type": "RuntimeDefault"}, + }, + "containers": [ + { + "name": "app", + "image": image, + "ports": [{"name": "http", "containerPort": 8080}], + "readinessProbe": { + "httpGet": {"path": "/", "port": "http"} + }, + "resources": { + "requests": { + "cpu": "250m", + "memory": "256Mi", + }, + "limits": {"memory": "256Mi"}, + }, + "securityContext": { + "allowPrivilegeEscalation": False, + "capabilities": {"drop": ["ALL"]}, + "readOnlyRootFilesystem": True, + "runAsNonRoot": True, + }, + } + ] + }, + }, + }, + }, + { + "apiVersion": "v1", + "kind": "Service", + "metadata": {"name": BASELINE, "namespace": namespace}, + "spec": { + "selector": labels, + "ports": [{"name": "http", "port": 80, "targetPort": "http"}], + }, + }, + ], + } + + +def kubectl_manifest(context, action, value, *extra): + return subprocess.run( + ["kubectl", "--context", context, action, "--filename", "-", *extra], + input=json.dumps(value), + text=True, + check=True, + stdout=subprocess.DEVNULL, + ) + + +def free_port(): + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + return listener.getsockname()[1] + + +@contextlib.contextmanager +def baseline_server(context, image, replicas, namespace): + if "@sha256:" not in image: + raise ValueError("baseline image must be digest-pinned") + manifest = baseline_manifest(image, replicas, namespace) + forward = None + try: + kubectl_manifest(context, "apply", manifest) + subprocess.run( + [ + "kubectl", + "--context", + context, + "--namespace", + namespace, + "rollout", + "status", + f"deployment/{BASELINE}", + "--timeout=300s", + ], + check=True, + ) + port = free_port() + forward = subprocess.Popen( + [ + "kubectl", + "--context", + context, + "--namespace", + namespace, + "port-forward", + f"service/{BASELINE}", + f"{port}:80", + ], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + deadline = time.time() + 30 + while time.time() < deadline: + if forward.poll() is not None: + raise RuntimeError("baseline port-forward exited before becoming ready") + with socket.socket() as connection: + if connection.connect_ex(("127.0.0.1", port)) == 0: + break + time.sleep(0.1) + else: + raise RuntimeError("baseline port-forward did not become ready") + yield {"url": f"http://127.0.0.1:{port}/", "process": forward} + finally: + original_error = sys.exc_info()[0] is not None + if forward is not None: + forward.terminate() + try: + forward.wait(timeout=5) + except subprocess.TimeoutExpired: + forward.kill() + forward.wait() + try: + kubectl_manifest( + context, "delete", manifest, "--ignore-not-found=true", "--wait=true" + ) + except subprocess.CalledProcessError as error: + if not original_error: + raise + print(f"warning: baseline cleanup failed: {error}", file=sys.stderr) + + +def require_running(process, name): + return_code = process.poll() + if return_code is not None: + raise RuntimeError(f"{name} exited with status {return_code}") + + +def run_oha(oha, url, duration, concurrency): + output = subprocess.check_output( + [ + str(oha), + "-z", + duration, + "-c", + str(concurrency), + "--wait-ongoing-requests-after-deadline", + "--stats-success-breakdown", + "--no-tui", + "--output-format", + "json", + "--insecure", + url, + ], + text=True, + ) + result = json.loads(output) + client = { + "summary": result["summary"], + "metrics": result.get("metrics", {}), + "statusCodeDistribution": result["statusCodeDistribution"], + "errorDistribution": result["errorDistribution"], + "successfulLatencyMs": { + name: value * 1000 if value is not None else None + for name, value in result["latencyPercentilesSuccessful"].items() + }, + } + client["httpSuccessRate"] = http_success_rate(client) + return client + + +def http_success_rate(client): + statuses = client.get("statusCodeDistribution", {}) + errors = client.get("errorDistribution", {}) + total = sum(statuses.values()) + sum(errors.values()) + if total == 0: + return 0 + successful = sum( + count for code, count in statuses.items() if 200 <= int(code) < 400 + ) + return successful / total + + +def warm_target(oha, url): + output = subprocess.check_output( + [ + str(oha), + "-n", + "20", + "-c", + "1", + "--stats-success-breakdown", + "--no-tui", + "--output-format", + "json", + "--insecure", + url, + ], + text=True, + ) + client = json.loads(output) + if http_success_rate(client) != 1: + raise RuntimeError( + "target warmup did not return only successful HTTP responses: " + f"statuses={client.get('statusCodeDistribution', {})} " + f"errors={client.get('errorDistribution', {})}" + ) + + +def display_number(value, precision=2): + if value is None: + return "n/a" + return f"{value:.{precision}f}" + + +def add_metrics(*values): + if any(value is None for value in values): + return None + return sum(values) + + +def target_resource_names(target): + if target == "lampyr": + return ( + "lampyrRouterCPU", + "lampyrHomeCPU", + "lampyrRouterMemoryBytes", + "lampyrHomeMemoryBytes", + ) + return ("baselineCPU", "baselineMemoryBytes") + + +def target_resources_available(target, metrics): + return all(metrics[name] is not None for name in target_resource_names(target)) + + +def atomic_write(path, content): + path.parent.mkdir(parents=True, exist_ok=True) + temporary = None + try: + with tempfile.NamedTemporaryFile( + mode="w", dir=path.parent, prefix=f".{path.name}.", delete=False + ) as handle: + temporary = Path(handle.name) + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + + +def write_json(result, path): + atomic_write(path, json.dumps(result, indent=2, sort_keys=True) + "\n") + + +def write_report(result, path): + lines = [ + "# Lampyr scale comparison", + "", + f"- Commit: `{result['metadata']['commit']}`", + f"- Context: `{result['metadata']['context']}`", + f"- Revision: `{result['metadata']['revision']}`", + f"- Duration per run: `{result['metadata']['duration']}`", + f"- Baseline image: `{result['metadata']['baselineImage']}`", + f"- Lampyr path: {result['metadata']['networkPaths']['lampyr']}", + f"- Kubernetes path: {result['metadata']['networkPaths']['kubernetes']}", + "", + "| Target | Concurrency | Requests/s | HTTP success | p50 ms | p95 ms | p99 ms | Platform errors | Shed | CPU cores | Peak memory MiB |", + "|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|", + ] + for scenario in result["scenarios"]: + client = scenario["client"] + metrics = scenario["platform"] + if scenario["target"] == "lampyr": + cpu = add_metrics( + metrics["lampyrRouterCPU"], metrics["lampyrHomeCPU"] + ) + memory = add_metrics( + metrics["lampyrRouterMemoryBytes"], + metrics["lampyrHomeMemoryBytes"], + ) + errors = metrics.get("lampyrErrors") + shed = metrics.get("lampyrShed") + else: + cpu = metrics["baselineCPU"] + memory = metrics["baselineMemoryBytes"] + errors = None + shed = None + latency = client.get("successfulLatencyMs", {}) + lines.append( + "| {target} | {concurrency} | {rps:.2f} | {success:.4f} | " + "{p50} | {p95} | {p99} | {errors} | {shed} | {cpu} | {memory} |".format( + target=scenario["target"], + concurrency=scenario["concurrency"], + rps=client["summary"]["requestsPerSec"], + success=client["httpSuccessRate"], + p50=display_number(latency.get("p50")), + p95=display_number(latency.get("p95")), + p99=display_number(latency.get("p99")), + errors=display_number(errors, 0), + shed=display_number(shed, 0), + cpu=display_number(cpu, 3), + memory=display_number( + memory / (1 << 20) if memory is not None else None + ), + ) + ) + atomic_write(path, "\n".join(lines) + "\n") + + +def node_summary(value): + nodes = [] + for item in value.get("items", []): + metadata = item.get("metadata", {}) + status = item.get("status", {}) + info = status.get("nodeInfo", {}) + labels = metadata.get("labels", {}) + nodes.append( + { + "name": metadata.get("name"), + "instanceType": labels.get("node.kubernetes.io/instance-type"), + "allocatable": status.get("allocatable", {}), + "kubeletVersion": info.get("kubeletVersion"), + "operatingSystem": info.get("operatingSystem"), + "osImage": info.get("osImage"), + "kernelVersion": info.get("kernelVersion"), + "containerRuntimeVersion": info.get("containerRuntimeVersion"), + } + ) + return nodes + + +def safe_url(value): + parsed = urllib.parse.urlsplit(value) + host = parsed.hostname or "" + if ":" in host: + host = f"[{host}]" + netloc = host + if parsed.port is not None: + netloc += f":{parsed.port}" + return urllib.parse.urlunsplit((parsed.scheme, netloc, parsed.path, "", "")) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--context", required=True) + parser.add_argument("--service", required=True) + parser.add_argument("--lampyr-url", required=True) + parser.add_argument("--baseline-image", required=True) + parser.add_argument("--namespace", default="default") + parser.add_argument("--baseline-replicas", type=int, default=1) + parser.add_argument("--duration", default="30s") + parser.add_argument("--concurrency", default="1,4,16,64") + parser.add_argument("--oha", default="build/tools/oha") + parser.add_argument("--output", default="build/scale-results.json") + args = parser.parse_args() + + seconds = duration_seconds(args.duration) + concurrencies = [int(value) for value in args.concurrency.split(",")] + if not concurrencies or any(value < 1 for value in concurrencies): + raise ValueError("concurrency values must be positive integers") + if args.baseline_replicas < 1: + raise ValueError("baseline replicas must be a positive integer") + oha = Path(args.oha) + if not oha.is_file(): + raise FileNotFoundError(f"load generator not found: {oha}") + revision = active_revision(args.context, args.service, args.namespace) + output = Path(args.output) + output.parent.mkdir(parents=True, exist_ok=True) + metadata = { + "context": args.context, + "service": args.service, + "namespace": args.namespace, + "revision": revision, + "lampyrUrl": safe_url(args.lampyr_url), + "baselineImage": args.baseline_image, + "baselineReplicas": args.baseline_replicas, + "duration": args.duration, + "concurrency": concurrencies, + "commit": command("git", "rev-parse", "HEAD"), + "dirty": bool(command("git", "status", "--porcelain")), + "ohaVersion": command(str(oha), "--version"), + "networkPaths": { + "lampyr": "configured ingress URL", + "kubernetes": "kubectl Service port-forward", + }, + "startedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), + "nodes": node_summary( + json.loads( + command( + "kubectl", + "--context", + args.context, + "get", + "nodes", + "--output", + "json", + ) + ) + ), + } + result = {"schema": 1, "metadata": metadata, "scenarios": []} + with baseline_server( + args.context, args.baseline_image, args.baseline_replicas, args.namespace + ) as baseline: + for target, url in [ + ("lampyr", args.lampyr_url), + ("kubernetes", baseline["url"]), + ]: + if target == "kubernetes": + require_running(baseline["process"], "baseline port-forward") + warm_target(oha, url) + time.sleep(6) + for concurrency in concurrencies: + for target, url in [ + ("lampyr", args.lampyr_url), + ("kubernetes", baseline["url"]), + ]: + if target == "kubernetes": + require_running(baseline["process"], "baseline port-forward") + snapshot_queries = metric_queries( + args.namespace, revision, "1s", BASELINE, 1 + ) + before = counter_snapshot(args.context, snapshot_queries) + if before["lampyrRequests"] is None: + raise RuntimeError( + "Lampyr request metrics are missing after warmup; check the " + "observability add-on and requested namespace" + ) + started = datetime.datetime.now(datetime.timezone.utc) + client = run_oha(oha, url, args.duration, concurrency) + load_ended = datetime.datetime.now(datetime.timezone.utc) + if target == "kubernetes": + require_running(baseline["process"], "baseline port-forward") + platform = None + for wait_seconds in (6, 5, 5, 5, 5, 5): + time.sleep(wait_seconds) + evaluated = time.time() + measured_seconds = evaluated - started.timestamp() + window = f"{math.ceil(measured_seconds * 1000)}ms" + queries = metric_queries( + args.namespace, + revision, + window, + BASELINE, + measured_seconds, + ) + resources = { + name: prometheus_query( + args.context, queries[name], evaluated + ) + for name in target_resource_names(target) + } + if target_resources_available(target, resources): + platform = collect_metrics( + args.context, queries, before, evaluated + ) + break + else: + raise RuntimeError( + f"Prometheus did not collect CPU and memory metrics for {target}" + ) + scenario = { + "target": target, + "concurrency": concurrency, + "startedAt": started.isoformat(), + "loadEndedAt": load_ended.isoformat(), + "metricsEvaluatedAt": datetime.datetime.fromtimestamp( + evaluated, datetime.timezone.utc + ).isoformat(), + "metricsWindowSeconds": measured_seconds, + "client": client, + "platform": platform, + } + result["scenarios"].append(scenario) + write_json(result, output) + write_report(result, output.with_suffix(".md")) + p95 = display_number(client["successfulLatencyMs"].get("p95")) + print( + f"{target} concurrency={concurrency} " + f"rps={client['summary']['requestsPerSec']:.2f} " + f"http_success={client['httpSuccessRate']:.4f} " + f"p95={p95}ms" + ) + result["metadata"]["completedAt"] = datetime.datetime.now( + datetime.timezone.utc + ).isoformat() + write_json(result, output) + write_report(result, output.with_suffix(".md")) + + +if __name__ == "__main__": + main() diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py new file mode 100644 index 0000000..85caa3d --- /dev/null +++ b/scripts/tests/test_scale_test.py @@ -0,0 +1,266 @@ +import importlib.util +from pathlib import Path +import tempfile +import unittest +from unittest import mock + + +PATH = Path(__file__).resolve().parents[1] / "scale-test.py" +SPEC = importlib.util.spec_from_file_location("scale_test", PATH) +scale = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(scale) + + +class ScaleTestTests(unittest.TestCase): + def test_duration_seconds(self): + self.assertEqual(scale.duration_seconds("30s"), 30) + self.assertEqual(scale.duration_seconds("2m"), 120) + for invalid in ("0s", "1h", "ten"): + with self.assertRaises(ValueError): + scale.duration_seconds(invalid) + + def test_report_compares_lampyr_and_kubernetes(self): + result = { + "metadata": { + "commit": "abc", + "dirty": False, + "context": "kind-test", + "revision": "demo-00001", + "duration": "30s", + "baselineImage": "example.test/baseline@sha256:abc", + "networkPaths": { + "lampyr": "configured ingress URL", + "kubernetes": "kubectl Service port-forward", + }, + }, + "scenarios": [ + { + "target": "lampyr", + "concurrency": 4, + "client": { + "summary": {"requestsPerSec": 10}, + "httpSuccessRate": 1, + "successfulLatencyMs": { + "p50": 1, + "p95": 2, + "p99": 3, + }, + }, + "platform": { + "lampyrErrors": 0, + "lampyrShed": 0, + "lampyrRouterCPU": 0.1, + "lampyrHomeCPU": 0.2, + "lampyrRouterMemoryBytes": 1 << 20, + "lampyrHomeMemoryBytes": 2 << 20, + "baselineCPU": None, + "baselineMemoryBytes": None, + }, + }, + { + "target": "kubernetes", + "concurrency": 4, + "client": { + "summary": {"requestsPerSec": 20}, + "httpSuccessRate": 1, + "successfulLatencyMs": { + "p50": 1, + "p95": 2, + "p99": 3, + }, + }, + "platform": { + "lampyrErrors": None, + "lampyrShed": None, + "lampyrRouterCPU": None, + "lampyrHomeCPU": None, + "lampyrRouterMemoryBytes": None, + "lampyrHomeMemoryBytes": None, + "baselineCPU": 0.4, + "baselineMemoryBytes": 4 << 20, + }, + }, + ], + } + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "report.md" + scale.write_report(result, output) + report = output.read_text() + self.assertIn("| lampyr | 4 | 10.00", report) + self.assertIn("| kubernetes | 4 | 20.00", report) + self.assertIn("| 0 | 0 | 0.300 | 3.00 |", report) + self.assertIn("kubectl Service port-forward", report) + + def test_report_handles_no_successful_responses(self): + result = { + "metadata": { + "commit": "abc", + "dirty": True, + "context": "kind-test", + "revision": "demo-00001", + "duration": "30s", + "baselineImage": "example.test/baseline@sha256:abc", + "networkPaths": { + "lampyr": "configured ingress URL", + "kubernetes": "kubectl Service port-forward", + }, + }, + "scenarios": [ + { + "target": "lampyr", + "concurrency": 4, + "client": { + "summary": {"requestsPerSec": 10}, + "httpSuccessRate": 0, + "successfulLatencyMs": { + "p50": None, + "p95": None, + "p99": None, + }, + }, + "platform": { + "lampyrErrors": 20, + "lampyrShed": 20, + "lampyrRouterCPU": None, + "lampyrHomeCPU": None, + "lampyrRouterMemoryBytes": None, + "lampyrHomeMemoryBytes": None, + "baselineCPU": None, + "baselineMemoryBytes": None, + }, + } + ], + } + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "report.md" + scale.write_report(result, output) + report = output.read_text() + self.assertIn("| lampyr | 4 | 10.00 | 0.0000 | n/a | n/a | n/a | 20 | 20 |", report) + + def test_report_does_not_turn_missing_metrics_into_zero(self): + result = { + "metadata": { + "commit": "abc", + "dirty": False, + "context": "kind-test", + "revision": "demo-00001", + "duration": "30s", + "baselineImage": "example.test/baseline@sha256:abc", + "networkPaths": { + "lampyr": "configured ingress URL", + "kubernetes": "kubectl Service port-forward", + }, + }, + "scenarios": [ + { + "target": "kubernetes", + "concurrency": 4, + "client": { + "summary": {"requestsPerSec": 20}, + "httpSuccessRate": 1, + "successfulLatencyMs": { + "p50": 1, + "p95": 2, + "p99": 3, + }, + }, + "platform": { + "lampyrErrors": 0, + "lampyrShed": 0, + "lampyrRouterCPU": 0.1, + "lampyrHomeCPU": 0.2, + "lampyrRouterMemoryBytes": 1 << 20, + "lampyrHomeMemoryBytes": 2 << 20, + "baselineCPU": None, + "baselineMemoryBytes": None, + }, + } + ], + } + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "report.md" + scale.write_report(result, output) + report = output.read_text() + self.assertIn("| n/a | n/a | n/a | n/a |", report) + + def test_http_success_rate_includes_transport_errors(self): + client = { + "statusCodeDistribution": {"200": 3, "503": 1}, + "errorDistribution": {"connection refused": 2}, + } + self.assertEqual(scale.http_success_rate(client), 0.5) + + def test_safe_url_removes_credentials_and_query(self): + self.assertEqual( + scale.safe_url("https://user:secret@example.test:8443/path?token=secret"), + "https://example.test:8443/path", + ) + + def test_metric_queries_use_requested_namespace(self): + queries = scale.metric_queries("team-a", "demo-00001", "30s", "baseline") + for name in ( + "lampyrRequestP95Seconds", + "lampyrAcquireP95Seconds", + "lampyrPeakBusyFibers", + "lampyrPeakInFlight", + "baselineCPU", + "baselineMemoryBytes", + ): + self.assertIn('namespace="team-a"', queries[name]) + self.assertIn( + 'label_serving_knative_dev_revision="demo-00001"', + queries["lampyrHomeCPU"], + ) + for name in ( + "lampyrRouterCPU", + "lampyrRouterMemoryBytes", + "lampyrHomeCPU", + "lampyrHomeMemoryBytes", + "baselineCPU", + "baselineMemoryBytes", + ): + self.assertIn("kube_pod_status_phase", queries[name]) + + def test_target_resources_require_cpu_and_memory(self): + metrics = { + "lampyrRouterCPU": 0.1, + "lampyrHomeCPU": 0.2, + "lampyrRouterMemoryBytes": 1, + "lampyrHomeMemoryBytes": 2, + "baselineCPU": None, + "baselineMemoryBytes": None, + } + self.assertTrue(scale.target_resources_available("lampyr", metrics)) + self.assertFalse(scale.target_resources_available("kubernetes", metrics)) + + def test_baseline_manifest_uses_restricted_pod_security(self): + manifest = scale.baseline_manifest( + "example.test/baseline@sha256:abc", 1, "team-a" + ) + deployment = manifest["items"][0] + pod = deployment["spec"]["template"]["spec"] + container = pod["containers"][0] + self.assertEqual(deployment["metadata"]["namespace"], "team-a") + self.assertFalse(pod["automountServiceAccountToken"]) + self.assertEqual(pod["securityContext"]["seccompProfile"]["type"], "RuntimeDefault") + self.assertTrue(container["securityContext"]["runAsNonRoot"]) + self.assertTrue(container["securityContext"]["readOnlyRootFilesystem"]) + + def test_baseline_cleanup_runs_when_rollout_fails(self): + image = "example.test/baseline@sha256:abc" + rollout_error = scale.subprocess.CalledProcessError(1, ["kubectl"]) + with mock.patch.object(scale, "kubectl_manifest") as manifest: + with mock.patch.object( + scale.subprocess, "run", side_effect=rollout_error + ): + with self.assertRaises(scale.subprocess.CalledProcessError): + with scale.baseline_server("test", image, 1, "team-a"): + pass + self.assertEqual( + [call.args[1] for call in manifest.call_args_list], + ["apply", "delete"], + ) + + +if __name__ == "__main__": + unittest.main() From d51c187cd8ba5039fdcf901976ba1effb275cda8 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 20 Nov 2026 17:33:45 -0800 Subject: [PATCH 02/20] fixup! Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- Justfile | 1 + scripts/tests/test_scale_test.py | 212 ++++++++++++++++++++++++++++++- 2 files changed, 211 insertions(+), 2 deletions(-) diff --git a/Justfile b/Justfile index 4e4c1f5..5a89dca 100644 --- a/Justfile +++ b/Justfile @@ -278,6 +278,7 @@ check-action-versions: # Run focused unit tests for Lampyr. test-unit: + python3 "{{repo-root}}/scripts/tests/test_scale_test.py" go test ./cmd/... ./internal/... python3 "{{repo-root}}/scripts/tests/test_worker_workspace.py" diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index 85caa3d..42596fb 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -1,4 +1,7 @@ +import contextlib import importlib.util +import json +import os from pathlib import Path import tempfile import unittest @@ -12,6 +15,18 @@ class ScaleTestTests(unittest.TestCase): + def main_arguments(self, *extra): + return [ + str(PATH), + "--context", "test", + "--service", "demo", + "--lampyr-url", "https://example.test/", + "--baseline-image", "example.test/baseline@sha256:abc", + "--oha", str(PATH), + "--concurrency", "1", + *extra, + ] + def test_duration_seconds(self): self.assertEqual(scale.duration_seconds("30s"), 30) self.assertEqual(scale.duration_seconds("2m"), 120) @@ -53,6 +68,7 @@ def test_report_compares_lampyr_and_kubernetes(self): "lampyrHomeCPU": 0.2, "lampyrRouterMemoryBytes": 1 << 20, "lampyrHomeMemoryBytes": 2 << 20, + "lampyrMemoryBytes": 2.5 * (1 << 20), "baselineCPU": None, "baselineMemoryBytes": None, }, @@ -88,7 +104,7 @@ def test_report_compares_lampyr_and_kubernetes(self): report = output.read_text() self.assertIn("| lampyr | 4 | 10.00", report) self.assertIn("| kubernetes | 4 | 20.00", report) - self.assertIn("| 0 | 0 | 0.300 | 3.00 |", report) + self.assertIn("| 0 | 0 | 0.300 | 2.50 |", report) self.assertIn("kubectl Service port-forward", report) def test_report_handles_no_successful_responses(self): @@ -125,6 +141,7 @@ def test_report_handles_no_successful_responses(self): "lampyrHomeCPU": None, "lampyrRouterMemoryBytes": None, "lampyrHomeMemoryBytes": None, + "lampyrMemoryBytes": None, "baselineCPU": None, "baselineMemoryBytes": None, }, @@ -227,11 +244,14 @@ def test_target_resources_require_cpu_and_memory(self): "lampyrHomeCPU": 0.2, "lampyrRouterMemoryBytes": 1, "lampyrHomeMemoryBytes": 2, + "lampyrMemoryBytes": 3, "baselineCPU": None, "baselineMemoryBytes": None, } self.assertTrue(scale.target_resources_available("lampyr", metrics)) self.assertFalse(scale.target_resources_available("kubernetes", metrics)) + metrics["lampyrMemoryBytes"] = None + self.assertFalse(scale.target_resources_available("lampyr", metrics)) def test_baseline_manifest_uses_restricted_pod_security(self): manifest = scale.baseline_manifest( @@ -258,8 +278,196 @@ def test_baseline_cleanup_runs_when_rollout_fails(self): pass self.assertEqual( [call.args[1] for call in manifest.call_args_list], - ["apply", "delete"], + ["create", "create", "delete"], + ) + + def test_baseline_does_not_delete_resources_when_creation_fails(self): + failure = scale.subprocess.CalledProcessError(1, ["kubectl"]) + with mock.patch.object(scale, "kubectl_manifest", side_effect=failure) as manifest: + with self.assertRaises(scale.subprocess.CalledProcessError): + with scale.baseline_server( + "test", "example.test/baseline@sha256:abc", 1, "team-a" + ): + pass + self.assertEqual(manifest.call_count, 1) + + def test_baseline_partial_creation_cleans_only_created_resources(self): + failure = scale.subprocess.CalledProcessError(1, ["kubectl"]) + with mock.patch.object( + scale, "kubectl_manifest", side_effect=[None, failure, None] + ) as manifest, mock.patch.object( + scale.subprocess, "run", side_effect=AssertionError("unexpected rollout") + ): + with self.assertRaises(scale.subprocess.CalledProcessError): + with scale.baseline_server( + "test", "example.test/baseline@sha256:abc", 1, "team-a" + ): + pass + self.assertEqual( + [call.args[1] for call in manifest.call_args_list], + ["create", "create", "delete"], + ) + cleanup = manifest.call_args.args[2]["items"] + self.assertEqual(cleanup, [manifest.call_args_list[0].args[2]]) + self.assertEqual(cleanup[0]["kind"], "Deployment") + + def test_baseline_runs_have_distinct_names_and_selectors(self): + failure = scale.subprocess.CalledProcessError(1, ["kubectl"]) + with mock.patch.object(scale, "kubectl_manifest") as manifest, mock.patch.object( + scale.subprocess, "run", side_effect=failure + ): + for _ in range(2): + with self.assertRaises(scale.subprocess.CalledProcessError): + with scale.baseline_server( + "test", "example.test/baseline@sha256:abc", 1, "team-a" + ): + pass + deployments = [] + for call in manifest.call_args_list: + if call.args[1] in ("apply", "create"): + value = call.args[2] + deployments.extend( + item for item in value.get("items", [value]) + if item["kind"] == "Deployment" + ) + self.assertEqual(len(deployments), 2) + self.assertNotEqual( + deployments[0]["metadata"]["name"], deployments[1]["metadata"]["name"] ) + self.assertNotEqual( + deployments[0]["spec"]["selector"], deployments[1]["spec"]["selector"] + ) + + def test_counter_resets_are_rejected_when_aggregate_increases(self): + queries = scale.metric_queries("team-a", "demo-00001", "30s", "baseline") + before = {name: 100 for name in scale.COUNTER_METRICS} + for name in scale.COUNTER_METRICS: + series = queries[name].removeprefix("sum(").removesuffix(")") + + def query_result(context, query, evaluation_time): + if "resets(" in query: + return int(f"resets({series}[" in query) + return 150 if query in (queries[key] for key in before) else 1 + + with self.subTest(metric=name), mock.patch.object( + scale, "prometheus_query", side_effect=query_result + ): + with self.assertRaisesRegex(RuntimeError, f"counter reset.*{name}"): + scale.collect_metrics("test", queries, before, 42) + + def test_load_and_warmup_bound_stalled_requests_with_the_same_timeout(self): + result = json.dumps({ + "summary": {"requestsPerSec": 1}, + "statusCodeDistribution": {"200": 1}, + "errorDistribution": {}, + "latencyPercentilesSuccessful": {"p95": 0.1}, + }) + with mock.patch.object( + scale.subprocess, "check_output", return_value=result + ) as execute: + scale.run_oha(Path("/oha"), "http://example.test/", "30s", 1) + scale.warm_target(Path("/oha"), "http://example.test/") + timeouts = [] + for call in execute.call_args_list: + arguments = call.args[0] + self.assertIn("-t", arguments) + value = arguments[arguments.index("-t") + 1] + self.assertGreater(scale.duration_seconds(value), 0) + self.assertGreater(call.kwargs["timeout"], 0) + timeouts.append(value) + self.assertEqual(timeouts[0], timeouts[1]) + + def test_main_rejects_multiple_baseline_replicas_and_short_cpu_windows(self): + for arguments, message in ( + (("--baseline-replicas", "2"), "one replica"), + (("--duration", "1s"), "at least 30"), + ): + with self.subTest(arguments=arguments), mock.patch.object( + scale.sys, "argv", self.main_arguments(*arguments) + ), mock.patch.object( + scale, "active_revision", return_value="demo-00001" + ) as revision, mock.patch.object( + scale, "command", return_value="{}" + ), mock.patch.object( + scale, "baseline_server", side_effect=AssertionError("unsafe configuration") + ): + with self.assertRaisesRegex(ValueError, message): + scale.main() + revision.assert_not_called() + + def test_relative_oha_path_executes_the_requested_local_binary(self): + execute = scale.command + with tempfile.TemporaryDirectory() as temporary: + executable = Path(temporary) / "oha" + executable.write_text("#!/bin/sh\necho 'oha test'\n") + executable.chmod(0o755) + + def metadata_command(*arguments): + return execute(*arguments) if "--version" in arguments else "{}" + + with contextlib.chdir(temporary), mock.patch.dict( + os.environ, {"PATH": os.defpath} + ), mock.patch.object( + scale.sys, "argv", self.main_arguments("--oha", "./oha") + ), mock.patch.object( + scale, "active_revision", return_value="demo-00001" + ), mock.patch.object( + scale, "command", side_effect=metadata_command + ) as command, mock.patch.object( + scale, "baseline_server", side_effect=RuntimeError("metadata collected") + ): + with self.assertRaisesRegex(RuntimeError, "metadata collected"): + scale.main() + version = next( + call.args for call in command.call_args_list if "--version" in call.args + ) + self.assertEqual(version[0], str(executable)) + + def test_scenario_waits_for_every_router_post_load_scrape(self): + clock = scale.datetime.datetime.fromtimestamp(400, scale.datetime.timezone.utc) + baseline = { + "name": "baseline-owned", + "url": "http://localhost/", + "process": mock.Mock(poll=mock.Mock(return_value=None)), + } + client = { + "summary": {"requestsPerSec": 1}, + "httpSuccessRate": 1, + "successfulLatencyMs": {"p95": 1}, + } + with mock.patch.object( + scale.sys, "argv", self.main_arguments() + ), mock.patch.object( + scale, "active_revision", return_value="demo-00001" + ), mock.patch.object( + scale, "command", return_value="{}" + ), mock.patch.object( + scale, "baseline_server", return_value=contextlib.nullcontext(baseline) + ), mock.patch.object( + scale, "warm_target" + ), mock.patch.object( + scale, "run_oha", return_value=client + ), mock.patch.object( + scale, "prometheus_query", return_value=1 + ), mock.patch.object( + scale, "router_scrapes", create=True, + side_effect=[{"router-1": 399, "router-2": 399}] + + [{"router-1": 420, "router-2": 399}] * 6, + ), mock.patch.object( + scale.datetime, "datetime", wraps=scale.datetime.datetime + ) as datetime, mock.patch.object( + scale.time, "time", return_value=420 + ), mock.patch.object( + scale.time, "sleep" + ), mock.patch.object( + scale, "write_json" + ) as write, mock.patch.object( + scale, "write_report" + ), mock.patch.object(scale, "print", create=True): + datetime.now.return_value = clock + with self.assertRaisesRegex(RuntimeError, "fresh.*router"): + scale.main() + write.assert_not_called() if __name__ == "__main__": From 3415cadeacbd94a12c3caea070b4a1e124951489 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 20 Nov 2026 17:50:38 -0800 Subject: [PATCH 03/20] fixup! Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- docs/scale-testing.md | 17 +-- scripts/scale-test.py | 173 ++++++++++++++++++++++--------- scripts/tests/test_scale_test.py | 2 +- 3 files changed, 135 insertions(+), 57 deletions(-) diff --git a/docs/scale-testing.md b/docs/scale-testing.md index 749e028..d4212b8 100644 --- a/docs/scale-testing.md +++ b/docs/scale-testing.md @@ -8,7 +8,7 @@ description: Compare Lampyr with the same application in a Kubernetes Deployment The opt-in scale framework compares a Lampyr Service with the same Go application in a normal Kubernetes Deployment. It uses oha for client latency and throughput, and queries the optional observability add-on for platform -metrics. It does not run in CI. +metrics. The live comparison does not run in CI. Install the add-on and deploy the committed Go standalone example through Lampyr. Build and publish the normal Kubernetes image from the same source: @@ -32,7 +32,7 @@ just scale-test \ The default sweep runs each target for 30 seconds at concurrency 1, 4, 16, and 64. The framework: -- creates a temporary one-replica Kubernetes Deployment and Service; +- creates a temporary one-replica Deployment and Service with unique names; - warms both targets; - runs the same client against Lampyr and Kubernetes; - queries Prometheus for request, Fiber, CPU, and memory measurements; @@ -46,14 +46,19 @@ port-forward and stops if it exits, but the tunnel can still limit high concurrency results. This framework is for repeatable comparisons, not a claim that the two network paths have identical overhead. +The runner requires one baseline replica and a duration of at least 30 seconds. +Both targets use a 10-second request timeout, including warmup. Cleanup removes +only resources this run created. + The report calculates HTTP success from response status codes and transport errors. Its latency columns include only successful HTTP responses. Platform error and shed counts come from Lampyr metrics. The runner waits for a final -Prometheus scrape after each load interval. If needed, it waits for up to five -more scrape intervals so short smoke tests still have enough cAdvisor samples. -CPU measurements include that collection interval. +healthy Prometheus scrape from every router after each load interval. It can +wait for up to five more scrape intervals. Counter resets reject the scenario. +The measurement window includes the pre-load router scrape and the final +collection interval. Peak memory is the maximum combined usage at one time. -Use the Lampyr Platform Grafana dashboard while a run is active. The JSON +Use the Lampyr Platform Perses dashboard while a run is active. The JSON result remains the source for comparisons across commits or machines. It records the image digest, namespace, replica count, oha version, Git state, and a limited node summary without node addresses or machine identifiers. diff --git a/scripts/scale-test.py b/scripts/scale-test.py index e28c3a7..80537f2 100644 --- a/scripts/scale-test.py +++ b/scripts/scale-test.py @@ -14,9 +14,11 @@ import tempfile import time import urllib.parse +import uuid BASELINE = "lampyr-scale-baseline" +REQUEST_TIMEOUT = "10s" PROMETHEUS_PROXY = ( "/api/v1/namespaces/lampyr-observability/" "services/http:prometheus:9090/proxy/api/v1/query" @@ -62,7 +64,7 @@ def active_revision(context, service, namespace): return next(iter(revisions)) -def prometheus_query(context, query, evaluation_time=None): +def prometheus_results(context, query, evaluation_time=None): parameters = {"query": query} if evaluation_time is not None: parameters["time"] = f"{evaluation_time:.3f}" @@ -70,7 +72,11 @@ def prometheus_query(context, query, evaluation_time=None): result = json.loads(command("kubectl", "--context", context, "get", "--raw", path)) if result.get("status") != "success": raise RuntimeError(f"Prometheus query failed: {result}") - values = result["data"]["result"] + return result["data"]["result"] + + +def prometheus_query(context, query, evaluation_time=None): + values = prometheus_results(context, query, evaluation_time) if not values: return None if len(values) != 1: @@ -79,6 +85,24 @@ def prometheus_query(context, query, evaluation_time=None): return value if math.isfinite(value) else None +def router_scrapes(context, evaluation_time): + values = prometheus_results( + context, + 'timestamp(up{job="fiber-router"}) * (up{job="fiber-router"} == bool 1)', + evaluation_time, + ) + if not values: + raise RuntimeError("Prometheus router targets are missing") + scrapes = {} + for item in values: + timestamp = float(item["value"][1]) + if not math.isfinite(timestamp): + raise RuntimeError("Prometheus router scrape timestamp is not finite") + identity = tuple(sorted(item["metric"].items())) + scrapes[identity] = timestamp + return scrapes + + def metric_queries(namespace, revision, window, baseline, window_seconds=30): revision_match = f'namespace="{namespace}",revision="{revision}"' running_home = ( @@ -95,14 +119,35 @@ def metric_queries(namespace, revision, window, baseline, window_seconds=30): f'label_serving_knative_dev_revision="{revision}"}} {running_home})' ) baseline_pods = f'namespace="{namespace}",pod=~"{baseline}-.*"' - return { + counter_series = { "lampyrRequests": ( - "sum(lampyr_router_request_duration_seconds_count" - f"{{{revision_match}}})" + "lampyr_router_request_duration_seconds_count" + f"{{{revision_match}}}" ), "lampyrErrors": ( - "sum(lampyr_router_request_duration_seconds_count" - f'{{{revision_match},code!~"2..|3.."}})' + "lampyr_router_request_duration_seconds_count" + f'{{{revision_match},code!~"2..|3.."}}' + ), + "lampyrShed": f"lampyr_router_shed_total{{{revision_match}}}", + "lampyrRetries": f"lampyr_router_clone_retries_total{{{revision_match}}}", + } + router_memory = ( + "sum(container_memory_working_set_bytes" + '{namespace="lampyr-system",container="router"} ' + f"{running_router})" + ) + home_memory = ( + "sum(container_memory_working_set_bytes" + f'{{namespace="{namespace}",container="fiberd"}} {home})' + ) + return { + **{name: f"sum({series})" for name, series in counter_series.items()}, + **{ + f"{name}Resets": f"sum(resets({series}[{window}]))" + for name, series in counter_series.items() + }, + "lampyrMemoryBytes": ( + f"max_over_time((({router_memory}) + ({home_memory}))[{window}:5s])" ), "lampyrRequestP95Seconds": ( "histogram_quantile(0.95,sum by(le)(increase(" @@ -114,12 +159,6 @@ def metric_queries(namespace, revision, window, baseline, window_seconds=30): f"lampyr_router_fiber_acquire_seconds_bucket{{{revision_match}}}" f"[{window}])))" ), - "lampyrShed": ( - "sum(lampyr_router_shed_total" f"{{{revision_match}}})" - ), - "lampyrRetries": ( - "sum(lampyr_router_clone_retries_total" f"{{{revision_match}}})" - ), "lampyrPeakBusyFibers": ( "max_over_time((sum(lampyr_router_fibers_busy" f"{{{revision_match}}}))[{window}:5s])" @@ -136,10 +175,7 @@ def metric_queries(namespace, revision, window, baseline, window_seconds=30): f" / {window_seconds:.3f}" ), "lampyrRouterMemoryBytes": ( - "max_over_time((sum(container_memory_working_set_bytes" - '{namespace="lampyr-system",container="router"} ' - f"{running_router}))" - f"[{window}:5s])" + f"max_over_time(({router_memory})[{window}:5s])" ), "lampyrHomeCPU": ( "(sum(increase(container_cpu_usage_seconds_total" @@ -147,8 +183,7 @@ def metric_queries(namespace, revision, window, baseline, window_seconds=30): f"{home})) / {window_seconds:.3f}" ), "lampyrHomeMemoryBytes": ( - "max_over_time((sum(container_memory_working_set_bytes" - f'{{namespace="{namespace}",container="fiberd"}} {home}))[{window}:5s])' + f"max_over_time(({home_memory})[{window}:5s])" ), "baselineCPU": ( "sum(increase(container_cpu_usage_seconds_total" @@ -173,9 +208,9 @@ def metric_queries(namespace, revision, window, baseline, window_seconds=30): } -def counter_snapshot(context, queries): +def counter_snapshot(context, queries, evaluation_time=None): return { - name: prometheus_query(context, query) + name: prometheus_query(context, query, evaluation_time) for name, query in queries.items() if name in COUNTER_METRICS } @@ -183,8 +218,17 @@ def counter_snapshot(context, queries): def collect_metrics(context, queries, before, evaluation_time): collected = {} + reset_metrics = {f"{name}Resets": name for name in COUNTER_METRICS} for name, query in queries.items(): value = prometheus_query(context, query, evaluation_time) + if name in reset_metrics: + counter = reset_metrics[name] + if value is None and before[counter] is not None: + raise RuntimeError(f"Prometheus reset metrics are missing: {counter}") + if value is not None and value > 0: + raise RuntimeError(f"Prometheus counter reset during scenario: {counter}") + collected[name] = value + continue if name not in COUNTER_METRICS: collected[name] = value continue @@ -201,8 +245,8 @@ def collect_metrics(context, queries, before, evaluation_time): return collected -def baseline_manifest(image, replicas, namespace): - labels = {"app": BASELINE} +def baseline_manifest(image, replicas, namespace, name): + labels = {"app": name} return { "apiVersion": "v1", "kind": "List", @@ -210,7 +254,7 @@ def baseline_manifest(image, replicas, namespace): { "apiVersion": "apps/v1", "kind": "Deployment", - "metadata": {"name": BASELINE, "namespace": namespace}, + "metadata": {"name": name, "namespace": namespace}, "spec": { "replicas": replicas, "selector": {"matchLabels": labels}, @@ -254,7 +298,7 @@ def baseline_manifest(image, replicas, namespace): { "apiVersion": "v1", "kind": "Service", - "metadata": {"name": BASELINE, "namespace": namespace}, + "metadata": {"name": name, "namespace": namespace}, "spec": { "selector": labels, "ports": [{"name": "http", "port": 80, "targetPort": "http"}], @@ -284,10 +328,14 @@ def free_port(): def baseline_server(context, image, replicas, namespace): if "@sha256:" not in image: raise ValueError("baseline image must be digest-pinned") - manifest = baseline_manifest(image, replicas, namespace) + name = f"{BASELINE}-{uuid.uuid4().hex}" + manifest = baseline_manifest(image, replicas, namespace, name) + created = [] forward = None try: - kubectl_manifest(context, "apply", manifest) + for resource in manifest["items"]: + kubectl_manifest(context, "create", resource) + created.append(resource) subprocess.run( [ "kubectl", @@ -297,7 +345,7 @@ def baseline_server(context, image, replicas, namespace): namespace, "rollout", "status", - f"deployment/{BASELINE}", + f"deployment/{name}", "--timeout=300s", ], check=True, @@ -311,7 +359,7 @@ def baseline_server(context, image, replicas, namespace): "--namespace", namespace, "port-forward", - f"service/{BASELINE}", + f"service/{name}", f"{port}:80", ], stdout=subprocess.DEVNULL, @@ -327,7 +375,7 @@ def baseline_server(context, image, replicas, namespace): time.sleep(0.1) else: raise RuntimeError("baseline port-forward did not become ready") - yield {"url": f"http://127.0.0.1:{port}/", "process": forward} + yield {"name": name, "url": f"http://127.0.0.1:{port}/", "process": forward} finally: original_error = sys.exc_info()[0] is not None if forward is not None: @@ -337,14 +385,19 @@ def baseline_server(context, image, replicas, namespace): except subprocess.TimeoutExpired: forward.kill() forward.wait() - try: - kubectl_manifest( - context, "delete", manifest, "--ignore-not-found=true", "--wait=true" - ) - except subprocess.CalledProcessError as error: - if not original_error: - raise - print(f"warning: baseline cleanup failed: {error}", file=sys.stderr) + if created: + try: + kubectl_manifest( + context, + "delete", + {"apiVersion": "v1", "kind": "List", "items": created}, + "--ignore-not-found=true", + "--wait=true", + ) + except subprocess.CalledProcessError as error: + if not original_error: + raise + print(f"warning: baseline cleanup failed: {error}", file=sys.stderr) def require_running(process, name): @@ -361,6 +414,8 @@ def run_oha(oha, url, duration, concurrency): duration, "-c", str(concurrency), + "-t", + REQUEST_TIMEOUT, "--wait-ongoing-requests-after-deadline", "--stats-success-breakdown", "--no-tui", @@ -370,6 +425,7 @@ def run_oha(oha, url, duration, concurrency): url, ], text=True, + timeout=duration_seconds(duration) + duration_seconds(REQUEST_TIMEOUT) + 5, ) result = json.loads(output) client = { @@ -406,6 +462,8 @@ def warm_target(oha, url): "20", "-c", "1", + "-t", + REQUEST_TIMEOUT, "--stats-success-breakdown", "--no-tui", "--output-format", @@ -414,6 +472,7 @@ def warm_target(oha, url): url, ], text=True, + timeout=20 * duration_seconds(REQUEST_TIMEOUT) + 5, ) client = json.loads(output) if http_success_rate(client) != 1: @@ -443,6 +502,7 @@ def target_resource_names(target): "lampyrHomeCPU", "lampyrRouterMemoryBytes", "lampyrHomeMemoryBytes", + "lampyrMemoryBytes", ) return ("baselineCPU", "baselineMemoryBytes") @@ -494,10 +554,7 @@ def write_report(result, path): cpu = add_metrics( metrics["lampyrRouterCPU"], metrics["lampyrHomeCPU"] ) - memory = add_metrics( - metrics["lampyrRouterMemoryBytes"], - metrics["lampyrHomeMemoryBytes"], - ) + memory = metrics.get("lampyrMemoryBytes") errors = metrics.get("lampyrErrors") shed = metrics.get("lampyrShed") else: @@ -575,12 +632,14 @@ def main(): args = parser.parse_args() seconds = duration_seconds(args.duration) + if seconds < 30: + raise ValueError("duration must be at least 30s to measure CPU across scrapes") concurrencies = [int(value) for value in args.concurrency.split(",")] if not concurrencies or any(value < 1 for value in concurrencies): raise ValueError("concurrency values must be positive integers") - if args.baseline_replicas < 1: - raise ValueError("baseline replicas must be a positive integer") - oha = Path(args.oha) + if args.baseline_replicas != 1: + raise ValueError("baseline must use one replica with Service port-forward") + oha = Path(args.oha).resolve() if not oha.is_file(): raise FileNotFoundError(f"load generator not found: {oha}") revision = active_revision(args.context, args.service, args.namespace) @@ -595,6 +654,7 @@ def main(): "baselineImage": args.baseline_image, "baselineReplicas": args.baseline_replicas, "duration": args.duration, + "requestTimeout": REQUEST_TIMEOUT, "concurrency": concurrencies, "commit": command("git", "rev-parse", "HEAD"), "dirty": bool(command("git", "status", "--porcelain")), @@ -622,6 +682,7 @@ def main(): with baseline_server( args.context, args.baseline_image, args.baseline_replicas, args.namespace ) as baseline: + metadata["baselineName"] = baseline["name"] for target, url in [ ("lampyr", args.lampyr_url), ("kubernetes", baseline["url"]), @@ -638,9 +699,14 @@ def main(): if target == "kubernetes": require_running(baseline["process"], "baseline port-forward") snapshot_queries = metric_queries( - args.namespace, revision, "1s", BASELINE, 1 + args.namespace, revision, "1s", baseline["name"], 1 ) - before = counter_snapshot(args.context, snapshot_queries) + snapshot_time = time.time() + before_scrapes = router_scrapes(args.context, snapshot_time) + if any(timestamp <= 0 for timestamp in before_scrapes.values()): + raise RuntimeError("Prometheus router targets are not healthy") + measurement_started = min(before_scrapes.values()) - 0.001 + before = counter_snapshot(args.context, snapshot_queries, snapshot_time) if before["lampyrRequests"] is None: raise RuntimeError( "Lampyr request metrics are missing after warmup; check the " @@ -655,13 +721,19 @@ def main(): for wait_seconds in (6, 5, 5, 5, 5, 5): time.sleep(wait_seconds) evaluated = time.time() - measured_seconds = evaluated - started.timestamp() + scrapes = router_scrapes(args.context, evaluated) + if scrapes.keys() != before_scrapes.keys() or any( + timestamp < load_ended.timestamp() + for timestamp in scrapes.values() + ): + continue + measured_seconds = evaluated - measurement_started window = f"{math.ceil(measured_seconds * 1000)}ms" queries = metric_queries( args.namespace, revision, window, - BASELINE, + baseline["name"], measured_seconds, ) resources = { @@ -677,7 +749,8 @@ def main(): break else: raise RuntimeError( - f"Prometheus did not collect CPU and memory metrics for {target}" + f"Prometheus did not collect fresh post-load router scrapes " + f"and CPU and memory metrics for {target}" ) scenario = { "target": target, diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index 42596fb..b3290c3 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -255,7 +255,7 @@ def test_target_resources_require_cpu_and_memory(self): def test_baseline_manifest_uses_restricted_pod_security(self): manifest = scale.baseline_manifest( - "example.test/baseline@sha256:abc", 1, "team-a" + "example.test/baseline@sha256:abc", 1, "team-a", "baseline-owned" ) deployment = manifest["items"][0] pod = deployment["spec"]["template"]["spec"] From f5c90b7e63f95360d5ee0e1b295c9d95483851d7 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 20 Nov 2026 18:07:10 -0800 Subject: [PATCH 04/20] fixup! Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- scripts/tests/test_scale_test.py | 126 +++++++++++++++++++++++++++++-- 1 file changed, 121 insertions(+), 5 deletions(-) diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index b3290c3..956adaa 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -1,4 +1,5 @@ import contextlib +import hashlib import importlib.util import json import os @@ -381,6 +382,8 @@ def test_main_rejects_multiple_baseline_replicas_and_short_cpu_windows(self): for arguments, message in ( (("--baseline-replicas", "2"), "one replica"), (("--duration", "1s"), "at least 30"), + (("--output", "results.md"), "JSON and Markdown"), + (("--output", "results.MD"), "JSON and Markdown"), ): with self.subTest(arguments=arguments), mock.patch.object( scale.sys, "argv", self.main_arguments(*arguments) @@ -423,7 +426,8 @@ def metadata_command(*arguments): ) self.assertEqual(version[0], str(executable)) - def test_scenario_waits_for_every_router_post_load_scrape(self): + @contextlib.contextmanager + def scenario_environment(self, routers, resources): clock = scale.datetime.datetime.fromtimestamp(400, scale.datetime.timezone.utc) baseline = { "name": "baseline-owned", @@ -448,11 +452,12 @@ def test_scenario_waits_for_every_router_post_load_scrape(self): ), mock.patch.object( scale, "run_oha", return_value=client ), mock.patch.object( - scale, "prometheus_query", return_value=1 + scale, "prometheus_query", + side_effect=lambda context, query, evaluation_time=None: 0 if "resets(" in query else 1, + ), mock.patch.object( + scale, "router_scrapes", side_effect=routers, ), mock.patch.object( - scale, "router_scrapes", create=True, - side_effect=[{"router-1": 399, "router-2": 399}] - + [{"router-1": 420, "router-2": 399}] * 6, + scale, "resource_samples", create=True, side_effect=resources, ), mock.patch.object( scale.datetime, "datetime", wraps=scale.datetime.datetime ) as datetime, mock.patch.object( @@ -465,10 +470,121 @@ def test_scenario_waits_for_every_router_post_load_scrape(self): scale, "write_report" ), mock.patch.object(scale, "print", create=True): datetime.now.return_value = clock + yield write + + def test_scenario_waits_for_every_router_post_load_scrape(self): + routers = [{"router-1": 400, "router-2": 400}] + routers += [{"router-1": 420, "router-2": 399}] * 6 + resources = [{"cadvisor": 400, "kube-state": 400}] + resources += [{"cadvisor": 420, "kube-state": 420}] * 6 + with self.scenario_environment(routers, resources) as write: with self.assertRaisesRegex(RuntimeError, "fresh.*router"): scale.main() write.assert_not_called() + def test_scenario_rejects_stale_resource_samples(self): + for source in ("cadvisor", "kube-state"): + before = {"cadvisor": 400, "kube-state": 400} + after = {"cadvisor": 420, "kube-state": 420} + after[source] = 399 + routers = [{"router-1": 400}] + [{"router-1": 420}] * 20 + resources = [before] + [after] * 20 + with self.subTest(source=source), self.scenario_environment( + routers, resources + ) as write: + with self.assertRaisesRegex(RuntimeError, "fresh.*resource"): + scale.main() + write.assert_not_called() + + def test_installer_uses_unique_downloads_for_concurrent_invocations(self): + justfile = (PATH.parents[1] / "Justfile").read_text() + recipe = justfile.split("\ninstall-oha:\n", 1)[1].split("\n\n", 1)[0] + checksums = scale.re.findall(r"[0-9a-f]{64}", recipe) + self.assertEqual(len(checksums), 1) + payload = b"#!/bin/sh\necho 'oha 1.17.0'\n" + digest = hashlib.sha256(payload).hexdigest() + recipe = recipe.replace(checksums[0], digest) + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + bin_path = root / "bin" + bin_path.mkdir() + (root / "payload").write_bytes(payload) + (root / "Justfile").write_text( + 'set shell := ["bash", "-euo", "pipefail", "-c"]\n' + 'repo-root := justfile_directory()\noha-version := "1.17.0"\n' + f"install-oha:\n{recipe}\n" + ) + scripts = { + "uname": "#!/bin/sh\necho 'Linux x86_64'\n", + "sha256sum": ( + "#!/usr/bin/env python3\n" + "import hashlib, pathlib, sys\n" + "expected, filename = sys.stdin.read().strip().split(' ', 1)\n" + "try:\n" + " actual = hashlib.sha256(pathlib.Path(filename).read_bytes()).hexdigest()\n" + "except OSError:\n" + " print('checksum input missing', file=sys.stderr)\n" + " sys.exit(1)\n" + "sys.exit(0 if actual == expected else 1)\n" + ), + "curl": ( + "#!/bin/bash\nset -euo pipefail\n" + "while (($#)); do\n" + " if [[ $1 == --output ]]; then output=$2; shift 2; else shift; fi\n" + "done\n" + 'cp "$TEST_ROOT/payload" "$output"\n' + "wait_for() {\n" + ' for ((i=0; i<500; i++)); do [[ -e $1 ]] && return 0; sleep 0.01; done\n' + " return 1\n" + "}\n" + 'if [[ $TEST_INSTALLER_ID == first ]]; then\n' + ' touch "$TEST_ROOT/first"\n' + ' wait_for "$TEST_ROOT/second"\n' + "else\n" + ' touch "$TEST_ROOT/second"\n' + ' wait_for "$TEST_ROOT/build/tools/oha"\n' + "fi\n" + ), + } + for name, content in scripts.items(): + executable = bin_path / name + executable.write_text(content) + executable.chmod(0o755) + environment = { + **os.environ, + "PATH": f"{bin_path}{os.pathsep}{os.environ['PATH']}", + "TEST_ROOT": str(root), + } + processes = [] + try: + for identifier in ("first", "second"): + processes.append(scale.subprocess.Popen( + ["just", "--justfile", str(root / "Justfile"), "install-oha"], + cwd=root, + env={**environment, "TEST_INSTALLER_ID": identifier}, + stdout=scale.subprocess.PIPE, + stderr=scale.subprocess.PIPE, + text=True, + )) + if identifier == "first": + deadline = scale.time.monotonic() + 5 + while not (root / "first").exists(): + self.assertLess(scale.time.monotonic(), deadline) + scale.time.sleep(0.01) + for process in processes: + stdout, stderr = process.communicate(timeout=10) + self.assertEqual(process.returncode, 0, stdout + stderr) + self.assertEqual((root / "build/tools/oha").read_bytes(), payload) + finally: + for process in processes: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=3) + except scale.subprocess.TimeoutExpired: + process.kill() + process.wait() + if __name__ == "__main__": unittest.main() From df0485994d10ab3a6659a93be4a3eeb4cb689ead Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 20 Nov 2026 18:19:35 -0800 Subject: [PATCH 05/20] fixup! Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- Justfile | 10 +- docs/scale-testing.md | 12 +- scripts/scale-test.py | 209 +++++++++++++++++++++---------- scripts/tests/test_scale_test.py | 32 +++++ 4 files changed, 190 insertions(+), 73 deletions(-) diff --git a/Justfile b/Justfile index 5a89dca..3a22da8 100644 --- a/Justfile +++ b/Justfile @@ -212,11 +212,13 @@ install-oha: [ "$("{{repo-root}}/build/tools/oha" --version)" = "oha {{oha-version}}" ]; then exit 0; fi; \ [ "$(uname -sm)" = "Linux x86_64" ] || { echo "install-oha supports linux-amd64 only" >&2; exit 1; }; \ mkdir -p "{{repo-root}}/build/tools"; \ - curl --fail --silent --show-error --location --output "{{repo-root}}/build/tools/oha.tmp" \ + temporary=$(mktemp "{{repo-root}}/build/tools/oha.XXXXXXXX"); \ + trap 'rm -f "$temporary"' EXIT; \ + curl --fail --silent --show-error --location --output "$temporary" \ "https://github.com/hatoo/oha/releases/download/v{{oha-version}}/oha-linux-amd64"; \ - echo "85c6eb98066b8c8bd513b2dd96fafd8f9863249ea653606bae1ca2e3a75c43d2 {{repo-root}}/build/tools/oha.tmp" | sha256sum --check; \ - chmod 0755 "{{repo-root}}/build/tools/oha.tmp"; \ - mv "{{repo-root}}/build/tools/oha.tmp" "{{repo-root}}/build/tools/oha" + echo "85c6eb98066b8c8bd513b2dd96fafd8f9863249ea653606bae1ca2e3a75c43d2 $temporary" | sha256sum --check; \ + chmod 0755 "$temporary"; \ + mv "$temporary" "{{repo-root}}/build/tools/oha" prepare-workspace: build-ly if [[ ! -f build/workspace/lampyr.workspace.yaml ]]; then build/ly scaffold workspace build/workspace; fi diff --git a/docs/scale-testing.md b/docs/scale-testing.md index d4212b8..8d5641e 100644 --- a/docs/scale-testing.md +++ b/docs/scale-testing.md @@ -49,14 +49,18 @@ that the two network paths have identical overhead. The runner requires one baseline replica and a duration of at least 30 seconds. Both targets use a 10-second request timeout, including warmup. Cleanup removes only resources this run created. +Custom JSON output names must not use the `.md` extension. The report calculates HTTP success from response status codes and transport errors. Its latency columns include only successful HTTP responses. Platform error and shed counts come from Lampyr metrics. The runner waits for a final -healthy Prometheus scrape from every router after each load interval. It can -wait for up to five more scrape intervals. Counter resets reject the scenario. -The measurement window includes the pre-load router scrape and the final -collection interval. Peak memory is the maximum combined usage at one time. +healthy Prometheus scrape from every router after each load interval. It also +requires fresh cAdvisor samples from the measured containers and fresh +kube-state-metrics inputs. Missing or changed input series reject the scenario. +It can wait for up to five more scrape intervals. Counter resets reject the +scenario. The measurement window includes the pre-load router and resource +samples after warmup, and the final collection interval. Peak memory is the +maximum combined usage at one time. Use the Lampyr Platform Perses dashboard while a run is active. The JSON result remains the source for comparisons across commits or machines. It diff --git a/scripts/scale-test.py b/scripts/scale-test.py index 80537f2..1266135 100644 --- a/scripts/scale-test.py +++ b/scripts/scale-test.py @@ -103,22 +103,100 @@ def router_scrapes(context, evaluation_time): return scrapes +def resource_inputs(namespace, revision, baseline): + baseline_pods = f'namespace="{namespace}",pod=~"{baseline}-.*"' + phase = f'kube_pod_status_phase{{namespace="{namespace}",phase="Running"}}' + return { + "lampyrRouter": { + "cpu": 'container_cpu_usage_seconds_total{namespace="lampyr-system",container="router"}', + "memory": 'container_memory_working_set_bytes{namespace="lampyr-system",container="router"}', + "phase": 'kube_pod_status_phase{namespace="lampyr-system",phase="Running"}', + }, + "lampyrHome": { + "cpu": f'container_cpu_usage_seconds_total{{namespace="{namespace}",container="fiberd"}}', + "memory": f'container_memory_working_set_bytes{{namespace="{namespace}",container="fiberd"}}', + "phase": phase, + "labels": ( + f'kube_pod_labels{{namespace="{namespace}",label_lampyr_dev_home="true",' + f'label_serving_knative_dev_revision="{revision}"}}' + ), + }, + "baseline": { + "cpu": f'container_cpu_usage_seconds_total{{{baseline_pods},container="app"}}', + "memory": f'container_memory_working_set_bytes{{{baseline_pods},container="app"}}', + "phase": phase, + }, + } + + +def selected_resource(selector, inputs): + membership = f'({inputs["phase"]} == 1)' + if "labels" in inputs: + membership = ( + f'({inputs["labels"]} * on(namespace,pod) group_left() {membership})' + ) + return f"{selector} * on(namespace,pod) group_left() {membership}" + + +def resource_sample_queries(namespace, revision, baseline, target): + inputs = resource_inputs(namespace, revision, baseline) + prefixes = { + "lampyr": ("lampyrRouter", "lampyrHome"), + "kubernetes": ("baseline",), + }[target] + queries = { + "kubeState": ( + 'timestamp(up{job="kube-state-metrics"}) ' + '* (up{job="kube-state-metrics"} == bool 1)' + ), + } + for prefix in prefixes: + resource = inputs[prefix] + selected_cpu = selected_resource(resource["cpu"], resource) + selected_memory = selected_resource(resource["memory"], resource) + selected = f"({selected_cpu}) or ({selected_memory})" + pods = f"group by(namespace,pod) ({selected})" + nodes = f"group by(job,instance,node) ({selected})" + for kind in ("cpu", "memory"): + queries[f"{prefix}{kind.title()}"] = selected_resource( + f'timestamp({resource[kind]})', resource + ) + for kind in ("phase", "labels"): + if kind in resource: + queries[f"{prefix}{kind.title()}"] = ( + f'timestamp({resource[kind]}) ' + f"* on(namespace,pod) group_left() ({pods})" + ) + queries[f"{prefix}Cadvisor"] = ( + 'timestamp(up{job="kubernetes-cadvisor"}) ' + '* (up{job="kubernetes-cadvisor"} == bool 1) ' + f"and on(job,instance,node) ({nodes})" + ) + return queries + + +def resource_samples(context, queries, evaluation_time): + query = " or ".join( + f'label_replace(({expression}), "scale_input", "{name}", "", "")' + for name, expression in queries.items() + ) + values = prometheus_results(context, query, evaluation_time) + samples = {} + sources = set() + for item in values: + source = item["metric"].get("scale_input") + if source not in queries: + raise RuntimeError(f"Prometheus returned an unknown resource input: {source}") + timestamp = float(item["value"][1]) + if not math.isfinite(timestamp): + raise RuntimeError("Prometheus resource sample timestamp is not finite") + sources.add(source) + samples[tuple(sorted(item["metric"].items()))] = timestamp + return samples if sources == queries.keys() else None + + def metric_queries(namespace, revision, window, baseline, window_seconds=30): revision_match = f'namespace="{namespace}",revision="{revision}"' - running_home = ( - '* on(namespace,pod) group_left() ' - f'(kube_pod_status_phase{{namespace="{namespace}",phase="Running"}} == 1)' - ) - running_router = ( - '* on(namespace,pod) group_left() ' - '(kube_pod_status_phase{namespace="lampyr-system",phase="Running"} == 1)' - ) - home = ( - '* on(namespace,pod) group_left() ' - f'(kube_pod_labels{{namespace="{namespace}",label_lampyr_dev_home="true",' - f'label_serving_knative_dev_revision="{revision}"}} {running_home})' - ) - baseline_pods = f'namespace="{namespace}",pod=~"{baseline}-.*"' counter_series = { "lampyrRequests": ( "lampyr_router_request_duration_seconds_count" @@ -131,24 +209,12 @@ def metric_queries(namespace, revision, window, baseline, window_seconds=30): "lampyrShed": f"lampyr_router_shed_total{{{revision_match}}}", "lampyrRetries": f"lampyr_router_clone_retries_total{{{revision_match}}}", } - router_memory = ( - "sum(container_memory_working_set_bytes" - '{namespace="lampyr-system",container="router"} ' - f"{running_router})" - ) - home_memory = ( - "sum(container_memory_working_set_bytes" - f'{{namespace="{namespace}",container="fiberd"}} {home})' - ) - return { + queries = { **{name: f"sum({series})" for name, series in counter_series.items()}, **{ f"{name}Resets": f"sum(resets({series}[{window}]))" for name, series in counter_series.items() }, - "lampyrMemoryBytes": ( - f"max_over_time((({router_memory}) + ({home_memory}))[{window}:5s])" - ), "lampyrRequestP95Seconds": ( "histogram_quantile(0.95,sum by(le)(increase(" f"lampyr_router_request_duration_seconds_bucket{{{revision_match}}}" @@ -167,37 +233,20 @@ def metric_queries(namespace, revision, window, baseline, window_seconds=30): "max_over_time((sum(lampyr_router_requests_in_flight" f"{{{revision_match}}}))[{window}:5s])" ), - "lampyrRouterCPU": ( - "sum(increase(container_cpu_usage_seconds_total" - f'{{namespace="lampyr-system",container="router"}}[{window}])' - f" {running_router}" - ")" - f" / {window_seconds:.3f}" - ), - "lampyrRouterMemoryBytes": ( - f"max_over_time(({router_memory})[{window}:5s])" - ), - "lampyrHomeCPU": ( - "(sum(increase(container_cpu_usage_seconds_total" - f'{{namespace="{namespace}",container="fiberd"}}[{window}]) ' - f"{home})) / {window_seconds:.3f}" - ), - "lampyrHomeMemoryBytes": ( - f"max_over_time(({home_memory})[{window}:5s])" - ), - "baselineCPU": ( - "sum(increase(container_cpu_usage_seconds_total" - f"{{{baseline_pods},container=\"app\"}}[{window}])" - f" {running_home}" - ")" - f" / {window_seconds:.3f}" - ), - "baselineMemoryBytes": ( - "max_over_time((sum(container_memory_working_set_bytes" - f"{{{baseline_pods},container=\"app\"}} {running_home}))" - f"[{window}:5s])" - ), } + memory = {} + for prefix, resource in resource_inputs(namespace, revision, baseline).items(): + cpu = selected_resource(f'increase({resource["cpu"]}[{window}])', resource) + memory[prefix] = f'sum({selected_resource(resource["memory"], resource)})' + queries[f"{prefix}CPU"] = f"sum({cpu}) / {window_seconds:.3f}" + queries[f"{prefix}MemoryBytes"] = ( + f"max_over_time(({memory[prefix]})[{window}:5s])" + ) + queries["lampyrMemoryBytes"] = ( + f'max_over_time((({memory["lampyrRouter"]}) + ' + f'({memory["lampyrHome"]}))[{window}:5s])' + ) + return queries COUNTER_METRICS = { @@ -639,11 +688,13 @@ def main(): raise ValueError("concurrency values must be positive integers") if args.baseline_replicas != 1: raise ValueError("baseline must use one replica with Service port-forward") + output = Path(args.output) + if output.suffix.lower() == ".md": + raise ValueError("JSON and Markdown output files must be distinct; do not use .md") oha = Path(args.oha).resolve() if not oha.is_file(): raise FileNotFoundError(f"load generator not found: {oha}") revision = active_revision(args.context, args.service, args.namespace) - output = Path(args.output) output.parent.mkdir(parents=True, exist_ok=True) metadata = { "context": args.context, @@ -690,6 +741,7 @@ def main(): if target == "kubernetes": require_running(baseline["process"], "baseline port-forward") warm_target(oha, url) + warmup_ended = datetime.datetime.now(datetime.timezone.utc).timestamp() time.sleep(6) for concurrency in concurrencies: for target, url in [ @@ -701,11 +753,32 @@ def main(): snapshot_queries = metric_queries( args.namespace, revision, "1s", baseline["name"], 1 ) - snapshot_time = time.time() - before_scrapes = router_scrapes(args.context, snapshot_time) - if any(timestamp <= 0 for timestamp in before_scrapes.values()): - raise RuntimeError("Prometheus router targets are not healthy") - measurement_started = min(before_scrapes.values()) - 0.001 + sample_queries = resource_sample_queries( + args.namespace, revision, baseline["name"], target + ) + for wait_seconds in (0, 5, 5, 5, 5, 5, 5): + if wait_seconds: + time.sleep(wait_seconds) + snapshot_time = time.time() + before_scrapes = router_scrapes(args.context, snapshot_time) + before_resources = resource_samples( + args.context, sample_queries, snapshot_time + ) + if before_resources is not None and all( + timestamp >= warmup_ended + for timestamp in ( + *before_scrapes.values(), *before_resources.values() + ) + ): + break + else: + raise RuntimeError( + f"Prometheus did not collect fresh pre-load router and " + f"resource samples for {target}" + ) + measurement_started = min( + *before_scrapes.values(), *before_resources.values() + ) - 0.001 before = counter_snapshot(args.context, snapshot_queries, snapshot_time) if before["lampyrRequests"] is None: raise RuntimeError( @@ -727,6 +800,12 @@ def main(): for timestamp in scrapes.values() ): continue + samples = resource_samples(args.context, sample_queries, evaluated) + if samples is None or samples.keys() != before_resources.keys() or any( + timestamp < load_ended.timestamp() + for timestamp in samples.values() + ): + continue measured_seconds = evaluated - measurement_started window = f"{math.ceil(measured_seconds * 1000)}ms" queries = metric_queries( @@ -749,8 +828,8 @@ def main(): break else: raise RuntimeError( - f"Prometheus did not collect fresh post-load router scrapes " - f"and CPU and memory metrics for {target}" + f"Prometheus did not collect fresh post-load router and " + f"resource samples with CPU and memory metrics for {target}" ) scenario = { "target": target, diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index 956adaa..725915e 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -496,6 +496,38 @@ def test_scenario_rejects_stale_resource_samples(self): scale.main() write.assert_not_called() + def test_scenario_rejects_disappeared_resource_series(self): + routers = [{"router-1": 420}] * 20 + resources = [{"container-1": 400, "container-2": 400}] + resources += [{"container-1": 420}] * 20 + with self.scenario_environment(routers, resources) as write: + with self.assertRaisesRegex(RuntimeError, "fresh.*resource"): + scale.main() + write.assert_not_called() + + def test_scenario_accepts_fresh_resource_samples(self): + with self.scenario_environment( + [{"router-1": 420}] * 20, + [{"container-1": 420, "kube-state": 420}] * 20, + ) as write: + scale.main() + self.assertEqual(len(write.call_args.args[0]["scenarios"]), 2) + + def test_resource_samples_require_every_input_family(self): + queries = {"cpu": "cpu_timestamp", "phase": "phase_timestamp"} + complete = [ + {"metric": {"scale_input": "cpu", "pod": "one"}, "value": [450, "420"]}, + {"metric": {"scale_input": "phase", "pod": "one"}, "value": [450, "410"]}, + ] + with mock.patch.object(scale, "prometheus_results", return_value=complete): + samples = scale.resource_samples("context", queries, 450) + self.assertEqual(sorted(samples.values()), [410, 420]) + for partial in ([], complete[:1]): + with self.subTest(partial=partial), mock.patch.object( + scale, "prometheus_results", return_value=partial + ): + self.assertIsNone(scale.resource_samples("context", queries, 450)) + def test_installer_uses_unique_downloads_for_concurrent_invocations(self): justfile = (PATH.parents[1] / "Justfile").read_text() recipe = justfile.split("\ninstall-oha:\n", 1)[1].split("\n\n", 1)[0] From e7a39e85e0375ff4a46b85d589692febfe3c289e Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 20 Nov 2026 18:20:12 -0800 Subject: [PATCH 06/20] fixup! Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- scripts/tests/test_scale_test.py | 43 ++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index 725915e..ad1782b 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -528,6 +528,49 @@ def test_resource_samples_require_every_input_family(self): ): self.assertIsNone(scale.resource_samples("context", queries, 450)) + def test_resource_samples_require_cpu_and_memory_for_each_container(self): + queries = { + "routersCpu": "cpu_timestamp", + "routersMemory": "memory_timestamp", + "routersPhase": "phase_timestamp", + } + complete = [] + for number in (1, 2): + labels = { + "namespace": "lampyr-system", "pod": f"router-{number}", + "container": "router", "id": f"/container-{number}", + "job": "kubernetes-cadvisor", "instance": f"node-{number}:10250", + "node": f"node-{number}", + } + for source in queries: + metric = {**labels, "scale_input": source} + if source == "routersCpu": + metric["cpu"] = "total" + complete.append({"metric": metric, "value": [450, "420"]}) + with mock.patch.object(scale, "prometheus_results", return_value=complete): + self.assertIsNotNone(scale.resource_samples("context", queries, 450)) + for missing in ("routersCpu", "routersMemory"): + partial = [ + item for item in complete + if not ( + item["metric"]["scale_input"] == missing + and item["metric"]["pod"] == "router-2" + ) + ] + with self.subTest(missing=missing), mock.patch.object( + scale, "prometheus_results", return_value=partial + ): + self.assertIsNone(scale.resource_samples("context", queries, 450)) + mismatched = [ + { + **item, + "metric": {**item["metric"], "id": "/different-container"}, + } if item["metric"]["scale_input"] == "routersCpu" else item + for item in complete + ] + with mock.patch.object(scale, "prometheus_results", return_value=mismatched): + self.assertIsNone(scale.resource_samples("context", queries, 450)) + def test_installer_uses_unique_downloads_for_concurrent_invocations(self): justfile = (PATH.parents[1] / "Justfile").read_text() recipe = justfile.split("\ninstall-oha:\n", 1)[1].split("\n\n", 1)[0] From 8cfae5f1eb0b16b2ea58183dd775e22b559e03c7 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 20 Nov 2026 18:30:11 -0800 Subject: [PATCH 07/20] fixup! Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- scripts/scale-test.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/scripts/scale-test.py b/scripts/scale-test.py index 1266135..e430dbc 100644 --- a/scripts/scale-test.py +++ b/scripts/scale-test.py @@ -183,6 +183,7 @@ def resource_samples(context, queries, evaluation_time): values = prometheus_results(context, query, evaluation_time) samples = {} sources = set() + containers = {} for item in values: source = item["metric"].get("scale_input") if source not in queries: @@ -192,7 +193,19 @@ def resource_samples(context, queries, evaluation_time): raise RuntimeError("Prometheus resource sample timestamp is not finite") sources.add(source) samples[tuple(sorted(item["metric"].items()))] = timestamp - return samples if sources == queries.keys() else None + identity = tuple(sorted( + (label, value) for label, value in item["metric"].items() + if label not in {"scale_input", "__name__", "cpu"} + )) + containers.setdefault(source, set()).add(identity) + if sources != queries.keys(): + return None + for source in queries: + if source.endswith("Cpu"): + memory = source.removesuffix("Cpu") + "Memory" + if containers[source] != containers[memory]: + return None + return samples def metric_queries(namespace, revision, window, baseline, window_seconds=30): From 113b7babb8c0378a00d203c12f9b07d918535572 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 20 Nov 2026 18:32:42 -0800 Subject: [PATCH 08/20] fixup! Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- scripts/tests/test_scale_test.py | 43 ++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index ad1782b..3d33014 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -427,7 +427,7 @@ def metadata_command(*arguments): self.assertEqual(version[0], str(executable)) @contextlib.contextmanager - def scenario_environment(self, routers, resources): + def scenario_environment(self, routers, resources, inventory=None): clock = scale.datetime.datetime.fromtimestamp(400, scale.datetime.timezone.utc) baseline = { "name": "baseline-owned", @@ -439,6 +439,10 @@ def scenario_environment(self, routers, resources): "httpSuccessRate": 1, "successfulLatencyMs": {"p95": 1}, } + coverage = ( + contextlib.nullcontext() if inventory is not None else + mock.patch.object(scale, "resource_coverage", create=True, return_value=True) + ) with mock.patch.object( scale.sys, "argv", self.main_arguments() ), mock.patch.object( @@ -458,6 +462,8 @@ def scenario_environment(self, routers, resources): scale, "router_scrapes", side_effect=routers, ), mock.patch.object( scale, "resource_samples", create=True, side_effect=resources, + ), mock.patch.object( + scale, "resource_inventory", create=True, return_value=inventory or {}, ), mock.patch.object( scale.datetime, "datetime", wraps=scale.datetime.datetime ) as datetime, mock.patch.object( @@ -468,7 +474,7 @@ def scenario_environment(self, routers, resources): scale, "write_json" ) as write, mock.patch.object( scale, "write_report" - ), mock.patch.object(scale, "print", create=True): + ), mock.patch.object(scale, "print", create=True), coverage: datetime.now.return_value = clock yield write @@ -513,6 +519,39 @@ def test_scenario_accepts_fresh_resource_samples(self): scale.main() self.assertEqual(len(write.call_args.args[0]["scenarios"]), 2) + def test_scenario_rejects_missing_router_membership_at_both_endpoints(self): + inventory = { + "lampyrRouter": { + ("lampyr-system", "router-1"), ("lampyr-system", "router-2"), + }, + "lampyrHome": {("team-a", "home-1")}, + } + queries = scale.resource_sample_queries( + "team-a", "demo-00001", "baseline-owned", "lampyr" + ) + for missing in ("membership", "router-target"): + samples = {} + for source in queries: + pods = ( + [("lampyr-system", f"router-{number}") for number in ( + (1,) if missing == "membership" else (1, 2) + )] if source.startswith("lampyrRouter") + else [("team-a", "home-1")] + ) + for namespace, pod in pods: + labels = {"scale_input": source, "namespace": namespace, "pod": pod} + samples[tuple(sorted(labels.items()))] = 420 + routers = { + (("pod", f"router-{number}"),): 420 + for number in ((1, 2) if missing == "membership" else (1,)) + } + with self.subTest(missing=missing), self.scenario_environment( + [routers] * 20, [samples] * 20, inventory, + ) as write: + with self.assertRaisesRegex(RuntimeError, "fresh.*resource"): + scale.main() + write.assert_not_called() + def test_resource_samples_require_every_input_family(self): queries = {"cpu": "cpu_timestamp", "phase": "phase_timestamp"} complete = [ From 82393a52b6c360bf72217d71f77dee911ea2a803 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 20 Nov 2026 18:41:56 -0800 Subject: [PATCH 09/20] fixup! Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- docs/scale-testing.md | 2 + scripts/scale-test.py | 72 ++++++++++++++++++++++++++++++-- scripts/tests/test_scale_test.py | 59 ++++++++++++++++++++++++++ 3 files changed, 129 insertions(+), 4 deletions(-) diff --git a/docs/scale-testing.md b/docs/scale-testing.md index 8d5641e..841cabe 100644 --- a/docs/scale-testing.md +++ b/docs/scale-testing.md @@ -50,6 +50,7 @@ The runner requires one baseline replica and a duration of at least 30 seconds. Both targets use a 10-second request timeout, including warmup. Cleanup removes only resources this run created. Custom JSON output names must not use the `.md` extension. +The context must allow read access to the measured Pods. The report calculates HTTP success from response status codes and transport errors. Its latency columns include only successful HTTP responses. Platform @@ -57,6 +58,7 @@ error and shed counts come from Lampyr metrics. The runner waits for a final healthy Prometheus scrape from every router after each load interval. It also requires fresh cAdvisor samples from the measured containers and fresh kube-state-metrics inputs. Missing or changed input series reject the scenario. +Coverage must match the running Pods from the Kubernetes API. It can wait for up to five more scrape intervals. Counter resets reject the scenario. The measurement window includes the pre-load router and resource samples after warmup, and the final collection interval. Peak memory is the diff --git a/scripts/scale-test.py b/scripts/scale-test.py index e430dbc..99c1e52 100644 --- a/scripts/scale-test.py +++ b/scripts/scale-test.py @@ -108,11 +108,15 @@ def resource_inputs(namespace, revision, baseline): phase = f'kube_pod_status_phase{{namespace="{namespace}",phase="Running"}}' return { "lampyrRouter": { + "namespace": "lampyr-system", + "selector": "app=fiber-router", "cpu": 'container_cpu_usage_seconds_total{namespace="lampyr-system",container="router"}', "memory": 'container_memory_working_set_bytes{namespace="lampyr-system",container="router"}', "phase": 'kube_pod_status_phase{namespace="lampyr-system",phase="Running"}', }, "lampyrHome": { + "namespace": namespace, + "selector": f"lampyr.dev/home=true,serving.knative.dev/revision={revision}", "cpu": f'container_cpu_usage_seconds_total{{namespace="{namespace}",container="fiberd"}}', "memory": f'container_memory_working_set_bytes{{namespace="{namespace}",container="fiberd"}}', "phase": phase, @@ -122,6 +126,8 @@ def resource_inputs(namespace, revision, baseline): ), }, "baseline": { + "namespace": namespace, + "selector": f"app={baseline}", "cpu": f'container_cpu_usage_seconds_total{{{baseline_pods},container="app"}}', "memory": f'container_memory_working_set_bytes{{{baseline_pods},container="app"}}', "phase": phase, @@ -208,6 +214,51 @@ def resource_samples(context, queries, evaluation_time): return samples +def resource_inventory(context, namespace, revision, baseline, target): + inputs = resource_inputs(namespace, revision, baseline) + prefixes = { + "lampyr": ("lampyrRouter", "lampyrHome"), + "kubernetes": ("lampyrRouter", "baseline"), + }[target] + inventory = {} + for prefix in prefixes: + resource = inputs[prefix] + pods = json.loads(command( + "kubectl", "--context", context, "--namespace", resource["namespace"], + "get", "pods", "--selector", resource["selector"], + "--field-selector", "status.phase=Running", "--output", "json", + )) + inventory[prefix] = { + (pod["metadata"]["namespace"], pod["metadata"]["name"]) + for pod in pods["items"] + } + return inventory + + +def resource_coverage(samples, queries, inventory, scrapes): + if not samples: + return False + observed = {} + for identity in samples: + labels = dict(identity) + if "namespace" in labels and "pod" in labels: + observed.setdefault(labels["scale_input"], set()).add( + (labels["namespace"], labels["pod"]) + ) + for prefix, pods in inventory.items(): + if not pods: + return False + for kind in ("Cpu", "Memory", "Phase", "Labels"): + source = prefix + kind + if source in queries and observed.get(source) != pods: + return False + routers = { + ("lampyr-system", dict(identity).get("pod")) + for identity in scrapes + } + return routers == inventory["lampyrRouter"] + + def metric_queries(namespace, revision, window, baseline, window_seconds=30): revision_match = f'namespace="{namespace}",revision="{revision}"' counter_series = { @@ -773,11 +824,16 @@ def main(): if wait_seconds: time.sleep(wait_seconds) snapshot_time = time.time() + before_inventory = resource_inventory( + args.context, args.namespace, revision, baseline["name"], target + ) before_scrapes = router_scrapes(args.context, snapshot_time) before_resources = resource_samples( args.context, sample_queries, snapshot_time ) - if before_resources is not None and all( + if resource_coverage( + before_resources, sample_queries, before_inventory, before_scrapes + ) and all( timestamp >= warmup_ended for timestamp in ( *before_scrapes.values(), *before_resources.values() @@ -814,9 +870,17 @@ def main(): ): continue samples = resource_samples(args.context, sample_queries, evaluated) - if samples is None or samples.keys() != before_resources.keys() or any( - timestamp < load_ended.timestamp() - for timestamp in samples.values() + inventory = resource_inventory( + args.context, args.namespace, revision, baseline["name"], target + ) + if ( + not resource_coverage(samples, sample_queries, inventory, scrapes) + or inventory != before_inventory + or samples.keys() != before_resources.keys() + or any( + timestamp < load_ended.timestamp() + for timestamp in samples.values() + ) ): continue measured_seconds = evaluated - measurement_started diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index 3d33014..7a9c771 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -567,6 +567,65 @@ def test_resource_samples_require_every_input_family(self): ): self.assertIsNone(scale.resource_samples("context", queries, 450)) + def test_resource_inventory_selects_the_revision_and_unique_baseline(self): + names = { + "app=fiber-router": "router-1", + "lampyr.dev/home=true,serving.knative.dev/revision=demo-00001": "home-1", + "app=baseline-owned": "baseline-owned-one", + } + + def pods(*arguments): + namespace = arguments[arguments.index("--namespace") + 1] + selector = arguments[arguments.index("--selector") + 1] + return json.dumps({"items": [{ + "metadata": {"namespace": namespace, "name": names[selector]}, + }]}) + + with mock.patch.object(scale, "command", side_effect=pods): + lampyr = scale.resource_inventory( + "context", "team-a", "demo-00001", "baseline-owned", "lampyr" + ) + baseline = scale.resource_inventory( + "context", "team-a", "demo-00001", "baseline-owned", "kubernetes" + ) + self.assertEqual(lampyr, { + "lampyrRouter": {("lampyr-system", "router-1")}, + "lampyrHome": {("team-a", "home-1")}, + }) + self.assertEqual(baseline, { + "lampyrRouter": {("lampyr-system", "router-1")}, + "baseline": {("team-a", "baseline-owned-one")}, + }) + + def test_resource_coverage_accepts_complete_target_inventories(self): + routers = {(("pod", "router-1"),): 420} + for target, prefix, pod in ( + ("lampyr", "lampyrHome", "home-1"), + ("kubernetes", "baseline", "baseline-owned-one"), + ): + queries = scale.resource_sample_queries( + "team-a", "demo-00001", "baseline-owned", target + ) + inventory = { + "lampyrRouter": {("lampyr-system", "router-1")}, + prefix: {("team-a", pod)}, + } + samples = {} + for source in queries: + namespace, name = ( + ("lampyr-system", "router-1") if source.startswith("lampyrRouter") + else ("team-a", pod) + ) + labels = {"scale_input": source, "namespace": namespace, "pod": name} + samples[tuple(sorted(labels.items()))] = 420 + with self.subTest(target=target): + self.assertTrue(scale.resource_coverage( + samples, queries, inventory, routers + )) + self.assertFalse(scale.resource_coverage( + None, queries, inventory, routers + )) + def test_resource_samples_require_cpu_and_memory_for_each_container(self): queries = { "routersCpu": "cpu_timestamp", From aff9eceb088b924112b1e76455e785c8c06f1eae Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Tue, 24 Nov 2026 13:45:34 -0800 Subject: [PATCH 10/20] fixup! Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- scripts/tests/test_scale_test.py | 64 +++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index 7a9c771..93e145b 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -427,7 +427,7 @@ def metadata_command(*arguments): self.assertEqual(version[0], str(executable)) @contextlib.contextmanager - def scenario_environment(self, routers, resources, inventory=None): + def scenario_environment(self, routers, resources, inventory=None, arguments=()): clock = scale.datetime.datetime.fromtimestamp(400, scale.datetime.timezone.utc) baseline = { "name": "baseline-owned", @@ -444,7 +444,7 @@ def scenario_environment(self, routers, resources, inventory=None): mock.patch.object(scale, "resource_coverage", create=True, return_value=True) ) with mock.patch.object( - scale.sys, "argv", self.main_arguments() + scale.sys, "argv", self.main_arguments(*arguments) ), mock.patch.object( scale, "active_revision", return_value="demo-00001" ), mock.patch.object( @@ -519,6 +519,66 @@ def test_scenario_accepts_fresh_resource_samples(self): scale.main() self.assertEqual(len(write.call_args.args[0]["scenarios"]), 2) + def test_warmup_and_load_use_identical_request_paths_and_queries(self): + for lampyr, baseline in ( + ("https://example.test/", "http://localhost/"), + ( + "https://example.test/compute?iterations=1000&size=64", + "http://localhost/compute?iterations=1000&size=64", + ), + ( + "https://example.test/a%2Fb?value=a%26b&value=c+d&empty=", + "http://localhost/a%2Fb?value=a%26b&value=c+d&empty=", + ), + ( + "https://example.test//other.test/compute?next=https%3A%2F%2Felsewhere.test", + "http://localhost//other.test/compute?next=https%3A%2F%2Felsewhere.test", + ), + ("https://example.test?iterations=1000", "http://localhost/?iterations=1000"), + ): + expected_lampyr = lampyr.replace( + "example.test?", "example.test/?" + ) + with self.subTest(lampyr=lampyr), self.scenario_environment( + [{"router-1": 420}] * 20, + [{"container-1": 420}] * 20, + arguments=("--lampyr-url", lampyr), + ), mock.patch.object(scale, "warm_target") as warm, mock.patch.object( + scale, "run_oha", return_value={ + "summary": {"requestsPerSec": 1}, + "httpSuccessRate": 1, + "successfulLatencyMs": {"p95": 1}, + }, + ) as load: + scale.main() + for execute in (warm, load): + self.assertEqual( + [call.args[1] for call in execute.call_args_list], + [expected_lampyr, baseline], + ) + + def test_invalid_workload_urls_fail_before_cluster_work(self): + for url in ( + "/compute?iterations=1000", + "ftp://example.test/compute", + "https:///compute", + "https://example.test:99999/compute", + "https://user:password@example.test/compute", + "https://example.test/compute#iterations=1000", + "https://example.test/compute#", + "https://example.test/a b", + "https://example.test/a\nb", + "https://example.test\\other.test/compute", + ): + with self.subTest(url=url), mock.patch.object( + scale.sys, "argv", self.main_arguments("--lampyr-url", url) + ), mock.patch.object(scale, "active_revision") as revision, mock.patch.object( + scale, "baseline_server", side_effect=AssertionError("cluster work started") + ): + with self.assertRaises(ValueError): + scale.main() + revision.assert_not_called() + def test_scenario_rejects_missing_router_membership_at_both_endpoints(self): inventory = { "lampyrRouter": { From 1b824d77efd1a02cf9fcedb11ff8b3dd7fde77a1 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Tue, 24 Nov 2026 13:54:25 -0800 Subject: [PATCH 11/20] fixup! Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- docs/scale-testing.md | 9 +++++-- scripts/scale-test.py | 41 +++++++++++++++++++++++++------- scripts/tests/test_scale_test.py | 6 ++++- 3 files changed, 44 insertions(+), 12 deletions(-) diff --git a/docs/scale-testing.md b/docs/scale-testing.md index 841cabe..a1b941d 100644 --- a/docs/scale-testing.md +++ b/docs/scale-testing.md @@ -29,6 +29,11 @@ just scale-test \ REGISTRY/IMAGE@sha256:DIGEST ``` +The runner uses the Lampyr URL's path and query for both targets, during warmup +and load. For example, `"https://LAMPYR_URL/compute?iterations=1000"` also sends +`/compute?iterations=1000` to Kubernetes. Quote URLs that contain query parameters. +Use an absolute HTTP or HTTPS URL without credentials or a fragment. + The default sweep runs each target for 30 seconds at concurrency 1, 4, 16, and 64. The framework: @@ -40,8 +45,8 @@ and 64. The framework: - writes a concise Markdown comparison beside it. The Kubernetes target uses a local Service port-forward, while the Lampyr URL -uses its configured ingress. Record that path difference when interpreting -results. The result metadata records both paths. The framework monitors the +uses its configured ingress. Record that network difference when interpreting +results. The result metadata records both network paths. The framework monitors the port-forward and stops if it exits, but the tunnel can still limit high concurrency results. This framework is for repeatable comparisons, not a claim that the two network paths have identical overhead. diff --git a/scripts/scale-test.py b/scripts/scale-test.py index 99c1e52..301560e 100644 --- a/scripts/scale-test.py +++ b/scripts/scale-test.py @@ -730,6 +730,27 @@ def safe_url(value): return urllib.parse.urlunsplit((parsed.scheme, netloc, parsed.path, "", "")) +def workload_url(value): + if any( + character.isspace() or ord(character) < 32 or ord(character) == 127 + or character == "\\" + for character in value + ): + raise ValueError( + "Lampyr URL must encode whitespace and must not contain controls or backslashes" + ) + parsed = urllib.parse.urlsplit(value) + if parsed.scheme not in {"http", "https"} or not parsed.hostname: + raise ValueError("Lampyr URL must be an absolute HTTP or HTTPS URL") + if parsed.username is not None or parsed.password is not None: + raise ValueError("Lampyr URL must not contain credentials") + if "#" in value: + raise ValueError("Lampyr URL must not contain a fragment; use query parameters") + if parsed.port == 0: + raise ValueError("Lampyr URL port must be between 1 and 65535") + return parsed._replace(path=parsed.path or "/") + + def main(): parser = argparse.ArgumentParser() parser.add_argument("--context", required=True) @@ -755,6 +776,7 @@ def main(): output = Path(args.output) if output.suffix.lower() == ".md": raise ValueError("JSON and Markdown output files must be distinct; do not use .md") + lampyr_url = workload_url(args.lampyr_url) oha = Path(args.oha).resolve() if not oha.is_file(): raise FileNotFoundError(f"load generator not found: {oha}") @@ -765,7 +787,7 @@ def main(): "service": args.service, "namespace": args.namespace, "revision": revision, - "lampyrUrl": safe_url(args.lampyr_url), + "lampyrUrl": safe_url(lampyr_url.geturl()), "baselineImage": args.baseline_image, "baselineReplicas": args.baseline_replicas, "duration": args.duration, @@ -798,20 +820,21 @@ def main(): args.context, args.baseline_image, args.baseline_replicas, args.namespace ) as baseline: metadata["baselineName"] = baseline["name"] - for target, url in [ - ("lampyr", args.lampyr_url), - ("kubernetes", baseline["url"]), - ]: + baseline_url = urllib.parse.urlsplit(baseline["url"])._replace( + path=lampyr_url.path, query=lampyr_url.query, fragment="" + ) + targets = ( + ("lampyr", lampyr_url.geturl()), + ("kubernetes", baseline_url.geturl()), + ) + for target, url in targets: if target == "kubernetes": require_running(baseline["process"], "baseline port-forward") warm_target(oha, url) warmup_ended = datetime.datetime.now(datetime.timezone.utc).timestamp() time.sleep(6) for concurrency in concurrencies: - for target, url in [ - ("lampyr", args.lampyr_url), - ("kubernetes", baseline["url"]), - ]: + for target, url in targets: if target == "kubernetes": require_running(baseline["process"], "baseline port-forward") snapshot_queries = metric_queries( diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index 93e145b..9301244 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -572,7 +572,11 @@ def test_invalid_workload_urls_fail_before_cluster_work(self): ): with self.subTest(url=url), mock.patch.object( scale.sys, "argv", self.main_arguments("--lampyr-url", url) - ), mock.patch.object(scale, "active_revision") as revision, mock.patch.object( + ), mock.patch.object( + scale, "active_revision", return_value="demo-00001" + ) as revision, mock.patch.object( + scale, "command", return_value="{}" + ), mock.patch.object( scale, "baseline_server", side_effect=AssertionError("cluster work started") ): with self.assertRaises(ValueError): From e628f660302977b2740b78e4468995f5e9ec4faa Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Tue, 24 Nov 2026 16:54:10 -0800 Subject: [PATCH 12/20] Compare the Node.js workload with stock Knative Signed-off-by: James Sturtevant --- Justfile | 10 +- docs/scale-testing.md | 63 +++++- scripts/fixtures/scale-workload/Dockerfile | 16 +- scripts/install-scale-metrics.sh | 37 ++++ scripts/scale-test.py | 236 +++++++++++++++++---- scripts/tests/test_scale_test.py | 217 +++++++++++++++++++ 6 files changed, 523 insertions(+), 56 deletions(-) create mode 100644 scripts/install-scale-metrics.sh diff --git a/Justfile b/Justfile index 3a22da8..ebd1f0b 100644 --- a/Justfile +++ b/Justfile @@ -362,14 +362,14 @@ release-disruption-gate service url: --service "{{service}}" \ --url "{{url}}" -# Build the normal Kubernetes image from the same Go source as the Lampyr example. +# Build the container image from the same Node.js source as the Lampyr example. [positional-arguments] scale-baseline-image image: docker build --tag "$1" --file scripts/fixtures/scale-workload/Dockerfile . -# Compare Lampyr with a normal Kubernetes Deployment using platform telemetry. +# Compare Lampyr with a Deployment and optionally stock Knative. [positional-arguments] -scale-test context service lampyr-url baseline-image duration="30s" concurrency="1,4,16,64" output="build/scale-results.json": install-oha +scale-test context service lampyr-url baseline-image duration="30s" concurrency="1,4,16,64" output="build/scale-results.json" knative-context="" knative-ingress-url="": install-oha python3 scripts/scale-test.py \ --context "$1" \ --service "$2" \ @@ -377,7 +377,9 @@ scale-test context service lampyr-url baseline-image duration="30s" concurrency= --baseline-image "$4" \ --duration "$5" \ --concurrency "$6" \ - --output "$7" + --output "$7" \ + --knative-context "$8" \ + --knative-ingress-url "$9" # Run the repository test suites used in CI. test: test-unit test-cli examples-check test-preview-release cli::test cli::test-intent helper::test azure::test kind::test k3d::test test-examples-local test-kind-integration test-k3d-integration test-existing-kind-integration test-knative-portability test-walkthrough diff --git a/docs/scale-testing.md b/docs/scale-testing.md index a1b941d..caae813 100644 --- a/docs/scale-testing.md +++ b/docs/scale-testing.md @@ -1,17 +1,18 @@ --- title: Scale testing -description: Compare Lampyr with the same application in a Kubernetes Deployment. +description: Compare the same Node.js application on Lampyr, Kubernetes, and Knative. --- # Scale testing -The opt-in scale framework compares a Lampyr Service with the same Go -application in a normal Kubernetes Deployment. It uses oha for client latency +The opt-in scale framework compares a Lampyr Service with the same Node.js +application in a Kubernetes Deployment and, optionally, stock Knative. It uses oha for client latency and throughput, and queries the optional observability add-on for platform metrics. The live comparison does not run in CI. -Install the add-on and deploy the committed Go standalone example through -Lampyr. Build and publish the normal Kubernetes image from the same source: +Install the add-on and deploy `docs/examples/hello-nodejs-standalone` through +Lampyr. This Express application returns JSON with `message` and `path` fields. +Build and publish the container image from that same source: ```bash just scale-baseline-image REGISTRY/IMAGE:TAG @@ -34,10 +35,52 @@ and load. For example, `"https://LAMPYR_URL/compute?iterations=1000"` also sends `/compute?iterations=1000` to Kubernetes. Quote URLs that contain query parameters. Use an absolute HTTP or HTTPS URL without credentials or a fragment. +## Stock Knative target + +Use a separate cluster with stock Knative Serving and working ingress. Context +aliases for the Lampyr cluster are rejected. The selected namespace must exist +in both clusters. Install the metrics collectors in the stock cluster: + +```bash +bash scripts/install-scale-metrics.sh KNATIVE_CONTEXT +``` + +This script requires `kubectl` and `jq`. It selects the metrics collectors from +the shared manifest. It does not install Lampyr, UI services, tracing services, +or Serving controllers. +Prometheus remains cluster-internal. The script omits the UI-only Prometheus +NetworkPolicy so the runner can query through the Kubernetes API proxy. + +Add the Knative context to the runner: + +```bash +python3 scripts/scale-test.py \ + --context LAMPYR_CONTEXT \ + --service SERVICE \ + --lampyr-url https://LAMPYR_URL \ + --baseline-image REGISTRY/IMAGE@sha256:DIGEST \ + --knative-context KNATIVE_CONTEXT +``` + +The runner creates a temporary Knative Service with the same image digest as +the Deployment. Both use a 768 MiB application memory limit. Knative uses +`min-scale=1` and `max-scale=1`; the client controls request concurrency. +The runner removes only the Service it created. This is a warm, fixed-capacity +comparison, not a cold-start or autoscaling test. + +The Knative Service URL must be reachable from the load generator. For local +ingress exposed on a different address or port, add +`--knative-ingress-url http://127.0.0.1:PORT`. Supply only the origin, without a +path or query. The runner sends the Service's routing Host header and copies +the Lampyr request path and query for both warmup and load. + +## Measurements + The default sweep runs each target for 30 seconds at concurrency 1, 4, 16, and 64. The framework: - creates a temporary one-replica Deployment and Service with unique names; +- creates a stock Knative Service when a Knative context is supplied; - warms both targets; - runs the same client against Lampyr and Kubernetes; - queries Prometheus for request, Fiber, CPU, and memory measurements; @@ -51,12 +94,20 @@ port-forward and stops if it exits, but the tunnel can still limit high concurrency results. This framework is for repeatable comparisons, not a claim that the two network paths have identical overhead. -The runner requires one baseline replica and a duration of at least 30 seconds. +The runner requires one Deployment replica and a duration of at least 30 seconds. Both targets use a 10-second request timeout, including warmup. Cleanup removes only resources this run created. Custom JSON output names must not use the `.md` extension. The context must allow read access to the measured Pods. +Client latency, throughput, and HTTP success come from oha for all targets. +CPU and memory come from each cluster's Prometheus, which scrapes kubelet +cAdvisor. kube-state-metrics supplies Pod membership. The Knative JSON records +the application and queue-proxy separately; the report includes both. Combined +peak memory is measured at one time, not the sum of separate peaks. Shared +ingress and control-plane costs are not included. Node details are recorded +for both clusters; use matching node sizes and configurations. + The report calculates HTTP success from response status codes and transport errors. Its latency columns include only successful HTTP responses. Platform error and shed counts come from Lampyr metrics. The runner waits for a final diff --git a/scripts/fixtures/scale-workload/Dockerfile b/scripts/fixtures/scale-workload/Dockerfile index c0a8c05..828a538 100644 --- a/scripts/fixtures/scale-workload/Dockerfile +++ b/scripts/fixtures/scale-workload/Dockerfile @@ -1,13 +1,9 @@ # syntax=docker/dockerfile:1 -FROM golang:1.26.7-bookworm@sha256:e8c859f5632dcfde7b32d2012b4351728f6437930887c2f6a91ea242459e5514 AS build -WORKDIR /src -COPY docs/examples/hello-go-standalone/go.mod docs/examples/hello-go-standalone/go.sum ./ -RUN go mod download -COPY docs/examples/hello-go-standalone/application.go docs/examples/hello-go-standalone/main.go ./ -RUN CGO_ENABLED=0 go build -mod=readonly -trimpath -ldflags="-s -w" -o /service . - -FROM scratch -COPY --from=build /service /service +FROM node:24-alpine@sha256:116b800c3754b440ee0aa3ed2f20f5bf3d99a554bfd9adeea09ea8017f6e85f5 +WORKDIR /app +COPY docs/examples/hello-nodejs-standalone/package.json docs/examples/hello-nodejs-standalone/package-lock.json ./ +RUN npm ci --omit=dev +COPY docs/examples/hello-nodejs-standalone/application.js docs/examples/hello-nodejs-standalone/server.js ./ ENV PORT=8080 USER 65532:65532 -ENTRYPOINT ["/service"] +ENTRYPOINT ["node", "server.js"] diff --git a/scripts/install-scale-metrics.sh b/scripts/install-scale-metrics.sh new file mode 100644 index 0000000..7b0fd1f --- /dev/null +++ b/scripts/install-scale-metrics.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# != 1 || -z $1 ]]; then + echo "usage: bash scripts/install-scale-metrics.sh CONTEXT" >&2 + exit 1 +fi +context=$1 +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) + +kubectl --context "$context" create --dry-run=client --validate=false \ + --filename "$root/k8s/observability.yaml" --output json | + jq --slurp --exit-status ' + { + apiVersion: "v1", + kind: "List", + items: [ + .[] | (if .kind == "List" then .items[] else . end) | + select(.metadata.namespace != "lampyr-system") | + select(.kind != "NetworkPolicy" or .metadata.name != "prometheus") | + select(.metadata.name | IN( + "lampyr-observability", + "lampyr-observability-prometheus", + "lampyr-observability-kube-state-metrics", + "prometheus", + "kube-state-metrics" + )) + ] + } | + if (.items | length) == 0 then error("no scale metrics resources found") else . end + ' | + kubectl --context "$context" apply --filename - + +for deployment in prometheus kube-state-metrics; do + kubectl --context "$context" --namespace lampyr-observability \ + rollout status "deployment/$deployment" --timeout=300s +done diff --git a/scripts/scale-test.py b/scripts/scale-test.py index 301560e..0465ab9 100644 --- a/scripts/scale-test.py +++ b/scripts/scale-test.py @@ -103,10 +103,10 @@ def router_scrapes(context, evaluation_time): return scrapes -def resource_inputs(namespace, revision, baseline): +def resource_inputs(namespace, revision, baseline, knative=None): baseline_pods = f'namespace="{namespace}",pod=~"{baseline}-.*"' phase = f'kube_pod_status_phase{{namespace="{namespace}",phase="Running"}}' - return { + inputs = { "lampyrRouter": { "namespace": "lampyr-system", "selector": "app=fiber-router", @@ -133,6 +133,21 @@ def resource_inputs(namespace, revision, baseline): "phase": phase, }, } + if knative: + for prefix, container in ( + ("knativeApp", "app"), ("knativeQueueProxy", "queue-proxy") + ): + selector = ( + f'namespace="{namespace}",pod=~"{knative}-.*",container="{container}"' + ) + inputs[prefix] = { + "namespace": namespace, + "selector": f"serving.knative.dev/revision={knative}", + "cpu": f"container_cpu_usage_seconds_total{{{selector}}}", + "memory": f"container_memory_working_set_bytes{{{selector}}}", + "phase": phase, + } + return inputs def selected_resource(selector, inputs): @@ -144,11 +159,12 @@ def selected_resource(selector, inputs): return f"{selector} * on(namespace,pod) group_left() {membership}" -def resource_sample_queries(namespace, revision, baseline, target): - inputs = resource_inputs(namespace, revision, baseline) +def resource_sample_queries(namespace, revision, baseline, target, knative=None): + inputs = resource_inputs(namespace, revision, baseline, knative) prefixes = { "lampyr": ("lampyrRouter", "lampyrHome"), "kubernetes": ("baseline",), + "knative": ("knativeApp", "knativeQueueProxy"), }[target] queries = { "kubeState": ( @@ -214,11 +230,12 @@ def resource_samples(context, queries, evaluation_time): return samples -def resource_inventory(context, namespace, revision, baseline, target): - inputs = resource_inputs(namespace, revision, baseline) +def resource_inventory(context, namespace, revision, baseline, target, knative=None): + inputs = resource_inputs(namespace, revision, baseline, knative) prefixes = { "lampyr": ("lampyrRouter", "lampyrHome"), "kubernetes": ("lampyrRouter", "baseline"), + "knative": ("knativeApp", "knativeQueueProxy"), }[target] inventory = {} for prefix in prefixes: @@ -256,10 +273,10 @@ def resource_coverage(samples, queries, inventory, scrapes): ("lampyr-system", dict(identity).get("pod")) for identity in scrapes } - return routers == inventory["lampyrRouter"] + return routers == inventory.get("lampyrRouter", set()) -def metric_queries(namespace, revision, window, baseline, window_seconds=30): +def metric_queries(namespace, revision, window, baseline, window_seconds=30, knative=None): revision_match = f'namespace="{namespace}",revision="{revision}"' counter_series = { "lampyrRequests": ( @@ -299,7 +316,7 @@ def metric_queries(namespace, revision, window, baseline, window_seconds=30): ), } memory = {} - for prefix, resource in resource_inputs(namespace, revision, baseline).items(): + for prefix, resource in resource_inputs(namespace, revision, baseline, knative).items(): cpu = selected_resource(f'increase({resource["cpu"]}[{window}])', resource) memory[prefix] = f'sum({selected_resource(resource["memory"], resource)})' queries[f"{prefix}CPU"] = f"sum({cpu}) / {window_seconds:.3f}" @@ -310,6 +327,15 @@ def metric_queries(namespace, revision, window, baseline, window_seconds=30): f'max_over_time((({memory["lampyrRouter"]}) + ' f'({memory["lampyrHome"]}))[{window}:5s])' ) + if knative: + queries["knativeCPU"] = ( + f'({queries["knativeAppCPU"]}) + ({queries["knativeQueueProxyCPU"]})' + ) + queries["knativeMemoryBytes"] = ( + f'max_over_time((({memory["knativeApp"]}) + ' + f'({memory["knativeQueueProxy"]}))[{window}:5s])' + ) + return {key: value for key, value in queries.items() if key.startswith("knative")} return queries @@ -392,9 +418,9 @@ def baseline_manifest(image, replicas, namespace, name): "resources": { "requests": { "cpu": "250m", - "memory": "256Mi", + "memory": "768Mi", }, - "limits": {"memory": "256Mi"}, + "limits": {"memory": "768Mi"}, }, "securityContext": { "allowPrivilegeEscalation": False, @@ -513,13 +539,87 @@ def baseline_server(context, image, replicas, namespace): print(f"warning: baseline cleanup failed: {error}", file=sys.stderr) +def require_separate_knative(context, lampyr_context): + identities = [ + json.loads(command( + "kubectl", "--context", target, "get", "namespace", "kube-system", + "--output", "json", + ))["metadata"]["uid"] + for target in (context, lampyr_context) + ] + if identities[0] == identities[1]: + raise ValueError("stock Knative must use a separate cluster, not a context alias") + if command( + "kubectl", "--context", context, "--namespace", "kube-system", + "get", "configmap", "lampyr-install", "--ignore-not-found", "--output", "name", + ): + raise ValueError("Knative target cluster must not have Lampyr installed") + + +def knative_manifest(image, namespace, name): + container = baseline_manifest(image, 1, namespace, name)["items"][0][ + "spec" + ]["template"]["spec"]["containers"][0] + container["ports"] = [{"containerPort": 8080}] + container["readinessProbe"]["httpGet"]["port"] = 8080 + return { + "apiVersion": "serving.knative.dev/v1", + "kind": "Service", + "metadata": {"name": name, "namespace": namespace}, + "spec": {"template": { + "metadata": {"annotations": { + "autoscaling.knative.dev/min-scale": "1", + "autoscaling.knative.dev/max-scale": "1", + }}, + "spec": {"containerConcurrency": 0, "containers": [container]}, + }}, + } + + +@contextlib.contextmanager +def knative_server(context, image, namespace): + if "@sha256:" not in image: + raise ValueError("Knative image must be digest-pinned") + name = f"scale-knative-{uuid.uuid4().hex[:24]}" + manifest = knative_manifest(image, namespace, name) + created = False + try: + kubectl_manifest(context, "create", manifest) + created = True + subprocess.run([ + "kubectl", "--context", context, "--namespace", namespace, + "wait", f"services.serving.knative.dev/{name}", + "--for=condition=Ready", "--timeout=300s", + ], check=True) + service = json.loads(command( + "kubectl", "--context", context, "--namespace", namespace, + "get", "services.serving.knative.dev", name, "--output", "json", + )) + yield { + "name": name, + "url": workload_url(service["status"]["url"]), + "revision": service["status"]["latestReadyRevisionName"], + } + finally: + original_error = sys.exc_info()[0] is not None + if created: + try: + kubectl_manifest( + context, "delete", manifest, "--ignore-not-found=true", "--wait=true" + ) + except subprocess.CalledProcessError as error: + if not original_error: + raise + print(f"warning: Knative cleanup failed: {error}", file=sys.stderr) + + def require_running(process, name): return_code = process.poll() if return_code is not None: raise RuntimeError(f"{name} exited with status {return_code}") -def run_oha(oha, url, duration, concurrency): +def run_oha(oha, url, duration, concurrency, host=None): output = subprocess.check_output( [ str(oha), @@ -535,6 +635,7 @@ def run_oha(oha, url, duration, concurrency): "--output-format", "json", "--insecure", + *(["--host", host] if host else []), url, ], text=True, @@ -567,7 +668,7 @@ def http_success_rate(client): return successful / total -def warm_target(oha, url): +def warm_target(oha, url, host=None): output = subprocess.check_output( [ str(oha), @@ -582,6 +683,7 @@ def warm_target(oha, url): "--output-format", "json", "--insecure", + *(["--host", host] if host else []), url, ], text=True, @@ -617,6 +719,11 @@ def target_resource_names(target): "lampyrHomeMemoryBytes", "lampyrMemoryBytes", ) + if target == "knative": + return ( + "knativeAppCPU", "knativeQueueProxyCPU", "knativeCPU", + "knativeAppMemoryBytes", "knativeQueueProxyMemoryBytes", "knativeMemoryBytes", + ) return ("baselineCPU", "baselineMemoryBytes") @@ -656,6 +763,10 @@ def write_report(result, path): f"- Baseline image: `{result['metadata']['baselineImage']}`", f"- Lampyr path: {result['metadata']['networkPaths']['lampyr']}", f"- Kubernetes path: {result['metadata']['networkPaths']['kubernetes']}", + *( + [f"- Knative path: {result['metadata']['networkPaths']['knative']}"] + if "knative" in result["metadata"]["networkPaths"] else [] + ), "", "| Target | Concurrency | Requests/s | HTTP success | p50 ms | p95 ms | p99 ms | Platform errors | Shed | CPU cores | Peak memory MiB |", "|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|", @@ -670,6 +781,11 @@ def write_report(result, path): memory = metrics.get("lampyrMemoryBytes") errors = metrics.get("lampyrErrors") shed = metrics.get("lampyrShed") + elif scenario["target"] == "knative": + cpu = metrics["knativeCPU"] + memory = metrics["knativeMemoryBytes"] + errors = None + shed = None else: cpu = metrics["baselineCPU"] memory = metrics["baselineMemoryBytes"] @@ -757,6 +873,8 @@ def main(): parser.add_argument("--service", required=True) parser.add_argument("--lampyr-url", required=True) parser.add_argument("--baseline-image", required=True) + parser.add_argument("--knative-context", default="") + parser.add_argument("--knative-ingress-url", default="") parser.add_argument("--namespace", default="default") parser.add_argument("--baseline-replicas", type=int, default=1) parser.add_argument("--duration", default="30s") @@ -777,6 +895,17 @@ def main(): if output.suffix.lower() == ".md": raise ValueError("JSON and Markdown output files must be distinct; do not use .md") lampyr_url = workload_url(args.lampyr_url) + knative_ingress = None + if args.knative_ingress_url: + if not args.knative_context: + raise ValueError("--knative-ingress-url requires --knative-context") + knative_ingress = workload_url(args.knative_ingress_url) + if knative_ingress.path != "/" or knative_ingress.query: + raise ValueError("Knative ingress URL must specify only an HTTP(S) origin") + if args.knative_context: + if args.knative_context == args.context: + raise ValueError("stock Knative must use a separate cluster context") + require_separate_knative(args.knative_context, args.context) oha = Path(args.oha).resolve() if not oha.is_file(): raise FileNotFoundError(f"load generator not found: {oha}") @@ -818,41 +947,72 @@ def main(): result = {"schema": 1, "metadata": metadata, "scenarios": []} with baseline_server( args.context, args.baseline_image, args.baseline_replicas, args.namespace - ) as baseline: + ) as baseline, ( + knative_server(args.knative_context, args.baseline_image, args.namespace) + if args.knative_context else contextlib.nullcontext(None) + ) as knative: metadata["baselineName"] = baseline["name"] baseline_url = urllib.parse.urlsplit(baseline["url"])._replace( path=lampyr_url.path, query=lampyr_url.query, fragment="" ) - targets = ( - ("lampyr", lampyr_url.geturl()), - ("kubernetes", baseline_url.geturl()), - ) - for target, url in targets: + targets = [ + ("lampyr", lampyr_url.geturl(), args.context, None), + ("kubernetes", baseline_url.geturl(), args.context, None), + ] + if knative: + route = knative["url"] + native_url = (knative_ingress or route)._replace( + path=lampyr_url.path, query=lampyr_url.query, fragment="" + ) + targets.append(( + "knative", native_url.geturl(), args.knative_context, + route.netloc if knative_ingress else None, + )) + metadata["knative"] = { + "context": args.knative_context, + "service": knative["name"], + "revision": knative["revision"], + "url": safe_url(native_url.geturl()), + "minScale": 1, + "maxScale": 1, + "nodes": node_summary(json.loads(command( + "kubectl", "--context", args.knative_context, + "get", "nodes", "--output", "json", + ))), + } + metadata["networkPaths"]["knative"] = "stock Knative ingress and queue-proxy" + for target, url, context, host in targets: if target == "kubernetes": require_running(baseline["process"], "baseline port-forward") - warm_target(oha, url) + warm_target(oha, url, **({"host": host} if host else {})) warmup_ended = datetime.datetime.now(datetime.timezone.utc).timestamp() time.sleep(6) for concurrency in concurrencies: - for target, url in targets: + for target, url, context, host in targets: + native_revision = knative["revision"] if target == "knative" else None if target == "kubernetes": require_running(baseline["process"], "baseline port-forward") snapshot_queries = metric_queries( - args.namespace, revision, "1s", baseline["name"], 1 + args.namespace, revision, "1s", baseline["name"], 1, + knative=native_revision, ) sample_queries = resource_sample_queries( - args.namespace, revision, baseline["name"], target + args.namespace, revision, baseline["name"], target, + knative=native_revision, ) for wait_seconds in (0, 5, 5, 5, 5, 5, 5): if wait_seconds: time.sleep(wait_seconds) snapshot_time = time.time() before_inventory = resource_inventory( - args.context, args.namespace, revision, baseline["name"], target + context, args.namespace, revision, baseline["name"], target, + knative=native_revision, + ) + before_scrapes = ( + {} if native_revision else router_scrapes(context, snapshot_time) ) - before_scrapes = router_scrapes(args.context, snapshot_time) before_resources = resource_samples( - args.context, sample_queries, snapshot_time + context, sample_queries, snapshot_time ) if resource_coverage( before_resources, sample_queries, before_inventory, before_scrapes @@ -868,17 +1028,19 @@ def main(): f"Prometheus did not collect fresh pre-load router and " f"resource samples for {target}" ) - measurement_started = min( + measurement_started = min([ *before_scrapes.values(), *before_resources.values() - ) - 0.001 - before = counter_snapshot(args.context, snapshot_queries, snapshot_time) - if before["lampyrRequests"] is None: + ]) - 0.001 + before = counter_snapshot(context, snapshot_queries, snapshot_time) + if not native_revision and before["lampyrRequests"] is None: raise RuntimeError( "Lampyr request metrics are missing after warmup; check the " "observability add-on and requested namespace" ) started = datetime.datetime.now(datetime.timezone.utc) - client = run_oha(oha, url, args.duration, concurrency) + client = run_oha( + oha, url, args.duration, concurrency, **({"host": host} if host else {}) + ) load_ended = datetime.datetime.now(datetime.timezone.utc) if target == "kubernetes": require_running(baseline["process"], "baseline port-forward") @@ -886,15 +1048,16 @@ def main(): for wait_seconds in (6, 5, 5, 5, 5, 5): time.sleep(wait_seconds) evaluated = time.time() - scrapes = router_scrapes(args.context, evaluated) + scrapes = {} if native_revision else router_scrapes(context, evaluated) if scrapes.keys() != before_scrapes.keys() or any( timestamp < load_ended.timestamp() for timestamp in scrapes.values() ): continue - samples = resource_samples(args.context, sample_queries, evaluated) + samples = resource_samples(context, sample_queries, evaluated) inventory = resource_inventory( - args.context, args.namespace, revision, baseline["name"], target + context, args.namespace, revision, baseline["name"], target, + knative=native_revision, ) if ( not resource_coverage(samples, sample_queries, inventory, scrapes) @@ -914,16 +1077,17 @@ def main(): window, baseline["name"], measured_seconds, + knative=native_revision, ) resources = { name: prometheus_query( - args.context, queries[name], evaluated + context, queries[name], evaluated ) for name in target_resource_names(target) } if target_resources_available(target, resources): platform = collect_metrics( - args.context, queries, before, evaluated + context, queries, before, evaluated ) break else: diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index 9301244..8e227ae 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -97,6 +97,21 @@ def test_report_compares_lampyr_and_kubernetes(self): "baselineMemoryBytes": 4 << 20, }, }, + { + "target": "knative", + "concurrency": 4, + "client": { + "summary": {"requestsPerSec": 15}, + "httpSuccessRate": 1, + "successfulLatencyMs": {"p50": 2, "p95": 3, "p99": 4}, + }, + "platform": { + "knativeCPU": 0.5, + "knativeAppMemoryBytes": 3 << 20, + "knativeQueueProxyMemoryBytes": 2 << 20, + "knativeMemoryBytes": 4 << 20, + }, + }, ], } with tempfile.TemporaryDirectory() as temporary: @@ -105,6 +120,8 @@ def test_report_compares_lampyr_and_kubernetes(self): report = output.read_text() self.assertIn("| lampyr | 4 | 10.00", report) self.assertIn("| kubernetes | 4 | 20.00", report) + self.assertIn("| knative | 4 | 15.00", report) + self.assertIn("| n/a | n/a | 0.500 | 4.00 |", report) self.assertIn("| 0 | 0 | 0.300 | 2.50 |", report) self.assertIn("kubectl Service port-forward", report) @@ -583,6 +600,206 @@ def test_invalid_workload_urls_fail_before_cluster_work(self): scale.main() revision.assert_not_called() + def test_knative_service_uses_same_image_and_cleans_only_after_creation(self): + image = "example.test/node@sha256:abc" + status = {"status": { + "url": "http://native.default.example.test", + "latestReadyRevisionName": "native-00001", + }} + with mock.patch.object(scale, "kubectl_manifest") as manifest, mock.patch.object( + scale.subprocess, "run" + ), mock.patch.object(scale, "command", return_value=json.dumps(status)): + with scale.knative_server("stock", image, "default") as native: + self.assertEqual(native["revision"], "native-00001") + created = manifest.call_args.args[2] + template = created["spec"]["template"] + self.assertEqual(template["spec"]["containers"][0]["image"], image) + self.assertEqual(template["spec"]["containers"][0]["name"], "app") + self.assertEqual(template["metadata"]["annotations"], { + "autoscaling.knative.dev/min-scale": "1", + "autoscaling.knative.dev/max-scale": "1", + }) + self.assertEqual( + [call.args[1] for call in manifest.call_args_list], ["create", "delete"] + ) + self.assertEqual(manifest.call_args.args[2], created) + failure = scale.subprocess.CalledProcessError(1, ["kubectl"]) + with mock.patch.object( + scale, "kubectl_manifest", side_effect=failure + ) as manifest: + with self.assertRaises(scale.subprocess.CalledProcessError): + with scale.knative_server("stock", image, "default"): + pass + self.assertEqual(manifest.call_count, 1) + with mock.patch.object(scale, "kubectl_manifest") as manifest, mock.patch.object( + scale.subprocess, "run", side_effect=failure + ): + with self.assertRaises(scale.subprocess.CalledProcessError): + with scale.knative_server("stock", image, "default"): + pass + self.assertEqual( + [call.args[1] for call in manifest.call_args_list], ["create", "delete"] + ) + + def test_knative_context_aliases_cannot_target_the_lampyr_cluster(self): + with mock.patch.object( + scale, "command", return_value=json.dumps({"metadata": {"uid": "same"}}) + ): + with self.assertRaisesRegex(ValueError, "separate cluster"): + scale.require_separate_knative("alias", "lampyr") + with mock.patch.object(scale, "command", side_effect=[ + json.dumps({"metadata": {"uid": "native"}}), + json.dumps({"metadata": {"uid": "lampyr"}}), + "configmap/lampyr-install", + ]): + with self.assertRaisesRegex(ValueError, "must not have Lampyr"): + scale.require_separate_knative("stock", "lampyr") + + def test_knative_uses_its_own_metrics_and_matching_workload_with_ingress_host(self): + native = { + "name": "native", "revision": "native-00001", + "url": scale.workload_url("http://native.default.example.test"), + } + arguments = ( + "--knative-context", "stock", + "--knative-ingress-url", "http://127.0.0.1:18080", + "--lampyr-url", "https://example.test/a%2Fb?size=64&value=a%26b", + ) + with self.scenario_environment( + [{"router-1": 420}] * 20, + [{"container-1": 420}] * 20, + arguments=arguments, + ) as write, mock.patch.object( + scale, "require_separate_knative" + ), mock.patch.object( + scale, "knative_server", return_value=contextlib.nullcontext(native) + ) as server, mock.patch.object(scale, "warm_target") as warm, mock.patch.object( + scale, "run_oha", return_value={ + "summary": {"requestsPerSec": 1}, "httpSuccessRate": 1, + "successfulLatencyMs": {"p95": 1}, + }, + ) as load: + scale.main() + server.assert_called_once_with( + "stock", "example.test/baseline@sha256:abc", "default" + ) + for execute in (warm, load): + self.assertEqual( + [call.args[1] for call in execute.call_args_list], + [ + "https://example.test/a%2Fb?size=64&value=a%26b", + "http://localhost/a%2Fb?size=64&value=a%26b", + "http://127.0.0.1:18080/a%2Fb?size=64&value=a%26b", + ], + ) + self.assertEqual( + execute.call_args.kwargs, {"host": "native.default.example.test"} + ) + sample_calls = scale.resource_samples.call_args_list + self.assertEqual([call.args[0] for call in sample_calls], [ + "test", "test", "test", "test", "stock", "stock", + ]) + self.assertEqual(scale.router_scrapes.call_count, 4) + result = write.call_args.args[0] + self.assertEqual( + [scenario["target"] for scenario in result["scenarios"]], + ["lampyr", "kubernetes", "knative"], + ) + self.assertEqual(result["metadata"]["knative"]["revision"], "native-00001") + self.assertTrue(all( + name.startswith("knative") + for name in result["scenarios"][-1]["platform"] + )) + + def test_knative_resources_include_both_containers_without_fiber_router(self): + queries = scale.resource_sample_queries( + "team-a", "lampyr-00001", "baseline-owned", "knative", "native-00001" + ) + inventory = { + "knativeApp": {("team-a", "native-00001-deployment-one")}, + "knativeQueueProxy": {("team-a", "native-00001-deployment-one")}, + } + samples = {} + for source in queries: + metric = {"scale_input": source} + if source.endswith(("Cpu", "Memory", "Phase")): + metric.update(namespace="team-a", pod="native-00001-deployment-one") + samples[tuple(sorted(metric.items()))] = 420 + self.assertTrue(scale.resource_coverage(samples, queries, inventory, {})) + for missing in ("knativeAppMemory", "knativeQueueProxyCpu"): + partial = { + identity: timestamp for identity, timestamp in samples.items() + if dict(identity)["scale_input"] != missing + } + self.assertFalse(scale.resource_coverage(partial, queries, inventory, {})) + joined = " ".join(queries.values()) + self.assertIn('container="app"', joined) + self.assertIn('container="queue-proxy"', joined) + self.assertNotIn("fiber-router", joined) + + def test_knative_ingress_options_are_rejected_before_cluster_work(self): + for extra in ( + ("--knative-ingress-url", "http://localhost:18080"), + ("--knative-context", "test"), + ("--knative-context", "stock", "--knative-ingress-url", "http://localhost/a"), + ): + with self.subTest(extra=extra), mock.patch.object( + scale.sys, "argv", self.main_arguments(*extra) + ), mock.patch.object(scale, "active_revision") as revision, mock.patch.object( + scale, "require_separate_knative" + ) as separate: + with self.assertRaises(ValueError): + scale.main() + revision.assert_not_called() + separate.assert_not_called() + + def test_stock_metrics_installer_excludes_lampyr_and_ui_resources(self): + source = [ + {"kind": "Namespace", "metadata": {"name": "lampyr-observability"}}, + {"kind": "ConfigMap", "metadata": { + "name": "prometheus", "namespace": "lampyr-observability", + }}, + {"kind": "ClusterRole", "metadata": { + "name": "lampyr-observability-kube-state-metrics", + }}, + {"kind": "NetworkPolicy", "metadata": { + "name": "prometheus", "namespace": "lampyr-system", + }}, + {"kind": "NetworkPolicy", "metadata": { + "name": "prometheus", "namespace": "lampyr-observability", + }}, + {"kind": "Deployment", "metadata": { + "name": "perses", "namespace": "lampyr-observability", + }}, + ] + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + fixture = root / "resources.json" + fixture.write_text(json.dumps(source)) + executable = root / "kubectl" + executable.write_text( + "#!/usr/bin/env python3\n" + "import json, os, pathlib, sys\n" + "assert sys.argv[1:3] == ['--context', 'stock']\n" + "if sys.argv[3] == 'create':\n" + " for item in json.loads(pathlib.Path(os.environ['FIXTURE']).read_text()):\n" + " print(json.dumps(item))\n" + "elif sys.argv[3] == 'apply':\n" + " pathlib.Path(os.environ['CAPTURE']).write_text(sys.stdin.read())\n" + ) + executable.chmod(0o755) + capture = root / "applied.json" + scale.subprocess.run( + ["bash", str(PATH.parent / "install-scale-metrics.sh"), "stock"], + check=True, stdout=scale.subprocess.DEVNULL, + env={ + **os.environ, + "PATH": f"{root}{os.pathsep}{os.environ['PATH']}", + "FIXTURE": str(fixture), "CAPTURE": str(capture), + }, + ) + self.assertEqual(json.loads(capture.read_text())["items"], source[:3]) + def test_scenario_rejects_missing_router_membership_at_both_endpoints(self): inventory = { "lampyrRouter": { From e9fbd47aefc494365697b2117382f0b774269bb8 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Tue, 24 Nov 2026 17:02:25 -0800 Subject: [PATCH 13/20] fixup! Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- scripts/tests/test_scale_test.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index 8e227ae..2435fc9 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -7,6 +7,8 @@ import tempfile import unittest from unittest import mock +import urllib.parse +import urllib.request PATH = Path(__file__).resolve().parents[1] / "scale-test.py" @@ -35,6 +37,33 @@ def test_duration_seconds(self): with self.assertRaises(ValueError): scale.duration_seconds(invalid) + def test_prometheus_queries_avoid_policy_blocked_service_proxy(self): + response = mock.MagicMock() + response.__enter__.return_value.read.return_value = json.dumps({ + "status": "success", + "data": {"result": [{"value": [420, "1"]}]}, + }).encode() + with mock.patch.object( + scale, "command", + side_effect=RuntimeError("NetworkPolicy blocks Service proxy traffic"), + ) as command, mock.patch( + "urllib.request.urlopen", return_value=response + ) as request: + self.assertEqual( + scale.prometheus_query( + "http://127.0.0.1:19090", 'up{job="fiber-router"}', 420 + ), + 1, + ) + command.assert_not_called() + url = urllib.parse.urlsplit(request.call_args.args[0]) + self.assertEqual(url.netloc, "127.0.0.1:19090") + self.assertEqual(url.path, "/api/v1/query") + self.assertEqual(urllib.parse.parse_qs(url.query), { + "query": ['up{job="fiber-router"}'], "time": ["420.000"], + }) + self.assertGreater(request.call_args.kwargs["timeout"], 0) + def test_report_compares_lampyr_and_kubernetes(self): result = { "metadata": { From 600f273af144783fd997d17980367c73fd81ae6d Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Tue, 24 Nov 2026 17:09:53 -0800 Subject: [PATCH 14/20] fixup! Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- docs/scale-testing.md | 6 +- scripts/scale-test.py | 135 +++++++++++++++++-------------- scripts/tests/test_scale_test.py | 106 +++++++++++++++++++++++- 3 files changed, 184 insertions(+), 63 deletions(-) diff --git a/docs/scale-testing.md b/docs/scale-testing.md index caae813..9252f36 100644 --- a/docs/scale-testing.md +++ b/docs/scale-testing.md @@ -48,8 +48,7 @@ bash scripts/install-scale-metrics.sh KNATIVE_CONTEXT This script requires `kubectl` and `jq`. It selects the metrics collectors from the shared manifest. It does not install Lampyr, UI services, tracing services, or Serving controllers. -Prometheus remains cluster-internal. The script omits the UI-only Prometheus -NetworkPolicy so the runner can query through the Kubernetes API proxy. +Prometheus remains cluster-internal. The script omits its UI-only NetworkPolicy. Add the Knative context to the runner: @@ -99,6 +98,9 @@ Both targets use a 10-second request timeout, including warmup. Cleanup removes only resources this run created. Custom JSON output names must not use the `.md` extension. The context must allow read access to the measured Pods. +It must also allow Pod port-forward access. The runner opens one local +Prometheus port-forward per cluster and closes it on exit. This path does not +need changes to the Lampyr add-on's Prometheus NetworkPolicy. Client latency, throughput, and HTTP success come from oha for all targets. CPU and memory come from each cluster's Prometheus, which scrapes kubelet diff --git a/scripts/scale-test.py b/scripts/scale-test.py index 0465ab9..10cfdcd 100644 --- a/scripts/scale-test.py +++ b/scripts/scale-test.py @@ -14,15 +14,12 @@ import tempfile import time import urllib.parse +import urllib.request import uuid BASELINE = "lampyr-scale-baseline" REQUEST_TIMEOUT = "10s" -PROMETHEUS_PROXY = ( - "/api/v1/namespaces/lampyr-observability/" - "services/http:prometheus:9090/proxy/api/v1/query" -) def command(*args): @@ -64,19 +61,21 @@ def active_revision(context, service, namespace): return next(iter(revisions)) -def prometheus_results(context, query, evaluation_time=None): +def prometheus_results(endpoint, query, evaluation_time=None): parameters = {"query": query} if evaluation_time is not None: parameters["time"] = f"{evaluation_time:.3f}" - path = PROMETHEUS_PROXY + "?" + urllib.parse.urlencode(parameters) - result = json.loads(command("kubectl", "--context", context, "get", "--raw", path)) + url = endpoint + "/api/v1/query?" + urllib.parse.urlencode(parameters) + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with opener.open(url, timeout=30) as response: + result = json.loads(response.read()) if result.get("status") != "success": raise RuntimeError(f"Prometheus query failed: {result}") return result["data"]["result"] -def prometheus_query(context, query, evaluation_time=None): - values = prometheus_results(context, query, evaluation_time) +def prometheus_query(endpoint, query, evaluation_time=None): + values = prometheus_results(endpoint, query, evaluation_time) if not values: return None if len(values) != 1: @@ -85,9 +84,9 @@ def prometheus_query(context, query, evaluation_time=None): return value if math.isfinite(value) else None -def router_scrapes(context, evaluation_time): +def router_scrapes(endpoint, evaluation_time): values = prometheus_results( - context, + endpoint, 'timestamp(up{job="fiber-router"}) * (up{job="fiber-router"} == bool 1)', evaluation_time, ) @@ -197,12 +196,12 @@ def resource_sample_queries(namespace, revision, baseline, target, knative=None) return queries -def resource_samples(context, queries, evaluation_time): +def resource_samples(endpoint, queries, evaluation_time): query = " or ".join( f'label_replace(({expression}), "scale_input", "{name}", "", "")' for name, expression in queries.items() ) - values = prometheus_results(context, query, evaluation_time) + values = prometheus_results(endpoint, query, evaluation_time) samples = {} sources = set() containers = {} @@ -347,19 +346,19 @@ def metric_queries(namespace, revision, window, baseline, window_seconds=30, kna } -def counter_snapshot(context, queries, evaluation_time=None): +def counter_snapshot(endpoint, queries, evaluation_time=None): return { - name: prometheus_query(context, query, evaluation_time) + name: prometheus_query(endpoint, query, evaluation_time) for name, query in queries.items() if name in COUNTER_METRICS } -def collect_metrics(context, queries, before, evaluation_time): +def collect_metrics(endpoint, queries, before, evaluation_time): collected = {} reset_metrics = {f"{name}Resets": name for name in COUNTER_METRICS} for name, query in queries.items(): - value = prometheus_query(context, query, evaluation_time) + value = prometheus_query(endpoint, query, evaluation_time) if name in reset_metrics: counter = reset_metrics[name] if value is None and before[counter] is not None: @@ -463,6 +462,51 @@ def free_port(): return listener.getsockname()[1] +@contextlib.contextmanager +def service_forward(context, namespace, name, remote_port, label): + port = free_port() + with tempfile.TemporaryFile(mode="w+") as log: + forward = subprocess.Popen( + [ + "kubectl", "--context", context, "--namespace", namespace, + "port-forward", f"service/{name}", f"{port}:{remote_port}", + "--address=127.0.0.1", + ], + stdout=log, + stderr=log, + ) + try: + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + if forward.poll() is not None: + log.seek(0) + raise RuntimeError( + f"{label} port-forward exited before becoming ready: {log.read()}" + ) + with socket.socket() as connection: + if connection.connect_ex(("127.0.0.1", port)) == 0: + break + time.sleep(0.1) + else: + raise RuntimeError(f"{label} port-forward did not become ready") + yield {"url": f"http://127.0.0.1:{port}/", "process": forward} + finally: + forward.terminate() + try: + forward.wait(timeout=5) + except subprocess.TimeoutExpired: + forward.kill() + forward.wait() + + +@contextlib.contextmanager +def prometheus_server(context): + with service_forward( + context, "lampyr-observability", "prometheus", 9090, "Prometheus" + ) as forward: + yield forward["url"].rstrip("/") + + @contextlib.contextmanager def baseline_server(context, image, replicas, namespace): if "@sha256:" not in image: @@ -470,7 +514,6 @@ def baseline_server(context, image, replicas, namespace): name = f"{BASELINE}-{uuid.uuid4().hex}" manifest = baseline_manifest(image, replicas, namespace, name) created = [] - forward = None try: for resource in manifest["items"]: kubectl_manifest(context, "create", resource) @@ -489,41 +532,10 @@ def baseline_server(context, image, replicas, namespace): ], check=True, ) - port = free_port() - forward = subprocess.Popen( - [ - "kubectl", - "--context", - context, - "--namespace", - namespace, - "port-forward", - f"service/{name}", - f"{port}:80", - ], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - ) - deadline = time.time() + 30 - while time.time() < deadline: - if forward.poll() is not None: - raise RuntimeError("baseline port-forward exited before becoming ready") - with socket.socket() as connection: - if connection.connect_ex(("127.0.0.1", port)) == 0: - break - time.sleep(0.1) - else: - raise RuntimeError("baseline port-forward did not become ready") - yield {"name": name, "url": f"http://127.0.0.1:{port}/", "process": forward} + with service_forward(context, namespace, name, 80, "baseline") as forward: + yield {"name": name, **forward} finally: original_error = sys.exc_info()[0] is not None - if forward is not None: - forward.terminate() - try: - forward.wait(timeout=5) - except subprocess.TimeoutExpired: - forward.kill() - forward.wait() if created: try: kubectl_manifest( @@ -950,7 +962,7 @@ def main(): ) as baseline, ( knative_server(args.knative_context, args.baseline_image, args.namespace) if args.knative_context else contextlib.nullcontext(None) - ) as knative: + ) as knative, contextlib.ExitStack() as metrics_forwards: metadata["baselineName"] = baseline["name"] baseline_url = urllib.parse.urlsplit(baseline["url"])._replace( path=lampyr_url.path, query=lampyr_url.query, fragment="" @@ -981,6 +993,10 @@ def main(): ))), } metadata["networkPaths"]["knative"] = "stock Knative ingress and queue-proxy" + metrics_endpoints = { + context: metrics_forwards.enter_context(prometheus_server(context)) + for context in dict.fromkeys(target[2] for target in targets) + } for target, url, context, host in targets: if target == "kubernetes": require_running(baseline["process"], "baseline port-forward") @@ -989,6 +1005,7 @@ def main(): time.sleep(6) for concurrency in concurrencies: for target, url, context, host in targets: + metrics_endpoint = metrics_endpoints[context] native_revision = knative["revision"] if target == "knative" else None if target == "kubernetes": require_running(baseline["process"], "baseline port-forward") @@ -1009,10 +1026,10 @@ def main(): knative=native_revision, ) before_scrapes = ( - {} if native_revision else router_scrapes(context, snapshot_time) + {} if native_revision else router_scrapes(metrics_endpoint, snapshot_time) ) before_resources = resource_samples( - context, sample_queries, snapshot_time + metrics_endpoint, sample_queries, snapshot_time ) if resource_coverage( before_resources, sample_queries, before_inventory, before_scrapes @@ -1031,7 +1048,7 @@ def main(): measurement_started = min([ *before_scrapes.values(), *before_resources.values() ]) - 0.001 - before = counter_snapshot(context, snapshot_queries, snapshot_time) + before = counter_snapshot(metrics_endpoint, snapshot_queries, snapshot_time) if not native_revision and before["lampyrRequests"] is None: raise RuntimeError( "Lampyr request metrics are missing after warmup; check the " @@ -1048,13 +1065,13 @@ def main(): for wait_seconds in (6, 5, 5, 5, 5, 5): time.sleep(wait_seconds) evaluated = time.time() - scrapes = {} if native_revision else router_scrapes(context, evaluated) + scrapes = {} if native_revision else router_scrapes(metrics_endpoint, evaluated) if scrapes.keys() != before_scrapes.keys() or any( timestamp < load_ended.timestamp() for timestamp in scrapes.values() ): continue - samples = resource_samples(context, sample_queries, evaluated) + samples = resource_samples(metrics_endpoint, sample_queries, evaluated) inventory = resource_inventory( context, args.namespace, revision, baseline["name"], target, knative=native_revision, @@ -1081,13 +1098,13 @@ def main(): ) resources = { name: prometheus_query( - context, queries[name], evaluated + metrics_endpoint, queries[name], evaluated ) for name in target_resource_names(target) } if target_resources_available(target, resources): platform = collect_metrics( - context, queries, before, evaluated + metrics_endpoint, queries, before, evaluated ) break else: diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index 2435fc9..331e497 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -1,10 +1,12 @@ import contextlib import hashlib +import http.server import importlib.util import json import os from pathlib import Path import tempfile +import threading import unittest from unittest import mock import urllib.parse @@ -47,7 +49,7 @@ def test_prometheus_queries_avoid_policy_blocked_service_proxy(self): scale, "command", side_effect=RuntimeError("NetworkPolicy blocks Service proxy traffic"), ) as command, mock.patch( - "urllib.request.urlopen", return_value=response + "urllib.request.OpenerDirector.open", return_value=response ) as request: self.assertEqual( scale.prometheus_query( @@ -64,6 +66,94 @@ def test_prometheus_queries_avoid_policy_blocked_service_proxy(self): }) self.assertGreater(request.call_args.kwargs["timeout"], 0) + def test_prometheus_queries_use_loopback_http_without_environment_proxy(self): + requests = [] + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + requests.append(self.path) + self.send_response(200) + self.end_headers() + self.wfile.write(json.dumps({ + "status": "success", + "data": {"result": [{"value": [420, "2"]}]}, + }).encode()) + + def log_message(self, *args): + pass + + with http.server.HTTPServer(("127.0.0.1", 0), Handler) as server: + worker = threading.Thread(target=server.serve_forever) + worker.start() + try: + with mock.patch.dict(os.environ, { + "http_proxy": "http://127.0.0.1:1", + "HTTP_PROXY": "http://127.0.0.1:1", + "no_proxy": "", "NO_PROXY": "", + }): + self.assertEqual(scale.prometheus_query( + f"http://127.0.0.1:{server.server_port}", "vector(2)", 420 + ), 2) + finally: + server.shutdown() + worker.join() + self.assertEqual(len(requests), 1) + query = urllib.parse.urlsplit(requests[0]) + self.assertEqual(query.path, "/api/v1/query") + self.assertEqual(urllib.parse.parse_qs(query.query), { + "query": ["vector(2)"], "time": ["420.000"], + }) + + def test_prometheus_forward_uses_selected_context_and_cleans_up_on_errors(self): + for failure in ("none", "query", "startup"): + forward = mock.Mock() + forward.poll.return_value = 1 if failure == "startup" else None + with self.subTest(failure=failure), mock.patch.object( + scale, "free_port", return_value=19090 + ), mock.patch.object( + scale.subprocess, "Popen", return_value=forward + ) as start, mock.patch.object(scale.socket, "socket") as socket: + socket.return_value.__enter__.return_value.connect_ex.return_value = 0 + + def query(): + with scale.prometheus_server("stock") as endpoint: + self.assertEqual(endpoint, "http://127.0.0.1:19090") + if failure == "query": + raise RuntimeError("query failed") + + if failure == "none": + query() + else: + message = "query failed" if failure == "query" else "exited" + with self.assertRaisesRegex(RuntimeError, message): + query() + start.assert_called_once() + self.assertEqual(start.call_args.args[0], [ + "kubectl", "--context", "stock", + "--namespace", "lampyr-observability", + "port-forward", "service/prometheus", "19090:9090", + "--address=127.0.0.1", + ]) + forward.terminate.assert_called_once() + forward.wait.assert_called_once_with(timeout=5) + + def test_prometheus_forward_startup_timeout_kills_unresponsive_process(self): + forward = mock.Mock(poll=mock.Mock(return_value=None)) + forward.wait.side_effect = [ + scale.subprocess.TimeoutExpired("kubectl", 5), None, + ] + with mock.patch.object( + scale, "free_port", return_value=19090 + ), mock.patch.object( + scale.subprocess, "Popen", return_value=forward + ), mock.patch.object(scale.time, "monotonic", side_effect=[0, 31]): + with self.assertRaisesRegex(RuntimeError, "did not become ready"): + with scale.prometheus_server("test"): + self.fail("unready Prometheus forward was accepted") + forward.terminate.assert_called_once() + forward.kill.assert_called_once() + self.assertEqual(forward.wait.call_count, 2) + def test_report_compares_lampyr_and_kubernetes(self): result = { "metadata": { @@ -497,6 +587,9 @@ def scenario_environment(self, routers, resources, inventory=None, arguments=()) scale, "command", return_value="{}" ), mock.patch.object( scale, "baseline_server", return_value=contextlib.nullcontext(baseline) + ), mock.patch.object( + scale, "prometheus_server", + side_effect=lambda context: contextlib.nullcontext(f"http://{context}.metrics"), ), mock.patch.object( scale, "warm_target" ), mock.patch.object( @@ -726,8 +819,17 @@ def test_knative_uses_its_own_metrics_and_matching_workload_with_ingress_host(se ) sample_calls = scale.resource_samples.call_args_list self.assertEqual([call.args[0] for call in sample_calls], [ - "test", "test", "test", "test", "stock", "stock", + "http://test.metrics", "http://test.metrics", + "http://test.metrics", "http://test.metrics", + "http://stock.metrics", "http://stock.metrics", + ]) + self.assertEqual(scale.prometheus_server.call_args_list, [ + mock.call("test"), mock.call("stock"), ]) + self.assertEqual( + [call.args[0] for call in scale.resource_inventory.call_args_list], + ["test", "test", "test", "test", "stock", "stock"], + ) self.assertEqual(scale.router_scrapes.call_count, 4) result = write.call_args.args[0] self.assertEqual( From 3d7de8138d507d4c451b1b0142d97cee18827933 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Tue, 24 Nov 2026 18:50:03 -0800 Subject: [PATCH 15/20] Measure verified scale-from-zero startup latency Signed-off-by: James Sturtevant --- Justfile | 6 +- docs/scale-testing.md | 36 ++- scripts/fiberd_grants.py | 43 +++- scripts/scale-test.py | 328 +++++++++++++++++++++++++--- scripts/tests/test_fiberd_grants.py | 36 +++ scripts/tests/test_scale_test.py | 117 ++++++++++ 6 files changed, 519 insertions(+), 47 deletions(-) diff --git a/Justfile b/Justfile index ebd1f0b..69bfa17 100644 --- a/Justfile +++ b/Justfile @@ -369,7 +369,7 @@ scale-baseline-image image: # Compare Lampyr with a Deployment and optionally stock Knative. [positional-arguments] -scale-test context service lampyr-url baseline-image duration="30s" concurrency="1,4,16,64" output="build/scale-results.json" knative-context="" knative-ingress-url="": install-oha +scale-test context service lampyr-url baseline-image duration="30s" concurrency="1,4,16,64" output="build/scale-results.json" knative-context="" knative-ingress-url="" startup-runs="3" startup-timeout="180s": install-oha python3 scripts/scale-test.py \ --context "$1" \ --service "$2" \ @@ -379,7 +379,9 @@ scale-test context service lampyr-url baseline-image duration="30s" concurrency= --concurrency "$6" \ --output "$7" \ --knative-context "$8" \ - --knative-ingress-url "$9" + --knative-ingress-url "$9" \ + --startup-runs "${10}" \ + --startup-timeout "${11}" # Run the repository test suites used in CI. test: test-unit test-cli examples-check test-preview-release cli::test cli::test-intent helper::test azure::test kind::test k3d::test test-examples-local test-kind-integration test-k3d-integration test-existing-kind-integration test-knative-portability test-walkthrough diff --git a/docs/scale-testing.md b/docs/scale-testing.md index 9252f36..a5b2ff4 100644 --- a/docs/scale-testing.md +++ b/docs/scale-testing.md @@ -64,8 +64,8 @@ python3 scripts/scale-test.py \ The runner creates a temporary Knative Service with the same image digest as the Deployment. Both use a 768 MiB application memory limit. Knative uses `min-scale=1` and `max-scale=1`; the client controls request concurrency. -The runner removes only the Service it created. This is a warm, fixed-capacity -comparison, not a cold-start or autoscaling test. +The runner removes only the Service it created. This target is for the warm, +fixed-capacity phase. The startup phase uses a separate scale-to-zero Service. The Knative Service URL must be reachable from the load generator. For local ingress exposed on a different address or port, add @@ -75,13 +75,39 @@ the Lampyr request path and query for both warmup and load. ## Measurements +The runner first measures startup three times for each target: + +- Lampyr: wait for zero Fibers, keep the same Ready home, and time one request. +- Knative: wait for zero Revision Pods and zero actual and desired scale, then + time one request through its ingress and activator. +- Deployment: wait for zero Pods, then time the scale request to one Ready Pod. + This is Pod startup, not request-triggered activation. + +The Lampyr check reads the home's fiberd audit records. It rejects missing or +invalid records, a home restart, and a request that does not create exactly one +new Fiber. A zero busy-Fiber metric alone is not proof of zero Fibers. +Use a Service with no other traffic. The context must allow `exec` in its +fiberd container to read the audit file. + +The startup Knative Service is separate from the warm target. It permits zero +replicas, has a six-second autoscaling window, and keeps at most one replica. +The runner waits for scale-to-zero without sending probe requests. Each trial +sends exactly one request, with no retry. A failed first request stops the run. +Images and snapshots stay cached; these are not image-download measurements. + +`--startup-runs COUNT` sets the number of trials; `0` keeps only warm traffic. +`--startup-timeout 180s` bounds each wait and first request. The JSON has a +separate `startups` array, and Markdown has a separate startup table. Startup +durations do not enter the warm latency or throughput statistics. + The default sweep runs each target for 30 seconds at concurrency 1, 4, 16, -and 64. The framework: +and 64. Lampyr's default fresh execution mode still creates a Fiber for each +request. Warm traffic does not imply live-Fiber reuse. The framework: - creates a temporary one-replica Deployment and Service with unique names; - creates a stock Knative Service when a Knative context is supplied; -- warms both targets; -- runs the same client against Lampyr and Kubernetes; +- warms all targets; +- runs the same client against each selected target; - queries Prometheus for request, Fiber, CPU, and memory measurements; - writes `build/scale-results.json` after every scenario; and - writes a concise Markdown comparison beside it. diff --git a/scripts/fiberd_grants.py b/scripts/fiberd_grants.py index 23aa12d..7616a83 100644 --- a/scripts/fiberd_grants.py +++ b/scripts/fiberd_grants.py @@ -130,27 +130,62 @@ def home_pod(context, resource): return running_home(pods) -def audit_records(context, home): +def audit_records(context, home, namespace="default", strict=False, timeout=60): """fiberd's audit records for the grant Pod `home`.""" raw = kubectl(context, "exec", f"pod/{home.name}", "--container", "fiberd", "--", - "cat", AUDIT_SPOOL) - return grant_records(raw, home.uid) + "cat", AUDIT_SPOOL, namespace=namespace, timeout=timeout) + return grant_records(raw, home.uid, strict=strict) -def grant_records(raw, pod_uid): +def grant_records(raw, pod_uid, strict=False): """The records of `raw` that fiberd stamped with the grant Pod's UID. fiberd's Fence has no JSON tags, so its fields keep their Go names.""" records = [] + sequence = 0 for line in raw.splitlines(): try: record = json.loads(line) except json.JSONDecodeError: + if strict: + raise RuntimeError("cannot verify zero Fibers: invalid audit record") continue + if strict: + if not isinstance(record, dict) or record.get("seq") != sequence + 1: + raise RuntimeError("cannot verify zero Fibers: incomplete audit sequence") + sequence = record["seq"] + if strict and record.get("event") == "gap": + raise RuntimeError("cannot verify zero Fibers: audit records are missing") if record.get("fence", {}).get("GrantUID") == pod_uid: records.append(record) return records +def live_fibers(records): + current_epoch = epoch(records) + current = [ + record for record in records + if record.get("fence", {}).get("Epoch") == current_epoch + ] + if not current_epoch or not any(record["event"] == "admit" for record in current): + raise RuntimeError("cannot verify zero Fibers: home admission audit is missing") + live = set() + ended = {"release", "park", "oom", "exit", "signal", "yield", "scope-revoked", "orphan"} + for record in current: + event = record["event"] + fiber = record.get("fiber_id") + if event in STARTS: + if not fiber: + raise RuntimeError("cannot verify zero Fibers: audit Fiber ID is missing") + live.add(fiber) + elif event in ended: + if not fiber: + raise RuntimeError("cannot verify zero Fibers: audit Fiber ID is missing") + live.discard(fiber) + elif fiber: + raise RuntimeError(f"cannot verify zero Fibers: unknown audit event {event}") + return live + + def fibers_started(records): return sum(1 for record in records if record.get("event") in STARTS) diff --git a/scripts/scale-test.py b/scripts/scale-test.py index 10cfdcd..005aa35 100644 --- a/scripts/scale-test.py +++ b/scripts/scale-test.py @@ -17,6 +17,8 @@ import urllib.request import uuid +import fiberd_grants + BASELINE = "lampyr-scale-baseline" REQUEST_TIMEOUT = "10s" @@ -508,7 +510,7 @@ def prometheus_server(context): @contextlib.contextmanager -def baseline_server(context, image, replicas, namespace): +def baseline_resources(context, image, replicas, namespace): if "@sha256:" not in image: raise ValueError("baseline image must be digest-pinned") name = f"{BASELINE}-{uuid.uuid4().hex}" @@ -518,22 +520,7 @@ def baseline_server(context, image, replicas, namespace): for resource in manifest["items"]: kubectl_manifest(context, "create", resource) created.append(resource) - subprocess.run( - [ - "kubectl", - "--context", - context, - "--namespace", - namespace, - "rollout", - "status", - f"deployment/{name}", - "--timeout=300s", - ], - check=True, - ) - with service_forward(context, namespace, name, 80, "baseline") as forward: - yield {"name": name, **forward} + yield name finally: original_error = sys.exc_info()[0] is not None if created: @@ -551,6 +538,17 @@ def baseline_server(context, image, replicas, namespace): print(f"warning: baseline cleanup failed: {error}", file=sys.stderr) +@contextlib.contextmanager +def baseline_server(context, image, replicas, namespace): + with baseline_resources(context, image, replicas, namespace) as name: + subprocess.run([ + "kubectl", "--context", context, "--namespace", namespace, + "rollout", "status", f"deployment/{name}", "--timeout=300s", + ], check=True) + with service_forward(context, namespace, name, 80, "baseline") as forward: + yield {"name": name, **forward} + + def require_separate_knative(context, lampyr_context): identities = [ json.loads(command( @@ -568,7 +566,7 @@ def require_separate_knative(context, lampyr_context): raise ValueError("Knative target cluster must not have Lampyr installed") -def knative_manifest(image, namespace, name): +def knative_manifest(image, namespace, name, min_scale=1): container = baseline_manifest(image, 1, namespace, name)["items"][0][ "spec" ]["template"]["spec"]["containers"][0] @@ -580,8 +578,9 @@ def knative_manifest(image, namespace, name): "metadata": {"name": name, "namespace": namespace}, "spec": {"template": { "metadata": {"annotations": { - "autoscaling.knative.dev/min-scale": "1", + "autoscaling.knative.dev/min-scale": str(min_scale), "autoscaling.knative.dev/max-scale": "1", + **({"autoscaling.knative.dev/window": "6s"} if min_scale == 0 else {}), }}, "spec": {"containerConcurrency": 0, "containers": [container]}, }}, @@ -589,11 +588,11 @@ def knative_manifest(image, namespace, name): @contextlib.contextmanager -def knative_server(context, image, namespace): +def knative_server(context, image, namespace, min_scale=1): if "@sha256:" not in image: raise ValueError("Knative image must be digest-pinned") name = f"scale-knative-{uuid.uuid4().hex[:24]}" - manifest = knative_manifest(image, namespace, name) + manifest = knative_manifest(image, namespace, name, min_scale) created = False try: kubectl_manifest(context, "create", manifest) @@ -631,16 +630,16 @@ def require_running(process, name): raise RuntimeError(f"{name} exited with status {return_code}") -def run_oha(oha, url, duration, concurrency, host=None): +def run_oha(oha, url, duration, concurrency, host=None, single=False): + request_timeout = duration if single else REQUEST_TIMEOUT output = subprocess.check_output( [ str(oha), - "-z", - duration, + *(["-n", "1"] if single else ["-z", duration]), "-c", str(concurrency), "-t", - REQUEST_TIMEOUT, + request_timeout, "--wait-ongoing-requests-after-deadline", "--stats-success-breakdown", "--no-tui", @@ -651,7 +650,10 @@ def run_oha(oha, url, duration, concurrency, host=None): url, ], text=True, - timeout=duration_seconds(duration) + duration_seconds(REQUEST_TIMEOUT) + 5, + timeout=( + duration_seconds(request_timeout) + 5 if single else + duration_seconds(duration) + duration_seconds(request_timeout) + 5 + ), ) result = json.loads(output) client = { @@ -668,6 +670,233 @@ def run_oha(oha, url, duration, concurrency, host=None): return client +def startup_pods(context, namespace, selector, timeout=15): + return json.loads(fiberd_grants.kubectl( + context, "get", "pods", "--selector", selector, "--output", "json", + namespace=namespace, timeout=min(15, timeout), + ))["items"] + + +def wait_startup_state(check, timeout, description): + deadline = time.monotonic() + timeout + while (remaining := deadline - time.monotonic()) > 0: + state = check(remaining) + remaining = deadline - time.monotonic() + if remaining <= 0: + break + if state is not None: + return state + time.sleep(min(0.5, remaining)) + raise RuntimeError(f"startup timed out waiting for {description}") + + +def startup_remaining(deadline): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise RuntimeError("startup observation timed out") + return remaining + + +def ready_pod(pods): + if len(pods) != 1: + return None + pod = pods[0] + if "deletionTimestamp" in pod["metadata"] or not any( + item["type"] == "Ready" and item["status"] == "True" + for item in pod.get("status", {}).get("conditions", []) + ): + return None + return pod + + +def lampyr_startup_state(context, namespace, revision, timeout=60): + deadline = time.monotonic() + timeout + pod = ready_pod(startup_pods( + context, namespace, + f"lampyr.dev/home=true,serving.knative.dev/revision={revision}", + timeout=startup_remaining(deadline), + )) + if pod is None: + raise RuntimeError("startup requires one Ready Lampyr home that stays running") + statuses = [ + item for item in pod["status"]["containerStatuses"] if item["name"] == "fiberd" + ] + if len(statuses) != 1 or "running" not in statuses[0]["state"]: + raise RuntimeError("startup requires a running fiberd container") + home = fiberd_grants.Home(pod["metadata"]["name"], pod["metadata"]["uid"]) + records = fiberd_grants.audit_records( + context, home, namespace=namespace, strict=True, + timeout=startup_remaining(deadline), + ) + live = fiberd_grants.live_fibers(records) + startup_remaining(deadline) + return { + "home": { + "name": home.name, "uid": home.uid, + "containerStartedAt": statuses[0]["state"]["running"]["startedAt"], + "restartCount": statuses[0]["restartCount"], + }, + "epoch": fiberd_grants.epoch(records), + "fiberCount": len(live), + "auditSeq": max(record["seq"] for record in records), + }, records + + +def first_request(oha, url, timeout, host=None): + client = run_oha(oha, url, f"{timeout}s", 1, host=host, single=True) + count = sum(client["statusCodeDistribution"].values()) + sum( + client["errorDistribution"].values() + ) + if count != 1 or client["httpSuccessRate"] != 1: + raise RuntimeError( + "startup first request failed; no retry was made: " + f"statuses={client['statusCodeDistribution']} errors={client['errorDistribution']}" + ) + return client + + +def lampyr_startup(oha, context, namespace, revision, url, timeout): + initial, _ = lampyr_startup_state(context, namespace, revision, timeout=timeout) + + def zero(remaining): + state, _ = lampyr_startup_state(context, namespace, revision, timeout=remaining) + if state["home"] != initial["home"] or state["epoch"] != initial["epoch"]: + raise RuntimeError("Lampyr home restarted while waiting for zero Fibers") + return state if state["fiberCount"] == 0 else None + + before = wait_startup_state(zero, timeout, "zero Lampyr Fibers") + client = first_request(oha, url, timeout) + after, records = lampyr_startup_state(context, namespace, revision, timeout=timeout) + if after["home"] != before["home"] or after["epoch"] != before["epoch"]: + raise RuntimeError("Lampyr home restarted during the startup request") + starts = [ + record for record in records + if record["seq"] > before["auditSeq"] and record["event"] in fiberd_grants.STARTS + ] + if len(starts) != 1 or starts[0]["event"] != "create": + raise RuntimeError("startup request must create exactly one fresh Lampyr Fiber") + return { + "target": "lampyr", "measurement": "zero Fibers to first response", + "durationMs": client["summary"]["average"] * 1000, + "before": before, "after": after, "client": client, + } + + +def deployment_startup(context, namespace, name, timeout): + selector = f"app={name}" + fiberd_grants.kubectl( + context, "scale", f"deployment/{name}", "--replicas=0", + namespace=namespace, timeout=15, + ) + wait_startup_state( + lambda remaining: {"podCount": 0} if not startup_pods( + context, namespace, selector, timeout=remaining + ) else None, + timeout, "zero Deployment Pods", + ) + started = time.monotonic() + fiberd_grants.kubectl( + context, "scale", f"deployment/{name}", "--replicas=1", + namespace=namespace, timeout=15, + ) + pod = wait_startup_state( + lambda remaining: ready_pod(startup_pods( + context, namespace, selector, timeout=remaining + )), + timeout, "Deployment Pod Ready", + ) + return { + "target": "kubernetes", "measurement": "scale from zero to Pod Ready", + "durationMs": (time.monotonic() - started) * 1000, + "before": {"podCount": 0}, + "after": { + "podCount": 1, "pod": pod["metadata"]["name"], + "uid": pod["metadata"]["uid"], "createdAt": pod["metadata"]["creationTimestamp"], + }, + } + + +def knative_startup(oha, context, namespace, native, url, host, timeout): + revision = native["revision"] + selector = f"serving.knative.dev/revision={revision}" + + def zero(remaining): + deadline = time.monotonic() + remaining + autoscaler = json.loads(fiberd_grants.kubectl( + context, "get", "podautoscalers.autoscaling.internal.knative.dev", revision, + "--output", "json", namespace=namespace, + timeout=min(15, startup_remaining(deadline)), + )) + status = autoscaler.get("status", {}) + if ( + status.get("actualScale") == 0 and status.get("desiredScale") == 0 + and not startup_pods( + context, namespace, selector, timeout=startup_remaining(deadline) + ) + ): + return {"podCount": 0, "actualScale": 0, "desiredScale": 0} + return None + + before = wait_startup_state(zero, timeout, "Knative scale-to-zero") + client = first_request(oha, url, timeout, host) + pod = wait_startup_state( + lambda remaining: ready_pod(startup_pods( + context, namespace, selector, timeout=remaining + )), + timeout, "activated Knative Pod Ready", + ) + return { + "target": "knative", "measurement": "zero replicas to first response", + "durationMs": client["summary"]["average"] * 1000, + "before": before, + "after": {"podCount": 1, "uid": pod["metadata"]["uid"]}, + "client": client, + } + + +def matching_url(origin, workload): + return origin._replace( + path=workload.path, query=workload.query, fragment="" + ).geturl() + + +def measure_startups(args, oha, revision, workload, ingress, result, output): + timeout = duration_seconds(args.startup_timeout) + with baseline_resources( + args.context, args.baseline_image, 0, args.namespace + ) as deployment, ( + knative_server(args.knative_context, args.baseline_image, args.namespace, min_scale=0) + if args.knative_context else contextlib.nullcontext(None) + ) as native: + if native: + result["metadata"]["startupKnative"] = { + "service": native["name"], "revision": native["revision"], + "minScale": 0, "maxScale": 1, "window": "6s", + } + for trial in range(1, args.startup_runs + 1): + targets = [ + ("lampyr", lambda: lampyr_startup( + oha, args.context, args.namespace, revision, workload.geturl(), timeout + )), + ("kubernetes", lambda: deployment_startup( + args.context, args.namespace, deployment, timeout + )), + ] + if native: + targets.append(("knative", lambda: knative_startup( + oha, args.knative_context, args.namespace, native, + matching_url(ingress or native["url"], workload), + native["url"].netloc if ingress else None, timeout, + ))) + for target, measure in targets: + value = measure() + value["trial"] = trial + result["startups"].append(value) + write_json(result, output) + write_report(result, output.with_suffix(".md")) + print(f"{target} startup trial={trial} duration={value['durationMs']:.2f}ms") + + def http_success_rate(client): statuses = client.get("statusCodeDistribution", {}) errors = client.get("errorDistribution", {}) @@ -780,6 +1009,26 @@ def write_report(result, path): if "knative" in result["metadata"]["networkPaths"] else [] ), "", + ] + if result.get("startups"): + lines += [ + "## Startup", + "", + "Lampyr keeps its home running with zero Fibers. Knative starts from zero", + "replicas. Deployment timing starts before its scale request and ends when", + "one Pod is Ready; it is not request-triggered activation.", + "Images and snapshots are not removed from node caches.", + "", + "| Target | Trial | Measurement | Duration ms |", + "|---|---:|---|---:|", + ] + for startup in result["startups"]: + lines.append( + f"| {startup['target']} | {startup['trial']} | " + f"{startup['measurement']} | {startup['durationMs']:.2f} |" + ) + lines += ["", "## Warm traffic", ""] + lines += [ "| Target | Concurrency | Requests/s | HTTP success | p50 ms | p95 ms | p99 ms | Platform errors | Shed | CPU cores | Peak memory MiB |", "|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|", ] @@ -891,6 +1140,8 @@ def main(): parser.add_argument("--baseline-replicas", type=int, default=1) parser.add_argument("--duration", default="30s") parser.add_argument("--concurrency", default="1,4,16,64") + parser.add_argument("--startup-runs", type=int, default=3) + parser.add_argument("--startup-timeout", default="180s") parser.add_argument("--oha", default="build/tools/oha") parser.add_argument("--output", default="build/scale-results.json") args = parser.parse_args() @@ -903,6 +1154,9 @@ def main(): raise ValueError("concurrency values must be positive integers") if args.baseline_replicas != 1: raise ValueError("baseline must use one replica with Service port-forward") + if args.startup_runs < 0: + raise ValueError("startup runs must be zero or a positive integer") + duration_seconds(args.startup_timeout) output = Path(args.output) if output.suffix.lower() == ".md": raise ValueError("JSON and Markdown output files must be distinct; do not use .md") @@ -934,6 +1188,8 @@ def main(): "duration": args.duration, "requestTimeout": REQUEST_TIMEOUT, "concurrency": concurrencies, + "startupRuns": args.startup_runs, + "startupTimeout": args.startup_timeout, "commit": command("git", "rev-parse", "HEAD"), "dirty": bool(command("git", "status", "--porcelain")), "ohaVersion": command(str(oha), "--version"), @@ -956,7 +1212,7 @@ def main(): ) ), } - result = {"schema": 1, "metadata": metadata, "scenarios": []} + result = {"schema": 1, "metadata": metadata, "scenarios": [], "startups": []} with baseline_server( args.context, args.baseline_image, args.baseline_replicas, args.namespace ) as baseline, ( @@ -964,27 +1220,23 @@ def main(): if args.knative_context else contextlib.nullcontext(None) ) as knative, contextlib.ExitStack() as metrics_forwards: metadata["baselineName"] = baseline["name"] - baseline_url = urllib.parse.urlsplit(baseline["url"])._replace( - path=lampyr_url.path, query=lampyr_url.query, fragment="" - ) + baseline_url = matching_url(urllib.parse.urlsplit(baseline["url"]), lampyr_url) targets = [ ("lampyr", lampyr_url.geturl(), args.context, None), - ("kubernetes", baseline_url.geturl(), args.context, None), + ("kubernetes", baseline_url, args.context, None), ] if knative: route = knative["url"] - native_url = (knative_ingress or route)._replace( - path=lampyr_url.path, query=lampyr_url.query, fragment="" - ) + native_url = matching_url(knative_ingress or route, lampyr_url) targets.append(( - "knative", native_url.geturl(), args.knative_context, + "knative", native_url, args.knative_context, route.netloc if knative_ingress else None, )) metadata["knative"] = { "context": args.knative_context, "service": knative["name"], "revision": knative["revision"], - "url": safe_url(native_url.geturl()), + "url": safe_url(native_url), "minScale": 1, "maxScale": 1, "nodes": node_summary(json.loads(command( @@ -993,6 +1245,10 @@ def main(): ))), } metadata["networkPaths"]["knative"] = "stock Knative ingress and queue-proxy" + if args.startup_runs: + measure_startups( + args, oha, revision, lampyr_url, knative_ingress, result, output + ) metrics_endpoints = { context: metrics_forwards.enter_context(prometheus_server(context)) for context in dict.fromkeys(target[2] for target in targets) diff --git a/scripts/tests/test_fiberd_grants.py b/scripts/tests/test_fiberd_grants.py index 6b254b8..6416464 100644 --- a/scripts/tests/test_fiberd_grants.py +++ b/scripts/tests/test_fiberd_grants.py @@ -124,9 +124,45 @@ def test_the_audit_spool_is_read_from_the_home_and_kept_for_its_uid(self): kubectl.assert_called_once_with( "kind-test", "exec", "pod/home", "--container", "fiberd", "--", "cat", fiberd_grants.AUDIT_SPOOL, + namespace="default", + timeout=60, ) self.assertEqual([record["fence"]["GrantUID"] for record in records], ["pod-2"]) + def test_live_fibers_include_idle_fibers_and_only_the_current_epoch(self): + records = [ + {"event": "admit", "fence": {"Epoch": 1}}, + {"event": "create", "fiber_id": "one", "fence": {"Epoch": 1}}, + {"event": "create", "fiber_id": "idle", "fence": {"Epoch": 1}}, + {"event": "release", "fiber_id": "one", "fence": {"Epoch": 1}}, + ] + self.assertEqual(fiberd_grants.live_fibers(records), {"idle"}) + records.append({"event": "admit", "fence": {"Epoch": 2}}) + self.assertEqual(fiberd_grants.live_fibers(records), set()) + with self.assertRaisesRegex(RuntimeError, "admission audit is missing"): + fiberd_grants.live_fibers([]) + with self.assertRaisesRegex(RuntimeError, "Fiber ID is missing"): + fiberd_grants.live_fibers([ + {"event": "admit", "fence": {"Epoch": 1}}, + {"event": "create", "fence": {"Epoch": 1}}, + ]) + + def test_strict_audit_rejects_gaps_torn_records_and_missing_sequence(self): + admission = { + "seq": 1, "event": "admit", "fence": {"GrantUID": "home", "Epoch": 1}, + } + complete = json.dumps(admission) + self.assertEqual( + fiberd_grants.grant_records(complete, "home", strict=True), [admission] + ) + for raw in ( + complete + "\n{torn", + complete + "\n" + json.dumps({"seq": 2, "event": "gap"}), + json.dumps({**admission, "seq": 2}), + ): + with self.subTest(raw=raw), self.assertRaisesRegex(RuntimeError, "cannot verify"): + fiberd_grants.grant_records(raw, "home", strict=True) + def test_busy_fibers_are_the_revision_series_of_the_router_gauge(self): metrics = "\n".join([ "# HELP lampyr_router_fibers_busy Fibers serving a request right now.", diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index 331e497..a499d1c 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -5,6 +5,7 @@ import json import os from pathlib import Path +import sys import tempfile import threading import unittest @@ -14,6 +15,7 @@ PATH = Path(__file__).resolve().parents[1] / "scale-test.py" +sys.path.insert(0, str(PATH.parent)) SPEC = importlib.util.spec_from_file_location("scale_test", PATH) scale = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(scale) @@ -29,6 +31,7 @@ def main_arguments(self, *extra): "--baseline-image", "example.test/baseline@sha256:abc", "--oha", str(PATH), "--concurrency", "1", + "--startup-runs", "0", *extra, ] @@ -39,6 +42,120 @@ def test_duration_seconds(self): with self.assertRaises(ValueError): scale.duration_seconds(invalid) + def test_lampyr_startup_waits_for_idle_fibers_and_keeps_home_running(self): + home = {"uid": "home", "containerStartedAt": "now", "restartCount": 0} + busy = {"home": home, "epoch": 1, "fiberCount": 1, "auditSeq": 2} + zero = {**busy, "fiberCount": 0, "auditSeq": 3} + after = {**zero, "auditSeq": 5} + records = [{"seq": 4, "event": "create"}, {"seq": 5, "event": "release"}] + client = {"summary": {"average": 0.25}} + with mock.patch.object(scale, "lampyr_startup_state", side_effect=[ + (busy, []), (busy, []), (zero, []), (after, records), + ]) as observe, mock.patch.object( + scale, "first_request", return_value=client + ) as request, mock.patch.object(scale.time, "sleep") as sleep: + result = scale.lampyr_startup( + "oha", "test", "team-a", "revision", "https://app.test/a?b=1", 180 + ) + self.assertEqual(result["durationMs"], 250) + self.assertEqual(result["before"]["fiberCount"], 0) + request.assert_called_once_with("oha", "https://app.test/a?b=1", 180) + self.assertEqual(observe.call_count, 4) + sleep.assert_called_once_with(0.5) + + def test_lampyr_startup_rejects_home_restart_or_extra_fiber(self): + zero = { + "home": {"uid": "home", "restartCount": 0}, + "epoch": 1, "fiberCount": 0, "auditSeq": 1, + } + for after, records, error in ( + ({**zero, "home": {"uid": "replacement"}}, [], "home restarted"), + ({**zero, "epoch": 2}, [], "home restarted"), + (zero, [{"seq": 2, "event": "resume"}], "exactly one fresh"), + (zero, [{"seq": 2, "event": "create"}, {"seq": 3, "event": "create"}], + "exactly one fresh"), + ): + with self.subTest(error=error), mock.patch.object( + scale, "lampyr_startup_state", + side_effect=[(zero, []), (zero, []), (after, records)], + ), mock.patch.object(scale, "first_request"): + with self.assertRaisesRegex(RuntimeError, error): + scale.lampyr_startup("oha", "test", "default", "revision", "url", 180) + + def test_deployment_startup_requires_no_pods_before_scaling_up(self): + old = {"metadata": {"name": "terminating", "deletionTimestamp": "now"}} + ready = { + "metadata": {"name": "new", "uid": "new-uid", "creationTimestamp": "now"}, + "status": {"conditions": [{"type": "Ready", "status": "True"}]}, + } + with mock.patch.object( + scale, "startup_pods", side_effect=[[old], [], [], [ready]] + ), mock.patch.object(scale.fiberd_grants, "kubectl") as kubectl, mock.patch.object( + scale.time, "sleep" + ): + result = scale.deployment_startup("test", "team-a", "owned", 180) + self.assertEqual(result["after"]["uid"], "new-uid") + self.assertEqual( + [call.args[3] for call in kubectl.call_args_list], ["--replicas=0", "--replicas=1"] + ) + self.assertTrue(all( + call.kwargs["namespace"] == "team-a" for call in kubectl.call_args_list + )) + + def test_knative_startup_waits_for_actual_zero_without_http_probes(self): + ready = { + "metadata": {"uid": "activated"}, + "status": {"conditions": [{"type": "Ready", "status": "True"}]}, + } + client = {"summary": {"average": 1.25}} + activating = { + **ready, "status": {"conditions": [{"type": "Ready", "status": "False"}]}, + } + with mock.patch.object( + scale.fiberd_grants, "kubectl", side_effect=[ + '{"status":{"desiredScale":0}}', + '{"status":{"desiredScale":0,"actualScale":1}}', + '{"status":{"desiredScale":0,"actualScale":0}}', + '{"status":{"desiredScale":0,"actualScale":0}}', + ], + ), mock.patch.object( + scale, "startup_pods", side_effect=[[ready], [], [activating], [ready]] + ), mock.patch.object( + scale, "first_request", return_value=client + ) as request, mock.patch.object(scale.time, "sleep"): + result = scale.knative_startup( + "oha", "stock", "team-a", {"revision": "native"}, + "http://127.0.0.1/a%2Fb?size=64", "native.test", 180, + ) + self.assertEqual(result["durationMs"], 1250) + self.assertEqual(result["before"]["actualScale"], 0) + request.assert_called_once_with( + "oha", "http://127.0.0.1/a%2Fb?size=64", 180, "native.test" + ) + annotations = scale.knative_manifest("image", "team-a", "name", min_scale=0)[ + "spec" + ]["template"]["metadata"]["annotations"] + self.assertEqual(annotations["autoscaling.knative.dev/min-scale"], "0") + + def test_startup_wait_rejects_an_observation_that_finishes_after_deadline(self): + check = mock.Mock(return_value={"podCount": 0}) + with mock.patch.object(scale.time, "monotonic", side_effect=[0, 0, 61]): + with self.assertRaisesRegex(RuntimeError, "timed out"): + scale.wait_startup_state(check, 1, "zero Pods") + check.assert_called_once_with(1) + + def test_startup_first_request_does_not_retry_a_failed_request(self): + failed = { + "statusCodeDistribution": {"503": 1}, + "errorDistribution": {}, "httpSuccessRate": 0, + } + with mock.patch.object(scale, "run_oha", return_value=failed) as request: + with self.assertRaisesRegex(RuntimeError, "no retry was made"): + scale.first_request("oha", "http://app.test/", 180) + request.assert_called_once_with( + "oha", "http://app.test/", "180s", 1, host=None, single=True + ) + def test_prometheus_queries_avoid_policy_blocked_service_proxy(self): response = mock.MagicMock() response.__enter__.return_value.read.return_value = json.dumps({ From 49e8c737e0f11efdfa926eca49270c0f57cd98ec Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Tue, 24 Nov 2026 19:00:18 -0800 Subject: [PATCH 16/20] fixup! Measure verified scale-from-zero startup latency Signed-off-by: James Sturtevant --- scripts/tests/test_scale_test.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index a499d1c..554348a 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -775,6 +775,24 @@ def test_scenario_accepts_fresh_resource_samples(self): scale.main() self.assertEqual(len(write.call_args.args[0]["scenarios"]), 2) + def test_startups_finish_before_any_warm_capacity_is_created(self): + with self.scenario_environment( + [{"router-1": 420}] * 20, + [{"container-1": 420, "kube-state": 420}] * 20, + arguments=("--startup-runs", "1"), + ), mock.patch.object(scale, "measure_startups") as startup: + baseline = scale.baseline_server.return_value + + def warm(*args): + self.assertTrue( + startup.called, "warm resources started before startup measurements" + ) + return baseline + + scale.baseline_server.side_effect = warm + scale.main() + startup.assert_called_once() + def test_warmup_and_load_use_identical_request_paths_and_queries(self): for lampyr, baseline in ( ("https://example.test/", "http://localhost/"), From bfedd3438f712c02e2a424a920c3c5d8946b2a10 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Tue, 24 Nov 2026 19:05:24 -0800 Subject: [PATCH 17/20] fixup! Measure verified scale-from-zero startup latency Signed-off-by: James Sturtevant --- docs/scale-testing.md | 3 +++ scripts/scale-test.py | 23 ++++++++++++++--------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/docs/scale-testing.md b/docs/scale-testing.md index a5b2ff4..02774a7 100644 --- a/docs/scale-testing.md +++ b/docs/scale-testing.md @@ -94,6 +94,9 @@ replicas, has a six-second autoscaling window, and keeps at most one replica. The runner waits for scale-to-zero without sending probe requests. Each trial sends exactly one request, with no retry. A failed first request stops the run. Images and snapshots stay cached; these are not image-download measurements. +The runner prepares the startup Deployment once before scaling it to zero. +Startup resources are removed before the warm targets are created, so the two +phases do not reserve application capacity at the same time. `--startup-runs COUNT` sets the number of trials; `0` keeps only warm traffic. `--startup-timeout 180s` bounds each wait and first request. The JSON has a diff --git a/scripts/scale-test.py b/scripts/scale-test.py index 005aa35..5de5bf2 100644 --- a/scripts/scale-test.py +++ b/scripts/scale-test.py @@ -541,14 +541,18 @@ def baseline_resources(context, image, replicas, namespace): @contextlib.contextmanager def baseline_server(context, image, replicas, namespace): with baseline_resources(context, image, replicas, namespace) as name: - subprocess.run([ - "kubectl", "--context", context, "--namespace", namespace, - "rollout", "status", f"deployment/{name}", "--timeout=300s", - ], check=True) + wait_deployment_ready(context, namespace, name) with service_forward(context, namespace, name, 80, "baseline") as forward: yield {"name": name, **forward} +def wait_deployment_ready(context, namespace, name): + subprocess.run([ + "kubectl", "--context", context, "--namespace", namespace, + "rollout", "status", f"deployment/{name}", "--timeout=300s", + ], check=True) + + def require_separate_knative(context, lampyr_context): identities = [ json.loads(command( @@ -863,11 +867,12 @@ def matching_url(origin, workload): def measure_startups(args, oha, revision, workload, ingress, result, output): timeout = duration_seconds(args.startup_timeout) with baseline_resources( - args.context, args.baseline_image, 0, args.namespace + args.context, args.baseline_image, 1, args.namespace ) as deployment, ( knative_server(args.knative_context, args.baseline_image, args.namespace, min_scale=0) if args.knative_context else contextlib.nullcontext(None) ) as native: + wait_deployment_ready(args.context, args.namespace, deployment) if native: result["metadata"]["startupKnative"] = { "service": native["name"], "revision": native["revision"], @@ -1213,6 +1218,10 @@ def main(): ), } result = {"schema": 1, "metadata": metadata, "scenarios": [], "startups": []} + if args.startup_runs: + measure_startups( + args, oha, revision, lampyr_url, knative_ingress, result, output + ) with baseline_server( args.context, args.baseline_image, args.baseline_replicas, args.namespace ) as baseline, ( @@ -1245,10 +1254,6 @@ def main(): ))), } metadata["networkPaths"]["knative"] = "stock Knative ingress and queue-proxy" - if args.startup_runs: - measure_startups( - args, oha, revision, lampyr_url, knative_ingress, result, output - ) metrics_endpoints = { context: metrics_forwards.enter_context(prometheus_server(context)) for context in dict.fromkeys(target[2] for target in targets) From 49deb156a77aafdbaabfa89d82f54ea1774bfe47 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Wed, 25 Nov 2026 13:34:34 -0800 Subject: [PATCH 18/20] fixup! Measure verified scale-from-zero startup latency Signed-off-by: James Sturtevant --- scripts/tests/test_scale_test.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/scripts/tests/test_scale_test.py b/scripts/tests/test_scale_test.py index 554348a..dae0db3 100644 --- a/scripts/tests/test_scale_test.py +++ b/scripts/tests/test_scale_test.py @@ -609,6 +609,28 @@ def query_result(context, query, evaluation_time): with self.assertRaisesRegex(RuntimeError, f"counter reset.*{name}"): scale.collect_metrics("test", queries, before, 42) + def test_oha_wait_flag_only_applies_to_duration_runs(self): + result = json.dumps({ + "summary": {"requestsPerSec": 1}, + "statusCodeDistribution": {"200": 1}, + "errorDistribution": {}, + "latencyPercentilesSuccessful": {"p95": 0.1}, + }) + for single in (True, False): + with self.subTest(single=single), mock.patch.object( + scale.subprocess, "check_output", return_value=result + ) as execute: + scale.run_oha(Path("/oha"), "http://example.test/", "30s", 1, single=single) + arguments = execute.call_args.args[0] + if single: + self.assertEqual(arguments[arguments.index("-n") + 1], "1") + self.assertNotIn("-z", arguments) + self.assertNotIn("--wait-ongoing-requests-after-deadline", arguments) + else: + self.assertEqual(arguments[arguments.index("-z") + 1], "30s") + self.assertNotIn("-n", arguments) + self.assertIn("--wait-ongoing-requests-after-deadline", arguments) + def test_load_and_warmup_bound_stalled_requests_with_the_same_timeout(self): result = json.dumps({ "summary": {"requestsPerSec": 1}, From dd88317f4e6d21daf80c842e7a081c8176052882 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Wed, 25 Nov 2026 13:41:23 -0800 Subject: [PATCH 19/20] fixup! Measure verified scale-from-zero startup latency Signed-off-by: James Sturtevant --- scripts/scale-test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/scale-test.py b/scripts/scale-test.py index 5de5bf2..64e089d 100644 --- a/scripts/scale-test.py +++ b/scripts/scale-test.py @@ -644,7 +644,7 @@ def run_oha(oha, url, duration, concurrency, host=None, single=False): str(concurrency), "-t", request_timeout, - "--wait-ongoing-requests-after-deadline", + *([] if single else ["--wait-ongoing-requests-after-deadline"]), "--stats-success-breakdown", "--no-tui", "--output-format", From f7b98747046884f5b1aef653ebb4ec93ae970c8d Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Wed, 25 Nov 2026 14:26:50 -0800 Subject: [PATCH 20/20] fixup! Add opt-in scale comparison framework Signed-off-by: James Sturtevant --- docs/scale-testing.md | 181 ++++++++++++++---------------------------- 1 file changed, 59 insertions(+), 122 deletions(-) diff --git a/docs/scale-testing.md b/docs/scale-testing.md index 02774a7..26c688a 100644 --- a/docs/scale-testing.md +++ b/docs/scale-testing.md @@ -5,14 +5,28 @@ description: Compare the same Node.js application on Lampyr, Kubernetes, and Kna # Scale testing -The opt-in scale framework compares a Lampyr Service with the same Node.js -application in a Kubernetes Deployment and, optionally, stock Knative. It uses oha for client latency -and throughput, and queries the optional observability add-on for platform -metrics. The live comparison does not run in CI. +Compare the same Node.js app on Lampyr, a Kubernetes Deployment, and optionally +stock Knative. -Install the add-on and deploy `docs/examples/hello-nodejs-standalone` through -Lampyr. This Express application returns JSON with `message` and `path` fields. -Build and publish the container image from that same source: +## Before you start + +**The runner does not create clusters or install Lampyr or Knative.** You need: + +- A running [Lampyr cluster](cluster-kind.md) with the + [observability add-on](observability.md#install-the-optional-add-on). +- `docs/examples/hello-nodejs-standalone` [deployed through Lampyr](cli/deploy.md), + with a URL you can reach. Use this app without other traffic during the test. +- A Linux x86-64 machine with `just`, Docker, Python 3, `kubectl`, and `jq`. + +Your Kubernetes access must allow test workload creation and deletion, Pod +reads, `exec` in the fiberd container, and port-forwarding. + +Run the commands below from the repository root. Replace the uppercase values. + +## Run Lampyr and Kubernetes + +The Deployment runs in your Lampyr cluster. Build and push the container image +from the same Node.js source to a registry that the cluster can reach: ```bash just scale-baseline-image REGISTRY/IMAGE:TAG @@ -20,141 +34,64 @@ docker push REGISTRY/IMAGE:TAG docker buildx imagetools inspect REGISTRY/IMAGE:TAG ``` -Pass the digest-pinned image and the Lampyr URL: +Copy the digest from the inspect output. Use it with your Lampyr context, +Service name, and app URL: ```bash just scale-test \ - CONTEXT \ + LAMPYR_CONTEXT \ SERVICE \ - https://LAMPYR_URL \ + "https://LAMPYR_URL" \ REGISTRY/IMAGE@sha256:DIGEST ``` -The runner uses the Lampyr URL's path and query for both targets, during warmup -and load. For example, `"https://LAMPYR_URL/compute?iterations=1000"` also sends -`/compute?iterations=1000` to Kubernetes. Quote URLs that contain query parameters. -Use an absolute HTTP or HTTPS URL without credentials or a fragment. +Use the HTTP or HTTPS URL printed by `ly deploy`. Its path and query are sent +to every target. The runner installs its pinned load generator, oha. -## Stock Knative target +## Add stock Knative -Use a separate cluster with stock Knative Serving and working ingress. Context -aliases for the Lampyr cluster are rejected. The selected namespace must exist -in both clusters. Install the metrics collectors in the stock cluster: +Use a **separate, existing cluster** with Knative Serving and working ingress. +The `default` namespace must exist in both clusters, and both must be able to +pull the container image. Install its metrics collectors: ```bash bash scripts/install-scale-metrics.sh KNATIVE_CONTEXT ``` -This script requires `kubectl` and `jq`. It selects the metrics collectors from -the shared manifest. It does not install Lampyr, UI services, tracing services, -or Serving controllers. -Prometheus remains cluster-internal. The script omits its UI-only NetworkPolicy. - -Add the Knative context to the runner: +Then run this command instead of `just scale-test`: ```bash +just install-oha python3 scripts/scale-test.py \ --context LAMPYR_CONTEXT \ --service SERVICE \ - --lampyr-url https://LAMPYR_URL \ + --lampyr-url "https://LAMPYR_URL" \ --baseline-image REGISTRY/IMAGE@sha256:DIGEST \ --knative-context KNATIVE_CONTEXT ``` -The runner creates a temporary Knative Service with the same image digest as -the Deployment. Both use a 768 MiB application memory limit. Knative uses -`min-scale=1` and `max-scale=1`; the client controls request concurrency. -The runner removes only the Service it created. This target is for the warm, -fixed-capacity phase. The startup phase uses a separate scale-to-zero Service. - -The Knative Service URL must be reachable from the load generator. For local -ingress exposed on a different address or port, add -`--knative-ingress-url http://127.0.0.1:PORT`. Supply only the origin, without a -path or query. The runner sends the Service's routing Host header and copies -the Lampyr request path and query for both warmup and load. - -## Measurements - -The runner first measures startup three times for each target: - -- Lampyr: wait for zero Fibers, keep the same Ready home, and time one request. -- Knative: wait for zero Revision Pods and zero actual and desired scale, then - time one request through its ingress and activator. -- Deployment: wait for zero Pods, then time the scale request to one Ready Pod. - This is Pod startup, not request-triggered activation. - -The Lampyr check reads the home's fiberd audit records. It rejects missing or -invalid records, a home restart, and a request that does not create exactly one -new Fiber. A zero busy-Fiber metric alone is not proof of zero Fibers. -Use a Service with no other traffic. The context must allow `exec` in its -fiberd container to read the audit file. - -The startup Knative Service is separate from the warm target. It permits zero -replicas, has a six-second autoscaling window, and keeps at most one replica. -The runner waits for scale-to-zero without sending probe requests. Each trial -sends exactly one request, with no retry. A failed first request stops the run. -Images and snapshots stay cached; these are not image-download measurements. -The runner prepares the startup Deployment once before scaling it to zero. -Startup resources are removed before the warm targets are created, so the two -phases do not reserve application capacity at the same time. - -`--startup-runs COUNT` sets the number of trials; `0` keeps only warm traffic. -`--startup-timeout 180s` bounds each wait and first request. The JSON has a -separate `startups` array, and Markdown has a separate startup table. Startup -durations do not enter the warm latency or throughput statistics. - -The default sweep runs each target for 30 seconds at concurrency 1, 4, 16, -and 64. Lampyr's default fresh execution mode still creates a Fiber for each -request. Warm traffic does not imply live-Fiber reuse. The framework: - -- creates a temporary one-replica Deployment and Service with unique names; -- creates a stock Knative Service when a Knative context is supplied; -- warms all targets; -- runs the same client against each selected target; -- queries Prometheus for request, Fiber, CPU, and memory measurements; -- writes `build/scale-results.json` after every scenario; and -- writes a concise Markdown comparison beside it. - -The Kubernetes target uses a local Service port-forward, while the Lampyr URL -uses its configured ingress. Record that network difference when interpreting -results. The result metadata records both network paths. The framework monitors the -port-forward and stops if it exits, but the tunnel can still limit high -concurrency results. This framework is for repeatable comparisons, not a claim -that the two network paths have identical overhead. - -The runner requires one Deployment replica and a duration of at least 30 seconds. -Both targets use a 10-second request timeout, including warmup. Cleanup removes -only resources this run created. -Custom JSON output names must not use the `.md` extension. -The context must allow read access to the measured Pods. -It must also allow Pod port-forward access. The runner opens one local -Prometheus port-forward per cluster and closes it on exit. This path does not -need changes to the Lampyr add-on's Prometheus NetworkPolicy. - -Client latency, throughput, and HTTP success come from oha for all targets. -CPU and memory come from each cluster's Prometheus, which scrapes kubelet -cAdvisor. kube-state-metrics supplies Pod membership. The Knative JSON records -the application and queue-proxy separately; the report includes both. Combined -peak memory is measured at one time, not the sum of separate peaks. Shared -ingress and control-plane costs are not included. Node details are recorded -for both clusters; use matching node sizes and configurations. - -The report calculates HTTP success from response status codes and transport -errors. Its latency columns include only successful HTTP responses. Platform -error and shed counts come from Lampyr metrics. The runner waits for a final -healthy Prometheus scrape from every router after each load interval. It also -requires fresh cAdvisor samples from the measured containers and fresh -kube-state-metrics inputs. Missing or changed input series reject the scenario. -Coverage must match the running Pods from the Kubernetes API. -It can wait for up to five more scrape intervals. Counter resets reject the -scenario. The measurement window includes the pre-load router and resource -samples after warmup, and the final collection interval. Peak memory is the -maximum combined usage at one time. - -Use the Lampyr Platform Perses dashboard while a run is active. The JSON -result remains the source for comparisons across commits or machines. It -records the image digest, namespace, replica count, oha version, Git state, and -a limited node summary without node addresses or machine identifiers. - -Keep the node type, cluster configuration, workload image, Lampyr settings, -duration, and concurrency sweep unchanged when comparing revisions. +For local Knative ingress, add `--knative-ingress-url http://127.0.0.1:PORT` +if the Service URL is not reachable. Do not include a path or query. + +## Read the results + +The runner measures startup three times per target: + +| Target | Startup measurement | +|---|---| +| Lampyr | Zero Fibers to first response, with the same home running | +| Deployment | Zero Pods to one Ready Pod; not request-triggered | +| Knative | Zero replicas to first response | + +Images stay cached. The runner then tests warm traffic for 30 seconds at each +concurrency: 1, 4, 16, and 64. Lampyr's default fresh mode still creates a Fiber +per request. + +Read `build/scale-results.md` for the comparison and `build/scale-results.json` +for the full data. Client results come from oha; CPU and memory come from each +cluster's Prometheus. Knative includes its queue-proxy. Shared ingress and +control-plane costs are excluded. + +Network paths differ: Deployment uses a port-forward; Lampyr and Knative use +ingress. Keep cluster sizes and test settings the same when comparing runs. +The runner removes its temporary workloads, not your Lampyr app or clusters.