Skip to content

2026 11 28 pyroscope source links

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

Profiles link to their source: the build's labels and python -m kubed.mcp.pyroscope: plan

History. Written 2026-11-28 for Dr K. It is the plan of record for #100, built in #101 on issue-100, which merges into main as a minor release. It adds telemetry TEL-25, TEL-26 and TEL-27, (proposed) until the task that builds each row drops the tag, and a section to the Telemetry Guide. It replaces the draft rows in #100's notes. Their TEL-9a is TEL-25 here, because ids count up and never take a letter. Their TEL-24 and TEL-25 are TEL-26 and TEL-27. The rows were first numbered TEL-24 to TEL-26, and moved up one when main took TEL-24 for the build span.

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: a flame graph's frame opens at its source line on GitHub. The server's own frames open at the commit its image was built from. kubed-mcp's, FastMCP's and the standard library's frames open at the versions the image installed.

Architecture: _profile_tags reads two more variables. A new module, kubed/mcp/pyroscope.py, reads the installed distributions through importlib.metadata and builds a list of _Mappings. It renders them as YAML and compares a committed file with them. Three seams (_distribution, _stdlib, _python) let the tests build an image's environment from fake distributions, with no network and no image.

Tech Stack: Python 3.11–3.14, importlib.metadata, sysconfig, platform, argparse, difflib, PyYAML 6 (already a runtime dependency), pytest, ruff.

Spec: telemetry TEL-25 to TEL-27, written this round from #100's notes and Dr K's rulings on the issue (2026-11-28, 01:02, 01:11 and 01:18 UTC; spec approved). The rows are the requirement. This plan is the record of how they're built.

The design this settles

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

  • the labels come from SERVICE_REPOSITORY and SERVICE_GIT_REF, on profiles only;
  • the command runs inside the built image, with --write and --check, as python -m kubed.mcp.pyroscope;
  • the ref rules: an rc is vX.Y.Z-rc.N, a dev build is its commit, and FastMCP's monorepo path is known to the command;
  • traces' vcs.* attributes are a follow-up;
  • it ships as one minor release.

The spec agent's calls, confirmed here: --check reads stdin, the server's distribution is an argument, only three distributions and the standard library are mapped, and there is no service_root_path. The command does exactly what TEL-26 and TEL-27 say. What they leave to the code is below, and each choice made here is marked (settled here).

  1. FastMCP is read from fastmcp-slim, not fastmcp (settled here, found in this round).

    • Since FastMCP 4, fastmcp is a meta-distribution: fastmcp 4.2.6 requires fastmcp-slim[client,server]==4.2.6 and installs no code.
    • fastmcp-slim installs fastmcp/. Its Project-URL Repository is https://github.com/PrefectHQ/fastmcp, which is PyPI's record for 4.2.6.
    • FastMCP's repository at v4.2.6 holds fastmcp_slim/fastmcp/, fastmcp_tasks/fastmcp_tasks/ and fastmcp_events/. So fastmcp-tasks installs a top-level package of its own and doesn't write into fastmcp/.
    • The monorepo folder is a table in the module, _MONOREPO = {"fastmcp-slim": "fastmcp_slim"}. The GitHub path is that folder, /, and the package's import path.
  2. A short commit works as a ref (verified 2026-11-28). GitHub's contents API answered GET /repos/kubed-io/quick-mcp/contents/pyproject.toml?ref=311c152 with the file, the same as for the full 311c15298c0c…. So a dev build without direct_url.json's commit maps to its g<sha>, and no fallback is needed. The full commit is used when pip recorded one (PEP 610: vcs_info.commit_id, written by pip install git+…).

  3. The exit codes (settled here):

    • 0: written, or up to date;
    • 1: --check found the committed file stale;
    • 2: the command couldn't build the image's mapping, couldn't read the committed file, or got bad arguments. argparse's own errors exit 2 too.
  4. A missing distribution (settled here). The named distribution is an error: a typo must not write a file that leaves the server's own frames unmapped, which was Dr K's first finding on mcp-kb. A missing fastmcp-slim, or a GitHub-mapped distribution whose files hold no package (an editable install), is left out with a line on stderr, as call 7 had it.

  5. --check compares meaning, not bytes (settled here). Both sides go through _normalised(document): {"version": …, "mappings": {prefix: (language, source as sorted JSON)}}, with one entry per prefix. So order, grouping and comments don't matter, and a hand-written file like mcp-kb's passes when it maps the same things. A document of any other shape normalises to None and is stale. The diff shown is the text's, from the committed file to the image's, so a reader sees what to commit.

  6. Exact copy (settled here). Every stderr line starts kubed.mcp.pyroscope: . {Name} is the distribution's metadata Name, and {name} is the argument as given.

    When stream line
    header, line 1 stdout # Generated by `python -m kubed.mcp.pyroscope --write {Name}` inside the server's image.
    header, line 2 stdout # Regenerate it there rather than edit it: CI checks it with --check.
    named distribution missing stderr {name} is not installed
    named distribution, no package stderr {Name}'s files hold no package
    no GitHub Project-URL stderr {Name}'s Project-URL names no GitHub repository
    kubed-mcp without a ref stderr kubed-mcp {version} has no tag or commit to map to
    fastmcp-slim missing stderr fastmcp-slim is not installed: its frames stay unmapped
    GitHub-mapped, no package stderr {Name}'s files hold no package, as in an editable install: its frames stay unmapped
    stale stderr .pyroscope.yaml is stale: regenerate it with --write {Name} in this image
    empty input stderr read nothing: pass the file's path, or run docker with -i so stdin reaches the command
    <file> unreadable stderr {file} can't be read: {type(error).__name__}
    diff headers stdout --- .pyroscope.yaml (committed) and +++ .pyroscope.yaml (this image)
  7. The rendered document. The header comes first, then yaml.safe_dump(document, sort_keys=False, default_flow_style=False).

    • The document is {"version": "v1", "source_code": {"mappings": [...]}}.
    • Each mapping is {"path": [{"prefix": d}, {"prefix": d[1:]}], "language": "python", "source": …}, in that key order. d is the installed directory, ending in /.
    • A source is {"local": {"path": "kubed/mcp_kb"}}, or {"github": {"owner": …, "repo": …, "ref": …, "path": …}} in that key order.
  8. The module never imports the top-level pyroscope. telemetry.py's import pyroscope is absolute, so the new module doesn't shadow it. The new module imports only the standard library and yaml, and no FastMCP: tests/test_facade.py's import check gains it.

