Skip to content

2026 11 26 profiling cost

kubed-io[bot] edited this page Nov 26, 2026 · 3 revisions

What profiling costs, measured and documented: plan

History. Written 2026-11-26 for Dr K. It is the plan of record for #63, built in #67 on issue-63. It changes no requirement. It adds the operator page Telemetry Guide, a script that measures what the page states, and a pointer from telemetry's Profiles section. Overtaken: the knob table went on the Telemetry Guide too, by Dr K's approval on #67, and TEL-2 and TEL-8 link to the spec's telemetry area page. Its item 8's "What a real server pays" was corrected in #73 (plan): one mcp-kb build's A/B, and no selenium-flow figure.

For agentic workers: REQUIRED SUB-SKILL: Use skill://superpowers/subagent-driven-development/SKILL.md (recommended) or skill://superpowers/executing-plans/SKILL.md to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: an operator reads, before switching profiles on, what they cost a bare QuickMCP server in CPU, and how to lower that with today's settings. Anyone can measure it again with one command.

Architecture: scripts/profile_cost.py starts a bare QuickMCP server in a child process once per configuration. It reads the child's CPU from /proc/<pid>/stat over an idle phase, then over a load phase of tool calls at a fixed rate, and prints a markdown table of medians. The numbers go on a new wiki page. The library doesn't change.

Tech Stack: Python 3.11–3.14, FastMCP 4.2 (Client over HTTP), kubed.mcp, pyroscope-io 1.4 (the telemetry extra), stdlib only otherwise, pytest, ruff.

Spec: #63's notes and Dr K's approval on #63 (2026-11-26, 16:21 UTC). There's no separate spec file: this plan is the record. The design below is that spec, settled against the code on issue-63.

The design this settles

Dr K's rulings aren't to be reopened:

  • No new setting. The library doesn't change.
  • Where the numbers go. The measured numbers, and how to lower them, go on a new operator wiki page linked from Home.md. The README gets one line pointing to it. The spec's Profiles section gets one sentence pointing to it.
  • The spec states no numbers. It holds promises, not measurements.
  • The other knobs stay out of the files. pyroscope-io's knobs are reported in the pull request only.

Where the issue left a detail open, the choice made here is marked (settled here).

  1. The page is docs/Telemetry-Guide.md, titled "Telemetry Guide" (settled here; Dr K to confirm). Dr K asked for Telemetry. A GitHub wiki puts every page in one flat namespace, whatever its directory. The spec's docs/superpowers/specs/telemetry.md is already the page telemetry, and Gollum may match page names case-insensitively. So a root Telemetry.md could hide the spec page or be hidden by it. A wiki branch isn't rendered, so this can't be tried before the merge. Every link to the page uses the full URL https://github.com/kubed-io/quick-mcp/wiki/Telemetry-Guide, as Home.md links the Specification.

  2. The script is committed, as scripts/profile_cost.py (settled here). AGENTS.md says "pyproject.toml plus scripts", and the page's numbers should be reproducible. It is linted with the rest of the checkout, and it gets a smoke test, so it can't rot unnoticed.

  3. What a run measures (settled here):

    • The child is the script's own serve subcommand: QuickMCP("profile-cost") with one tool, ping, returning "pong", served by mcp.run(). Its config comes from the environment the parent builds.
    • A run starts the child, waits until its port accepts a connection, then waits the warm-up (default 15 s, so the first push has happened).
      • Idle phase (default 60 s): no client, no calls.
      • Load phase (default 30 s): one FastMCP Client session, opened before the phase starts, calls ping at a fixed rate (default 10 a second). Call i waits until start + i / rate, so every configuration does the same work, rate × load calls. A late call goes at once.
    • CPU is the child's utime + stime over wall time, in millicores. A Pyroscope agent's threads run in the same process, so they're counted.
    • A configuration's row is the median of its runs, with the lowest and highest beside it. The runs go round the configurations in turn (run 1 of each, then run 2 of each), so drift on the node spreads across all of them.
  4. The configurations set these four variables in the child, and nothing else of TELEMETRY_*:

    Name TELEMETRY_PROFILES TELEMETRY_PROFILE_CPU TELEMETRY_PROFILE_MEMORY TELEMETRY_OTEL
    off removed true true false
    cpu the parent's true false false
    memory the parent's false true false
    both the parent's true true false
    otel removed true true true
    • The Pyroscope address is the parent's own TELEMETRY_PROFILES, the variable a server reads. The script never prints it, and neither does any file or comment.
    • The child also gets TRANSPORT=http, HOST=127.0.0.1, a free PORT the parent picked, and LOG_LEVEL=WARNING, so access logs add no noise.
    • The parent adds 127.0.0.1,localhost to its own NO_PROXY and no_proxy before anything starts, so a runner's proxy never sees the load. The child inherits that, and its push to Pyroscope is otherwise untouched.
  5. pyroscope-io's knobs, measured without a setting. --option KEY=VALUE is repeatable. Each one is passed to pyroscope.configure in the child, on top of what QuickMCP passes, through a wrapper the child installs before mcp.run(). This works because _start_profiles imports pyroscope and calls pyroscope.configure at start.

    • VALUE is read as JSON when it parses (20, false), else as a string.
    • The parent refuses (exit 2), before starting anything:
      • a key the real configure doesn't take;
      • a key QuickMCP owns: application_name, server_address, cpu_enabled, mem_enabled, tags. upload_interval is allowed, since overriding it is the point;
      • any option given when pyroscope-io isn't installed.
    • The options reach the child as JSON in PROFILE_COST_OPTIONS, for profile configurations only. A row's name carries its options: both sample_rate=20.
  6. Exit codes:

    • 0: the table was printed.
    • 2: usage. That's argparse, a profile configuration without TELEMETRY_PROFILES, or a refused option.
    • 1: a child that exited, or that didn't accept a connection within 60 s. The script names the file holding the child's stderr (a temporary directory the script keeps).

    The child is always stopped in a finally: SIGTERM, a wait of up to 15 s so pyroscope can flush, then SIGKILL. No server is left pushing.

  7. The knob runs are always measured (settled here). The issue made them conditional on the existing settings not cutting the cost. Measuring them is cheap and adds no setting, and it spares the code agent judging "meaningfully". Three runs of both, each with one option:

    • sample_rate=20;
    • upload_interval=60;
    • mem_heap_sample_size=4194304.

    Their table goes in the code agent's reply on #67, with the both row from the same session as the baseline. It never goes in a file.

  8. The page (docs/Telemetry-Guide.md), for operators. It holds, in this order:

    • one opening sentence: what each signal costs a bare server, and how to lower it with today's settings;
    • What it costs: the table from the main run, with the otel row. Under it goes one line on the setup: the kubed-mcp version (pip show kubed-mcp), the Python and pyroscope-io versions, the phase lengths and the rate, and "on a Kubernetes node, pushing to Pyroscope in the same cluster". It says what the otel row exported to (item 9);
    • What a real server pays: one sentence with the live figures from #63, marked as observed in production, not measured by the script. mcp-kb went from 7–10m to 27–28m with profiles on, and selenium-flow from about 55m to about 80m;
    • Lowering it: the cheaper single switch, whichever the table shows, written as the config key and its env var (profile_memory: false / TELEMETRY_PROFILE_MEMORY=false, or the CPU pair). It says what that switch gives up: allocation profiles, or CPU flame graphs. Then the two further steps: profiles off (leave profiles unset) and OpenTelemetry alone. If neither single switch saves much, the page says so plainly;
    • Measuring it again: the command. It says the script is Linux only (/proc) and pushes to the Pyroscope it's given, under the service name profile-cost;
    • links to TEL-2 and TEL-8 through the Specification URL.

    It names no pyroscope-io knob, no address, and no cluster or host name.

  9. The otel row runs with the OTEL_* the code agent's environment gives it:

    • with an OTLP collector in the cluster, the code agent sets OTEL_EXPORTER_OTLP_ENDPOINT to it for the command only;
    • without one, it sets OTEL_TRACES_EXPORTER=none and OTEL_METRICS_EXPORTER=none.

    The page says which, without the address.