Global Constraints

  • from __future__ import annotations at the top of every module. kubed/ gets no __init__.py.
  • No public name changes, and no [project.scripts] entry. The command's contract is its arguments, output and exit codes (TEL-26). Every name in kubed/mcp/pyroscope.py but main is private.
  • kubed/mcp/pyroscope.py imports only the standard library and yaml, with no relative import, and doesn't need the telemetry extra.
  • _otel._resource_attributes isn't touched. The two new labels are for profiles only (TEL-25).
  • Tests:
    • no network;
    • the module's tests build distributions as importlib.metadata.Distribution fakes, never by installing anything;
    • only the entry-point test runs a subprocess, against the test environment's own distributions.
  • Checks, as CI runs them: lint.yml runs ruff check ., and test.yml runs pytest after pip install .[test,tasks]. This repository's plans also run ruff format --check .. Locally, run pip install -e .[test,tasks], then ruff check . && ruff format --check . && pytest.
  • The wiki. Edits are left in the docs/ checkout. The job commits them on the wiki branch issue-100 and moves the pointer here. No git runs inside docs/, and the wiki's master is never pushed. Spec text is in the present tense, with no issue numbers. Examples use example.com and github.com/example/server.
  • .github/ isn't touched. The pull request takes release:minor.

Review Focus

  1. docker run without -i. stdin is empty, so a --check that compared would call every mapping stale. It must exit 2 and say why (Task 3, test_empty_input_says_how_to_pass_it).
  2. An image without a venv, where site-packages sits inside the standard library's directory (/usr/local/lib/python3.14/site-packages/). Both prefixes must be listed, the stdlib's one shorter, so the longest prefix still wins (Task 2, test_an_image_without_a_venv_keeps_every_prefix).
  3. A committed file written by hand, like mcp-kb's: another order, one mapping per prefix, comments. --check must pass when the mappings are the same (Task 3, test_it_reproduces_mcp_kbs_committed_file, test_check_ignores_order_grouping_and_comments).
  4. The distribution's name spelled another way, kubed_mcp_kb or Kubed-MCP-KB. It must write the same bytes, with the header naming kubed-mcp-kb (Task 3, test_the_name_is_read_as_pip_reads_it).
  5. kubed-mcp installed from git or editable in the image. A git install maps to the full commit, and an editable one is left out with a line, never an error (Task 2, test_a_git_install_maps_to_its_full_commit, test_what_it_leaves_out).

Task 1: TEL-25, the build's labels on profiles

Files:

  • Modify: kubed/mcp/telemetry.py: _profile_tags, and its docstring.
  • Modify: tests/test_telemetry.py: the _clean fixture and _child's exclusion list gain SERVICE_REPOSITORY and SERVICE_GIT_REF. New tests go beside test_profiles_carry_the_pod_and_tags_win.
  • Modify: docs/superpowers/specs/telemetry.md: drop (proposed) from TEL-25.

Interfaces:

  • Consumes: _profile_tags(tags: Mapping[str, str]) -> dict[str, str], the pyroscope and served test helpers.

  • Produces: _profile_tags with the same signature. Labels in this order: namespace, pod, service_repository, service_git_ref, then tags, which win.

  • Step 1: Write the failing tests