Global Constraints

  • Nothing under kubed/ changes, and no setting is added. No requirement is added, reworded or numbered: the spec gains one unnumbered sentence after TEL-8, with no numbers in it.
  • This repository is public. No cluster hostname, service address, credential or personal name in a file, a commit message, the page or the pull request. The Pyroscope address lives only in the environment of the commands that run the script.
  • scripts/profile_cost.py has from __future__ import annotations. It imports only the stdlib, fastmcp.Client, kubed.mcp, and pyroscope (inside the functions that check options). It runs nothing at import.
  • Tests:
    • no network beyond localhost;
    • a test that runs the script starts it as a subprocess with an explicit env, so nothing is left behind;
    • the tests skip when /proc/self/stat doesn't exist.
  • Checks, as CI runs them (lint.yml, and test.yml after pip install -e .[test,tasks]): ruff check ., ruff format --check . and pytest.
  • The changelog gets no line: this is docs and a script. The pull request takes the no changelog label and no release:* label, so its merge releases nothing.
  • The wiki. Edits are left in the docs/ checkout. The job commits them on the wiki branch issue-63, cut from the commit this branch pins (5c4ea8a), and moves the pointer here. Nothing is committed inside docs/ by hand, and the wiki's master is never pushed.
  • .github/ isn't touched.

Review Focus

  1. A runner with proxy variables set. The load goes to 127.0.0.1 and must never reach a proxy (Task 1, test_a_proxy_in_the_environment_never_sees_the_load).
  2. A child that dies at boot, from an inherited variable the config refuses. The script must exit 1 quickly, naming the child's log, and not wait out the 60 s (Task 1, test_a_server_that_fails_at_boot_ends_the_run).
  3. A Pyroscope address with credentials. Nothing the script prints may carry it, even when the push fails (Task 1, test_the_address_never_shows).
  4. An option value's type. sample_rate=20 must reach configure as the int 20, and gil_only=false as False, never as strings (Task 1, test_options_are_read_as_json_first).
  5. A load phase whose calls run late. Each configuration must still make exactly rate × load calls (Task 1, test_profiles_off_prints_one_row, the calls column).

Task 1: The measurement script

Files:

  • Create: scripts/profile_cost.py
  • Test: tests/test_profile_cost.py

Interfaces:

  • Produces, in scripts/profile_cost.py:

    • CONFIGS: dict[str, dict[str, str | None]]: item 4's table, where None removes the variable;
    • OWNED: frozenset[str]: item 5's five keys;
    • cpu_seconds(pid: int) -> float: utime + stime from /proc/<pid>/stat, read after the last ), since the command name may hold spaces, then divided by os.sysconf("SC_CLK_TCK");
    • parse_option(text: str) -> tuple[str, object]: raises ValueError without an =;
    • child_env(config: str, base: Mapping[str, str], port: int, options: Mapping[str, object]) -> dict[str, str];
    • @dataclass(frozen=True) class Sample with idle: float, load: float (millicores) and calls: int;
    • measure_once(config: str, options: Mapping[str, object], *, warmup: float, idle: float, load: float, rate: float) -> Sample;
    • table(results: Mapping[str, Sequence[Sample]]) -> str;
    • serve() -> None (the child);
    • main(argv: Sequence[str] | None = None) -> int.
  • The command line: python scripts/profile_cost.py measure [--configs off,cpu,memory,both] [--runs 3] [--warmup 15] [--idle 60] [--load 30] [--rate 10] [--option KEY=VALUE ...], and python scripts/profile_cost.py serve.

  • The table, exact columns: | config | idle (millicores) | load (millicores) | calls per run | runs |. A row reads | cpu | 7 (6–8) | 25 (24–27) | 300 | 3 |: medians rounded to whole millicores, then the lowest and highest, with an en dash.

  • Step 1: Write the failing tests

The module is loaded with importlib.util.spec_from_file_location("profile_cost", ROOT / "scripts/profile_cost.py"). run(*args, env) runs [sys.executable, "scripts/profile_cost.py", *args] from the repository root, with capture_output=True, text=True, timeout=120. Its env is os.environ minus every TELEMETRY_* and OTEL_* variable, plus what the test gives. FAST = ("--warmup", "0", "--idle", "1", "--load", "1", "--runs", "1").

pytestmark = pytest.mark.skipif(not Path("/proc/self/stat").exists(), reason="Linux /proc only")


def test_cpu_seconds_counts_this_process() -> None:
    before = profile_cost.cpu_seconds(os.getpid())
    deadline = time.process_time() + 0.2
    while time.process_time() < deadline:
        pass
    assert profile_cost.cpu_seconds(os.getpid()) - before >= 0.1


def test_options_are_read_as_json_first() -> None:
    assert profile_cost.parse_option("sample_rate=20") == ("sample_rate", 20)
    assert profile_cost.parse_option("gil_only=false") == ("gil_only", False)
    assert profile_cost.parse_option("tenant_id=team-a") == ("tenant_id", "team-a")
    with pytest.raises(ValueError):
        profile_cost.parse_option("sample_rate")


def test_each_config_sets_its_four_variables() -> None:
    base = {"TELEMETRY_PROFILES": "http://127.0.0.1:1", "TELEMETRY_TAGS": '{"a": "b"}'}
    off = profile_cost.child_env("off", base, 8123, {})
    assert "TELEMETRY_PROFILES" not in off and off["TELEMETRY_OTEL"] == "false"
    memory = profile_cost.child_env("memory", base, 8123, {"sample_rate": 20})
    assert (memory["TELEMETRY_PROFILE_CPU"], memory["TELEMETRY_PROFILE_MEMORY"]) == ("false", "true")
    assert json.loads(memory["PROFILE_COST_OPTIONS"]) == {"sample_rate": 20}
    assert (memory["TRANSPORT"], memory["HOST"], memory["PORT"], memory["LOG_LEVEL"]) == ("http", "127.0.0.1", "8123", "WARNING")
    assert "PROFILE_COST_OPTIONS" not in profile_cost.child_env("off", base, 8123, {"sample_rate": 20})
    assert memory["TELEMETRY_TAGS"] == '{"a": "b"}'


def test_profiles_off_prints_one_row() -> None:
    out = run("measure", "--configs", "off", *FAST, env={})
    assert out.returncode == 0, out.stderr
    assert re.search(r"^\| off \| \d+ \(\d+–\d+\) \| \d+ \(\d+–\d+\) \| 10 \| 1 \|$", out.stdout, re.M)


def test_a_proxy_in_the_environment_never_sees_the_load() -> None:
    dead = "http://127.0.0.1:9"
    out = run("measure", "--configs", "off", *FAST, env={"HTTP_PROXY": dead, "http_proxy": dead, "ALL_PROXY": dead})
    assert out.returncode == 0, out.stderr


def test_a_profile_config_without_an_address_is_refused() -> None:
    out = run("measure", "--configs", "cpu", *FAST, env={})
    assert out.returncode == 2 and "TELEMETRY_PROFILES" in out.stderr


@pytest.mark.parametrize("option", ["no_such_knob=1", "server_address=x", "tags={}"])
def test_an_option_configure_does_not_take_or_quickmcp_owns_is_refused(option) -> None:
    out = run("measure", "--configs", "cpu", "--option", option, *FAST, env={"TELEMETRY_PROFILES": "http://127.0.0.1:1"})
    assert out.returncode == 2 and option.split("=")[0] in out.stderr


def test_a_server_that_fails_at_boot_ends_the_run() -> None:
    started = time.monotonic()
    out = run("measure", "--configs", "off", *FAST, env={"TELEMETRY_TAGS": "{"})
    assert out.returncode == 1 and time.monotonic() - started < 30
    (log,) = re.findall(r"(/\S+\.log)", out.stderr)
    assert Path(log).is_file()


def test_the_address_never_shows() -> None:
    secret = "http://us3r:s3cret@127.0.0.1:9/p4th?t0ken=x"
    out = run("measure", "--configs", "cpu", "--option", "sample_rate=20", *FAST, env={"TELEMETRY_PROFILES": secret})
    assert out.returncode == 0, out.stderr
    for part in ("us3r", "s3cret", "p4th", "t0ken"):
        assert part not in out.stdout + out.stderr
    assert re.search(r"^\| cpu sample_rate=20 \|", out.stdout, re.M)