REPOSITORY = "https://github.com/example/server"
COMMIT = "311c15298c0c036bce9e99d306c166689c4525a9"


async def test_profiles_carry_the_build(pyroscope, monkeypatch) -> None:
    monkeypatch.setenv("SERVICE_REPOSITORY", REPOSITORY)
    monkeypatch.setenv("SERVICE_GIT_REF", COMMIT)
    async with Client(served("built", TelemetrySettings(profiles=ADDRESS)).server):
        pass
    assert pyroscope[0]["tags"] == {"service_repository": REPOSITORY, "service_git_ref": COMMIT}


async def test_an_empty_build_variable_adds_no_label(pyroscope, monkeypatch) -> None:
    monkeypatch.setenv("SERVICE_REPOSITORY", "")
    monkeypatch.setenv("SERVICE_GIT_REF", COMMIT)
    async with Client(served("half-built", TelemetrySettings(profiles=ADDRESS)).server):
        pass
    assert pyroscope[0]["tags"] == {"service_git_ref": COMMIT}


async def test_tags_override_the_build(pyroscope, monkeypatch) -> None:
    monkeypatch.setenv("SERVICE_REPOSITORY", REPOSITORY)
    monkeypatch.setenv("SERVICE_GIT_REF", COMMIT)
    settings = TelemetrySettings(profiles=ADDRESS, tags={"service_git_ref": "pinned"})
    async with Client(served("overridden", settings).server):
        pass
    assert pyroscope[0]["tags"] == {"service_repository": REPOSITORY, "service_git_ref": "pinned"}


async def test_no_build_variables_add_no_labels(pyroscope) -> None:
    async with Client(served("unbuilt", TelemetrySettings(profiles=ADDRESS)).server):
        pass
    assert pyroscope[0]["tags"] == {}


def test_the_build_is_not_on_traces(monkeypatch) -> None:
    from kubed.mcp._otel import _resource_attributes

    monkeypatch.setenv("SERVICE_REPOSITORY", REPOSITORY)
    monkeypatch.setenv("SERVICE_GIT_REF", COMMIT)
    assert _resource_attributes("", {}) == ""
  • Step 2: Run them to verify they fail

Run: pytest tests/test_telemetry.py -v -k "build" Expected: the first three fail on the missing labels. test_no_build_variables_add_no_labels and test_the_build_is_not_on_traces pass already.

  • Step 3: Add ("service_repository", "SERVICE_REPOSITORY") and ("service_git_ref", "SERVICE_GIT_REF") to _profile_tags' loop, after pod

The docstring says: the pod's labels from POD_NAMESPACE and POD_NAME, then the build's from SERVICE_REPOSITORY and SERVICE_GIT_REF, then tags, which win.

  • Step 4: Run the tests to verify they pass

Run: pytest tests/test_telemetry.py -v Expected: PASS, test_profiles_carry_the_pod_and_tags_win and test_an_empty_pod_variable_adds_no_label unchanged.

  • Step 5: Drop (proposed) from TEL-25, run the checks, commit

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

git add kubed/mcp/telemetry.py tests/test_telemetry.py
git commit -m "feat(telemetry): profiles carry service_repository and service_git_ref from the build"

Task 2: TEL-26 and TEL-27, the image's mappings

Files:

  • Create: kubed/mcp/pyroscope.py: the module docstring, _MONOREPO, _Mapping, _Unmappable, _ref, _commit, _github, _packages, the seams, _mappings and _render.
  • Create: tests/test_source_links.py: the Fake distribution, the image fixture, and this task's tests. Not test_pyroscope.py: the suite's pyroscope fixture fakes the top-level module, and the name would read as its test.
  • Modify: tests/test_facade.py: the import check's parameters gain ("kubed.mcp.pyroscope", {"yaml"}, set()).

Interfaces:

  • Consumes: nothing from Task 1.

  • Produces, all in kubed/mcp/pyroscope.py:

    • _MONOREPO: dict[str, str] = {"fastmcp-slim": "fastmcp_slim"}, keyed by normalised name;
    • @dataclass(frozen=True) class _Mapping: directory: str; source: dict[str, dict[str, str]]. directory is absolute and ends in /;
    • class _Unmappable(Exception), whose message is the stderr line without its prefix (design item 6);
    • _normalise(name: str) -> str: PEP 503, lowercase with each run of -, _ and . as -;
    • _ref(version: str, commit: str | None) -> str | None: kubed-mcp's rule (TEL-27). None means no ref;
    • _commit(dist: Distribution) -> str | None: direct_url.json's vcs_info.commit_id, or None when the file, vcs_info or the key is missing, or the file isn't JSON;
    • _github(dist: Distribution) -> tuple[str, str]: owner and repository. It raises _Unmappable;
    • _packages(dist: Distribution) -> list[tuple[str, str]]: (import path, directory), sorted by import path, such as ("kubed/mcp_kb", "/opt/venv/lib/python3.14/site-packages/kubed/mcp_kb/");
    • the seams: _distribution(name: str) -> Distribution | None (importlib.metadata.distribution, None on PackageNotFoundError), _stdlib() -> str (sysconfig.get_paths()["stdlib"]) and _python() -> str (platform.python_version());
    • _mappings(name: str, warn: Callable[[str], None]) -> tuple[str, list[_Mapping]]: the distribution's metadata Name and its mappings in TEL-26's order. It raises _Unmappable;
    • _render(name: str, mappings: Sequence[_Mapping]) -> str: the header for name, then the document (design item 7).
  • Step 1: Write the failing tests

The fake, and the environment mcp-kb's image has:

SITE = PurePosixPath("/opt/venv/lib/python3.14/site-packages")
FULL = "311c15298c0c036bce9e99d306c166689c4525a9"


class Fake(importlib.metadata.Distribution):
    """A distribution read from strings, installed under ``site``."""

    def __init__(self, name, version, files=(), urls=(), direct_url=None, site=SITE): ...
    # read_text("METADATA"): Metadata-Version 2.1, Name, Version, one Project-URL line per url.
    # read_text("RECORD"): one "path,," line per file. read_text("direct_url.json"):
    # json.dumps(direct_url) when given. Anything else: None.
    # locate_file(path): site / path.


def kb(**kw): return Fake("kubed-mcp-kb", "1.4.0", ["kubed/mcp_kb/__init__.py", "kubed/mcp_kb/app.py",
                          "kubed/mcp_kb/tools/__init__.py"], ["Repository, https://github.com/kubed-io/mcp-kb"], **kw)
def mcp(version="0.6.1", **kw): return Fake("kubed-mcp", version, ["kubed/mcp/__init__.py", "kubed/mcp/telemetry.py"],
                          ["Homepage, https://github.com/kubed-io", "Repository, https://github.com/kubed-io/quick-mcp"], **kw)
def slim(**kw): return Fake("fastmcp-slim", "4.2.6", ["fastmcp/__init__.py", "fastmcp/server/__init__.py"],
                          ["Repository, https://github.com/PrefectHQ/fastmcp"], **kw)


@pytest.fixture
def image(monkeypatch):
    """Install fakes as the image's distributions: image(*fakes, stdlib=..., python=...)."""
    def install(*fakes, stdlib="/usr/local/lib/python3.14", python="3.14.10"):
        found = {_normalise(f.metadata["Name"]): f for f in fakes}
        monkeypatch.setattr(source_map, "_distribution", lambda name: found.get(_normalise(name)))
        monkeypatch.setattr(source_map, "_stdlib", lambda: stdlib)
        monkeypatch.setattr(source_map, "_python", lambda: python)
    return install

source_map is import kubed.mcp.pyroscope as source_map. The tests:

@pytest.mark.parametrize(("version", "commit", "ref"), [
    ("0.6.1", None, "v0.6.1"),
    ("0.8.0rc2", None, "v0.8.0-rc.2"),
    ("0.7.1.dev3+g311c152", None, "311c152"),
    ("0.7.1.dev3+g311c152.d20261128", None, "311c152"),
    ("0.8.0rc2.dev1+g311c152", None, "311c152"),
    ("0.7.1.dev3+g311c152", FULL, FULL),
    ("0.6.1", FULL, "v0.6.1"),
    ("0.7.1.dev3", None, None),
    ("0.7.0.post1", None, None),
])
def test_kubed_mcps_version_maps_to_its_ref(version, commit, ref) -> None:
    assert _ref(version, commit) == ref


def test_a_git_install_maps_to_its_full_commit(image) -> None:
    git = {"url": "https://github.com/kubed-io/quick-mcp", "vcs_info": {"vcs": "git", "commit_id": FULL}}
    editable = {"url": "file:///src/quick-mcp", "dir_info": {"editable": True}}
    assert _commit(mcp("0.7.1.dev3+g311c152", direct_url=git)) == FULL
    assert _commit(mcp(direct_url=editable)) is None and _commit(mcp()) is None
    image(kb(), mcp("0.7.1.dev3+g311c152", direct_url=git), slim())
    _, mappings = _mappings("kubed-mcp-kb", print)
    assert mappings[1].source["github"]["ref"] == FULL


@pytest.mark.parametrize(("urls", "repository"), [
    (["Repository, https://github.com/PrefectHQ/fastmcp"], ("PrefectHQ", "fastmcp")),
    (["Homepage, https://github.com/kubed-io", "Repository, https://github.com/kubed-io/quick-mcp"], ("kubed-io", "quick-mcp")),
    (["Source Code, https://github.com/example/server.git"], ("example", "server")),
    (["source, https://github.com/example/server/"], ("example", "server")),
])
def test_the_repository_comes_from_project_url(urls, repository) -> None:
    assert _github(Fake("x", "1.0", urls=urls)) == repository