TELEMETRY_TAGS={ is a value the config refuses at boot, which the script doesn't set. If Step 2 shows the config accepts it, use another inherited value the boot refuses, and say which in the pull request.

test_the_address_never_shows runs the real pyroscope-io from the test extra. Its push to 127.0.0.1:9 fails locally, which is the point: the failure must not print the address.

  • Step 2: Run the tests to verify they fail

Run: pytest tests/test_profile_cost.py -v Expected: collection fails, because scripts/profile_cost.py doesn't exist.

  • Step 3: Implement scripts/profile_cost.py by design items 3 to 6

  • The module docstring says three things: what the script measures, that it's Linux only, and that the Pyroscope address comes from TELEMETRY_PROFILES and is never printed.

  • The child's wrapper: serve() reads PROFILE_COST_OPTIONS. When it's there, it replaces pyroscope.configure with a function that calls the real one with {**kwargs, **options}.

  • The load phase runs in asyncio.run inside measure_once.

  • The free port comes from binding ("127.0.0.1", 0) and closing the socket.

  • The child's stderr goes to <tempdir>/<config>-<run>.log.

  • Step 4: Run the tests to verify they pass

Run: pytest tests/test_profile_cost.py -v Expected: PASS, in well under a minute.

  • Step 5: Checks and commit

Run: ruff check . && ruff format --check . && pytest Expected: all pass.

git add scripts/profile_cost.py tests/test_profile_cost.py
git commit -m "chore(scripts): profile_cost.py measures what profiling costs a bare server"

Task 2: Measure, and write the page, the links and the pointer

Files:

  • Create: docs/Telemetry-Guide.md (the wiki).
  • Modify: docs/Home.md: one row in "Where to go".
  • Modify: docs/superpowers/specs/telemetry.md: one sentence after TEL-8.
  • Modify: README.md: one line.

Interfaces:

  • Consumes: Task 1's command line and table.

  • Step 1: Find the in-cluster Pyroscope and collector

Use the cluster tools: service/pyroscope for the address, and an OTLP collector service, if there is one, for item 9. Write neither down anywhere. Each goes into the environment of one command only.

  • Step 2: The main run

Run: TELEMETRY_PROFILES=<address> python scripts/profile_cost.py measure --configs off,cpu,memory,both --runs 3 Expected: exit 0, and a table of four rows, each with calls per run 300. It takes about 20 minutes. Run it in the background and wait on it.

  • Step 3: The OpenTelemetry reference

Run: python scripts/profile_cost.py measure --configs off,otel --runs 3, with item 9's variables. Expected: exit 0, two rows.

  • Step 4: The knob runs (item 7)

Run, one after another, each with TELEMETRY_PROFILES=<address>: python scripts/profile_cost.py measure --configs both --runs 3 --option sample_rate=20, then the same with --option upload_interval=60, then with --option mem_heap_sample_size=4194304. Expected: exit 0, one row each. Keep the tables in .issue/scratch/, which is never committed, for the reply.

  • Step 5: Write docs/Telemetry-Guide.md by design item 8

The table is the main run's, as printed, plus the otel row from Step 3. Write the guidance from the numbers, not from expectation: whichever of cpu and memory is cheaper decides the switch the page recommends.

  • Step 6: The links

  • docs/Home.md: a row after "Know what the package promises": | Know what telemetry costs, and lower it | [the Telemetry Guide](https://github.com/kubed-io/quick-mcp/wiki/Telemetry-Guide) |

  • docs/superpowers/specs/telemetry.md: a paragraph right after TEL-8, unnumbered: What profiling costs a server, measured, and how to lower it with these settings, is on the [Telemetry Guide](https://github.com/kubed-io/quick-mcp/wiki/Telemetry-Guide).

  • README.md: one line after the install code block, before the ---: Profiles cost CPU: the [Telemetry Guide](https://github.com/kubed-io/quick-mcp/wiki/Telemetry-Guide) says how much, and how to lower it.

  • Step 7: Check that no address got out

Search the changed files and docs/Telemetry-Guide.md for the address's host, for svc, and for cluster.local. Run: git diff --stat and git -C docs status --short. Check that each lists only this task's files and Task 1's. Expected: no match, and no file beyond these.

  • Step 8: Checks and commit

Run: ruff check . && ruff format --check . && pytest Expected: all pass. The wiki edits are left for the job to commit, as Global Constraints says.

git add README.md
git commit -m "docs: the README points to what telemetry costs"
  • Step 9: The report on #67

The code agent's reply on the pull request, never a file, carries:

  • the main run's table;
  • the knob runs' table, beside the both row;
  • one line per knob saying what it trades away: fewer CPU samples, later profiles, or coarser allocation profiles;
  • which knob, if any, cuts the cost that no existing setting cuts.

It proposes no setting: that's Dr K's separate decision.

Clone this wiki locally