@pytest.mark.parametrize("urls", [[], ["Homepage, https://gofastmcp.com"], ["Repository, https://gitlab.com/example/server"],
                                  ["Repository, https://github.com/example"]])
def test_no_github_repository_is_unmappable(urls) -> None:
    with pytest.raises(_Unmappable, match=r"^x's Project-URL names no GitHub repository$"):
        _github(Fake("x", "1.0", urls=urls))


def test_a_namespace_package_is_its_subpackage() -> None:
    assert _packages(kb()) == [("kubed/mcp_kb", f"{SITE}/kubed/mcp_kb/")]


def test_the_mappings_of_mcp_kbs_image(image) -> None:
    image(kb(), mcp(), slim())
    assert _mappings("kubed-mcp-kb", print) == ("kubed-mcp-kb", [
        _Mapping(f"{SITE}/kubed/mcp_kb/", {"local": {"path": "kubed/mcp_kb"}}),
        _Mapping(f"{SITE}/kubed/mcp/", {"github": {"owner": "kubed-io", "repo": "quick-mcp", "ref": "v0.6.1", "path": "kubed/mcp"}}),
        _Mapping(f"{SITE}/fastmcp/", {"github": {"owner": "PrefectHQ", "repo": "fastmcp", "ref": "v4.2.6", "path": "fastmcp_slim/fastmcp"}}),
        _Mapping("/usr/local/lib/python3.14/", {"github": {"owner": "python", "repo": "cpython", "ref": "v3.14.10", "path": "Lib"}}),
    ])


def test_each_prefix_is_listed_with_and_without_its_slash(image) -> None:
    image(kb(), mcp(), slim())
    document = yaml.safe_load(_render(*_mappings("kubed-mcp-kb", print)))
    assert document["version"] == "v1"
    first = document["source_code"]["mappings"][0]
    assert first == {"path": [{"prefix": f"{SITE}/kubed/mcp_kb/"}, {"prefix": f"{str(SITE)[1:]}/kubed/mcp_kb/"}],
                     "language": "python", "source": {"local": {"path": "kubed/mcp_kb"}}}


def test_the_same_image_writes_the_same_bytes(image) -> None:
    image(kb(), mcp(), slim())
    text = _render(*_mappings("kubed-mcp-kb", print))
    assert text == _render(*_mappings("kubed-mcp-kb", print))
    assert text.splitlines()[:2] == [
        "# Generated by `python -m kubed.mcp.pyroscope --write kubed-mcp-kb` inside the server's image.",
        "# Regenerate it there rather than edit it: CI checks it with --check.",
    ]


def test_an_image_without_a_venv_keeps_every_prefix(image) -> None:
    system = PurePosixPath("/usr/local/lib/python3.14/site-packages")
    image(kb(site=system), mcp(site=system), slim(site=system))
    _, mappings = _mappings("kubed-mcp-kb", print)
    assert [m.directory for m in mappings] == [f"{system}/kubed/mcp_kb/", f"{system}/kubed/mcp/",
                                              f"{system}/fastmcp/", "/usr/local/lib/python3.14/"]


def test_a_distribution_is_mapped_once(image) -> None:
    image(mcp(), slim())
    _, mappings = _mappings("kubed-mcp", print)
    assert [m.source for m in mappings][0] == {"local": {"path": "kubed/mcp"}}
    assert len(mappings) == 3


def test_what_it_cannot_map(image) -> None:
    image(mcp(), slim())
    with pytest.raises(_Unmappable, match=r"^nope is not installed$"):
        _mappings("nope", print)
    image(Fake("kubed-mcp-kb", "1.4.0", ["kubed_mcp_kb.py"]), mcp(), slim())
    with pytest.raises(_Unmappable, match=r"^kubed-mcp-kb's files hold no package$"):
        _mappings("kubed-mcp-kb", print)
    image(kb(), mcp("0.7.1.dev3"), slim())
    with pytest.raises(_Unmappable, match=r"^kubed-mcp 0\.7\.1\.dev3 has no tag or commit to map to$"):
        _mappings("kubed-mcp-kb", print)


def test_what_it_leaves_out(image) -> None:
    lines: list[str] = []
    editable = Fake("kubed-mcp", "0.7.1.dev3+g311c152", ["__editable__.kubed_mcp-0.7.1.pth"],
                    ["Repository, https://github.com/kubed-io/quick-mcp"])
    image(kb(), editable)
    _, mappings = _mappings("kubed-mcp-kb", lines.append)
    assert [m.directory for m in mappings] == [f"{SITE}/kubed/mcp_kb/", "/usr/local/lib/python3.14/"]
    assert lines == [
        "kubed-mcp's files hold no package, as in an editable install: its frames stay unmapped",
        "fastmcp-slim is not installed: its frames stay unmapped",
    ]
  • Step 2: Run them to verify they fail

Run: pytest tests/test_source_links.py -v Expected: collection fails with ModuleNotFoundError: No module named 'kubed.mcp.pyroscope'.

  • Step 3: Implement the module's mapping half in kubed/mcp/pyroscope.py

  • The module docstring says why the module exists: Pyroscope reads .pyroscope.yaml from the server's repository at service_git_ref, so the file is committed. Only the built image knows the true paths and versions, so the command runs there.

  • _ref checks the local part first: \+g([0-9a-f]{7,40}) gives commit or that sha. Then ^\d+\.\d+\.\d+$ gives v and the version, and ^(\d+\.\d+\.\d+)rc(\d+)$ gives v\1-rc.\2. Anything else gives None. A commit passed for a final or rc version is ignored.

  • _github matches ^https://github\.com/([^/]+)/([^/]+?)(?:\.git)?/?$ against the URL of the first Project-URL whose normalised label is in {"source", "repository", "sourcecode", "github"}. The label is lowercased with [\W_] removed, as PEP 753 does. A value is split at its first ", ".

  • _packages reads dist.files or []. It keeps each __init__.py whose parent's own __init__.py isn't among the files. The import path is parent.as_posix(). The directory is f"{dist.locate_file(parent)}/", not resolved.

  • _mappings builds each row of TEL-26's table in order, skipping a distribution whose normalised name an earlier row already mapped:

    • the named distribution's packages become local sources;
    • kubed-mcp, at _ref(version, _commit(dist)), has GitHub path kubed/mcp;
    • fastmcp-slim, at v{version}, has GitHub path f"{_MONOREPO[...]}/{import path}";
    • the standard library is _stdlib().rstrip("/") + "/", at v{_python()}.

    A GitHub-mapped distribution gets one mapping per package. The _Unmappable and warn lines are design item 6's.

  • Step 4: Run the tests to verify they pass

Run: pytest tests/test_source_links.py tests/test_facade.py -v Expected: PASS, the new import check included.

  • Step 5: Checks and commit

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

git add kubed/mcp/pyroscope.py tests/test_source_links.py tests/test_facade.py
git commit -m "feat(telemetry): map an image's packages to their sources for Pyroscope"

Task 3: TEL-26, --write and --check

Files:

  • Modify: kubed/mcp/pyroscope.py: _normalised, main and the __main__ guard.
  • Create: tests/data/mcp-kb.pyroscope.yaml: mcp-kb's committed file, copied byte for byte from mcp-kb's main with gh api repos/kubed-io/mcp-kb/contents/.pyroscope.yaml -H "Accept: application/vnd.github.raw". Its header comment gets one line naming where it came from and the commit it was copied at.
  • Modify: tests/test_source_links.py: this task's tests.
  • Modify: docs/superpowers/specs/telemetry.md: drop (proposed) from TEL-26, TEL-27 and the use case.

Interfaces:

  • Consumes: _mappings, _render, _Unmappable, _normalise and the seams from Task 2.

  • Produces:

    • _normalised(document: object) -> dict[str, object] | None (design item 5);
    • main(argv: Sequence[str] | None = None) -> int, run by if __name__ == "__main__": raise SystemExit(main()). It parses with argparse.ArgumentParser(prog="python -m kubed.mcp.pyroscope"):
      • a required, mutually exclusive --write / --check;
      • the positional distribution;
      • an optional positional file. With --write, a file is a parser.error.
  • Step 1: Write the failing tests

FIXTURE = Path(__file__).with_name("data") / "mcp-kb.pyroscope.yaml"


def written(image, capsys, *fakes, **env) -> str:
    image(*fakes, **env)
    assert main(["--write", "kubed-mcp-kb"]) == 0
    return capsys.readouterr().out


def test_write_prints_the_file(image, capsys) -> None:
    image(kb(), mcp(), slim())
    assert main(["--write", "kubed-mcp-kb"]) == 0
    out, err = capsys.readouterr()
    assert out == _render(*_mappings("kubed-mcp-kb", print)) and err == ""


@pytest.mark.parametrize("spelling", ["kubed_mcp_kb", "Kubed-MCP-KB"])
def test_the_name_is_read_as_pip_reads_it(image, capsys, spelling) -> None:
    text = written(image, capsys, kb(), mcp(), slim())
    assert main(["--write", spelling]) == 0
    assert capsys.readouterr().out == text


def test_it_reproduces_mcp_kbs_committed_file(image, capsys) -> None:
    image(kb(), mcp("0.6.1"), slim())  # the versions mcp-kb's file names
    assert main(["--check", "kubed-mcp-kb", str(FIXTURE)]) == 0
    assert capsys.readouterr() == ("", "")


def test_check_ignores_order_grouping_and_comments(image, capsys, monkeypatch) -> None:
    document = yaml.safe_load(written(image, capsys, kb(), mcp(), slim()))
    split = [dict(m, path=[p]) for m in reversed(document["source_code"]["mappings"]) for p in m["path"]]
    document["source_code"]["mappings"] = split
    monkeypatch.setattr(sys, "stdin", io.StringIO("# by hand\n" + yaml.safe_dump(document)))
    assert main(["--check", "kubed-mcp-kb"]) == 0


@pytest.mark.parametrize("given", [[], ["-"]])
def test_check_reads_stdin(image, capsys, monkeypatch, given) -> None:
    text = written(image, capsys, kb(), mcp(), slim())
    monkeypatch.setattr(sys, "stdin", io.StringIO(text))
    assert main(["--check", "kubed-mcp-kb", *given]) == 0


def test_a_moved_ref_is_stale(image, capsys, monkeypatch) -> None:
    committed = written(image, capsys, kb(), mcp("0.6.1"), slim())
    image(kb(), mcp("0.7.0"), slim())
    monkeypatch.setattr(sys, "stdin", io.StringIO(committed))
    assert main(["--check", "kubed-mcp-kb"]) == 1
    out, err = capsys.readouterr()
    assert out.splitlines()[:2] == ["--- .pyroscope.yaml (committed)", "+++ .pyroscope.yaml (this image)"]
    assert any(line.startswith("-") and "v0.6.1" in line for line in out.splitlines()[2:])
    assert any(line.startswith("+") and "v0.7.0" in line for line in out.splitlines()[2:])
    assert err == "kubed.mcp.pyroscope: .pyroscope.yaml is stale: regenerate it with --write kubed-mcp-kb in this image\n"


@pytest.mark.parametrize("committed", ["version: v1\n", "not: [a, map\n", "- just\n- a list\n"])
def test_a_file_that_is_not_a_source_map_is_stale(image, capsys, monkeypatch, committed) -> None:
    image(kb(), mcp(), slim())
    monkeypatch.setattr(sys, "stdin", io.StringIO(committed))
    assert main(["--check", "kubed-mcp-kb"]) == 1


@pytest.mark.parametrize("empty", ["", "\n  \n"])
def test_empty_input_says_how_to_pass_it(image, capsys, monkeypatch, empty) -> None:
    image(kb(), mcp(), slim())
    monkeypatch.setattr(sys, "stdin", io.StringIO(empty))
    assert main(["--check", "kubed-mcp-kb"]) == 2
    assert capsys.readouterr() == ("", "kubed.mcp.pyroscope: read nothing: pass the file's path, or run docker with -i so stdin reaches the command\n")


def test_what_it_cannot_map_exits_2_naming_it(image, capsys) -> None:
    image(mcp(), slim())
    assert main(["--write", "nope"]) == 2
    assert capsys.readouterr() == ("", "kubed.mcp.pyroscope: nope is not installed\n")


def test_write_takes_no_file(image) -> None:
    image(kb(), mcp(), slim())
    with pytest.raises(SystemExit) as exit:
        main(["--write", "kubed-mcp-kb", ".pyroscope.yaml"])
    assert exit.value.code == 2


def test_the_real_entry_point_in_this_environment() -> None:
    run = [sys.executable, "-m", "kubed.mcp.pyroscope"]
    wrote = subprocess.run([*run, "--write", "fastmcp-slim"], capture_output=True, text=True, timeout=60)
    assert wrote.returncode == 0, wrote.stderr
    mappings = yaml.safe_load(wrote.stdout)["source_code"]["mappings"]
    assert mappings[0]["source"] == {"local": {"path": "fastmcp"}}
    assert mappings[-1]["source"] == {"github": {"owner": "python", "repo": "cpython",
                                                 "ref": f"v{platform.python_version()}", "path": "Lib"}}
    assert mappings[-1]["path"][0]["prefix"] == sysconfig.get_paths()["stdlib"].rstrip("/") + "/"
    checked = subprocess.run([*run, "--check", "fastmcp-slim"], input=wrote.stdout,
                             capture_output=True, text=True, timeout=60)
    assert checked.returncode == 0, checked.stdout + checked.stderr

The entry-point test names fastmcp-slim because it's installed in every test environment, and the CI install of kubed-mcp is a wheel while a local one is editable. kubed-mcp's row is then there or left out with a line, and the test passes either way.

  • Step 2: Run them to verify they fail

Run: pytest tests/test_source_links.py -v Expected: Task 3's tests fail on ImportError: cannot import name 'main', and the entry-point test fails with a non-zero exit. Task 2's tests still pass.

  • Step 3: Implement _normalised and main

  • main's flow:

    1. parse;
    2. _mappings(distribution, warn), where warn writes design item 6's prefix and the line to stderr. An _Unmappable writes its line and returns 2;
    3. --write writes _render(...) to stdout and returns 0;
    4. --check reads file with Path.read_text(encoding="utf-8"), or stdin for none or -. A text that is blank after strip() writes the empty-input line and returns 2. A file that can't be read writes {file} can't be read: {type(error).__name__} and returns 2;
    5. yaml.YAMLError from yaml.safe_load makes the document None;
    6. when _normalised(committed) == _normalised(image's) and isn't None, it returns 0 and prints nothing;
    7. otherwise it writes difflib.unified_diff(...) with design item 6's file names to stdout, writes the stale line to stderr, and returns 1.
  • _normalised returns None for anything but a dict whose source_code.mappings is a list of dicts, each holding a list path of dicts with a string prefix, a string language and a dict source.

  • Step 4: Run the tests to verify they pass

Run: pytest tests/test_source_links.py -v Expected: PASS. If test_it_reproduces_mcp_kbs_committed_file fails, read the diff. A difference that isn't a comment or a moved ref is a bug in the module, since mcp-kb's file is what works in Pyroscope today. A ref that has moved since mcp-kb committed means the fixture's versions are what image(...) takes, so set them to the file's.

  • Step 5: Drop (proposed) from TEL-26, TEL-27 and the use case; checks; commit

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

git add kubed/mcp/pyroscope.py tests/test_source_links.py tests/data/mcp-kb.pyroscope.yaml
git commit -m "feat(telemetry): python -m kubed.mcp.pyroscope writes and checks .pyroscope.yaml"

Task 4: The Telemetry Guide and the changelog

Files:

  • Modify: docs/Telemetry-Guide.md: the H1 becomes # Telemetry Guide, the intro sentence names both subjects, and a new ## Source links section goes after ## Measuring it again.

  • Modify: docs/Home.md: the Telemetry Guide row reads "Know what telemetry costs, lower it, and link profiles to their source".

  • Modify: CHANGELOG.md, [Unreleased]: one ### Added section.

  • Step 1: The guide's ## Source links, for the operator of a server, in this order:

    1. What it gives: a frame in a Grafana flame graph opens its file at its line on GitHub, for the server, kubed-mcp, FastMCP and the standard library (TEL-25, TEL-26).

    2. The image sets the build, with the commit passed as a build argument:

      ARG SERVICE_GIT_REF
      ENV SERVICE_REPOSITORY=https://github.com/example/server \
          SERVICE_GIT_REF=${SERVICE_GIT_REF}

      docker build --build-arg SERVICE_GIT_REF="$(git rev-parse HEAD)" .

    3. Write the file in the built image and commit it at the repository's root: docker run --rm <image> python -m kubed.mcp.pyroscope --write <distribution> > .pyroscope.yaml. Pyroscope reads it from the repository at service_git_ref, so a file only in the image does nothing.

    4. Commit it with the change that moves a version. The image built from that change checks clean, and until the file is committed the check fails, which is the point.

    5. Check it in CI, in a job after the image builds:

      source-map:
        needs: image
        runs-on: ubuntu-26.04
        steps:
        - uses: actions/checkout@v7
          with:
            persist-credentials: false
        - name: Check .pyroscope.yaml
          env:
            IMAGE: ${{ needs.image.outputs.image }}
          run: docker run -i --rm "$IMAGE" python -m kubed.mcp.pyroscope --check <distribution> < .pyroscope.yaml

      -i is what lets stdin reach the command.

    6. What isn't mapped: other distributions' frames, such as pydantic's or uvicorn's, show no source. A package below src/ in its repository isn't mapped either (TEL-26's "Not now").

    7. Grafana's side, in one line: the Pyroscope datasource needs the GitHub integration's session cookie kept, or every lookup after sign-in fails. That is the deployment's, not the server's.

  • Step 2: The changelog, under [Unreleased]:

### Added

- Profiles carry `service_repository` and `service_git_ref` from `SERVICE_REPOSITORY` and `SERVICE_GIT_REF`, so Pyroscope opens a frame's source at the image's commit.
- **`python -m kubed.mcp.pyroscope`** writes a server's `.pyroscope.yaml` from inside its image, and `--check` fails CI when the committed one is stale.
  • Step 3: Checks

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

git add CHANGELOG.md
git commit -m "docs: source links in the Telemetry Guide; the changelog"

Follow-ups (not this change)

  • vcs.repository.url.full and vcs.ref.head.revision as resource attributes on traces and metrics.
  • SERVICE_ROOT_PATH to service_root_path.
  • Mapping more distributions: pydantic, starlette, uvicorn, anyio, mcp.
  • Per server: Image Builder's build argument (kubed-io/actions), the Dockerfile's ENV, the committed file and the CI check, in mcp-kb and selenium-flow.

Clone this wiki locally