Repository navigation
2026 11 28 pyroscope source links
History. Written 2026-11-28 for Dr K. It is the plan of record for #100, built in #101 on
issue-100, which merges intomainas 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.
Dr K's rulings aren't to be reopened:
- the labels come from
SERVICE_REPOSITORYandSERVICE_GIT_REF, on profiles only; - the command runs inside the built image, with
--writeand--check, aspython -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).
-
FastMCP is read from
fastmcp-slim, notfastmcp(settled here, found in this round).- Since FastMCP 4,
fastmcpis a meta-distribution:fastmcp 4.2.6requiresfastmcp-slim[client,server]==4.2.6and installs no code. -
fastmcp-sliminstallsfastmcp/. Its Project-URLRepositoryishttps://github.com/PrefectHQ/fastmcp, which is PyPI's record for 4.2.6. - FastMCP's repository at
v4.2.6holdsfastmcp_slim/fastmcp/,fastmcp_tasks/fastmcp_tasks/andfastmcp_events/. Sofastmcp-tasksinstalls a top-level package of its own and doesn't write intofastmcp/. - 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.
- Since FastMCP 4,
-
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=311c152with the file, the same as for the full311c15298c0c…. So a dev build withoutdirect_url.json's commit maps to itsg<sha>, and no fallback is needed. The full commit is used when pip recorded one (PEP 610:vcs_info.commit_id, written bypip install git+…). -
The exit codes (settled here):
-
0: written, or up to date; -
1:--checkfound 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.
-
-
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. -
--checkcompares 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 toNoneand is stale. The diff shown is the text's, from the committed file to the image's, so a reader sees what to commit. -
Exact copy (settled here). Every stderr line starts
kubed.mcp.pyroscope:.{Name}is the distribution's metadataName, 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 installednamed distribution, no package stderr {Name}'s files hold no packageno GitHub Project-URL stderr {Name}'s Project-URL names no GitHub repositorykubed-mcp without a ref stderr kubed-mcp {version} has no tag or commit to map tofastmcp-slim missing stderr fastmcp-slim is not installed: its frames stay unmappedGitHub-mapped, no package stderr {Name}'s files hold no package, as in an editable install: its frames stay unmappedstale stderr .pyroscope.yaml is stale: regenerate it with --write {Name} in this imageempty input stderr read nothing: pass the file's path, or run docker with -i so stdin reaches the command<file>unreadablestderr {file} can't be read: {type(error).__name__}diff headers stdout --- .pyroscope.yaml (committed)and+++ .pyroscope.yaml (this image) -
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.dis the installed directory, ending in/. - A source is
{"local": {"path": "kubed/mcp_kb"}}, or{"github": {"owner": …, "repo": …, "ref": …, "path": …}}in that key order.
- The document is
-
The module never imports the top-level
pyroscope.telemetry.py'simport pyroscopeis absolute, so the new module doesn't shadow it. The new module imports only the standard library andyaml, and no FastMCP:tests/test_facade.py's import check gains it.
-
from __future__ import annotationsat 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 inkubed/mcp/pyroscope.pybutmainis private. -
kubed/mcp/pyroscope.pyimports only the standard library andyaml, with no relative import, and doesn't need thetelemetryextra. -
_otel._resource_attributesisn't touched. The two new labels are for profiles only (TEL-25). -
Tests:
- no network;
- the module's tests build distributions as
importlib.metadata.Distributionfakes, 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.ymlrunsruff check ., andtest.ymlrunspytestafterpip install .[test,tasks]. This repository's plans also runruff format --check .. Locally, runpip install -e .[test,tasks], thenruff check . && ruff format --check . && pytest. -
The wiki. Edits are left in the
docs/checkout. The job commits them on the wiki branchissue-100and moves the pointer here. No git runs insidedocs/, and the wiki'smasteris never pushed. Spec text is in the present tense, with no issue numbers. Examples useexample.comandgithub.com/example/server. -
.github/isn't touched. The pull request takesrelease:minor.
-
docker runwithout-i. stdin is empty, so a--checkthat compared would call every mapping stale. It must exit 2 and say why (Task 3,test_empty_input_says_how_to_pass_it). -
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). -
A committed file written by hand, like mcp-kb's: another order, one mapping per prefix,
comments.
--checkmust pass when the mappings are the same (Task 3,test_it_reproduces_mcp_kbs_committed_file,test_check_ignores_order_grouping_and_comments). -
The distribution's name spelled another way,
kubed_mcp_kborKubed-MCP-KB. It must write the same bytes, with the header namingkubed-mcp-kb(Task 3,test_the_name_is_read_as_pip_reads_it). -
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).
Files:
- Modify:
kubed/mcp/telemetry.py:_profile_tags, and its docstring. - Modify:
tests/test_telemetry.py: the_cleanfixture and_child's exclusion list gainSERVICE_REPOSITORYandSERVICE_GIT_REF. New tests go besidetest_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], thepyroscopeandservedtest helpers. -
Produces:
_profile_tagswith the same signature. Labels in this order:namespace,pod,service_repository,service_git_ref, thentags, 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, afterpod
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"Files:
- Create:
kubed/mcp/pyroscope.py: the module docstring,_MONOREPO,_Mapping,_Unmappable,_ref,_commit,_github,_packages, the seams,_mappingsand_render. - Create:
tests/test_source_links.py: theFakedistribution, theimagefixture, and this task's tests. Nottest_pyroscope.py: the suite'spyroscopefixture 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]].directoryis 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).Nonemeans no ref; -
_commit(dist: Distribution) -> str | None:direct_url.json'svcs_info.commit_id, orNonewhen the file,vcs_infoor 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,NoneonPackageNotFoundError),_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 metadataNameand its mappings in TEL-26's order. It raises_Unmappable; -
_render(name: str, mappings: Sequence[_Mapping]) -> str: the header forname, 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 installsource_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.yamlfrom the server's repository atservice_git_ref, so the file is committed. Only the built image knows the true paths and versions, so the command runs there. -
_refchecks the local part first:\+g([0-9a-f]{7,40})givescommit orthat sha. Then^\d+\.\d+\.\d+$givesvand the version, and^(\d+\.\d+\.\d+)rc(\d+)$givesv\1-rc.\2. Anything else givesNone. A commit passed for a final or rc version is ignored. -
_githubmatches^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", ". -
_packagesreadsdist.files or []. It keeps each__init__.pywhose parent's own__init__.pyisn't among the files. The import path isparent.as_posix(). The directory isf"{dist.locate_file(parent)}/", not resolved. -
_mappingsbuilds 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
localsources; - kubed-mcp, at
_ref(version, _commit(dist)), has GitHub pathkubed/mcp; - fastmcp-slim, at
v{version}, has GitHub pathf"{_MONOREPO[...]}/{import path}"; - the standard library is
_stdlib().rstrip("/") + "/", atv{_python()}.
A GitHub-mapped distribution gets one mapping per package. The
_Unmappableandwarnlines are design item 6's. - the named distribution's packages become
-
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"Files:
- Modify:
kubed/mcp/pyroscope.py:_normalised,mainand the__main__guard. - Create:
tests/data/mcp-kb.pyroscope.yaml: mcp-kb's committed file, copied byte for byte from mcp-kb'smainwithgh 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,_normaliseand the seams from Task 2. -
Produces:
-
_normalised(document: object) -> dict[str, object] | None(design item 5); -
main(argv: Sequence[str] | None = None) -> int, run byif __name__ == "__main__": raise SystemExit(main()). It parses withargparse.ArgumentParser(prog="python -m kubed.mcp.pyroscope"):- a required, mutually exclusive
--write/--check; - the positional
distribution; - an optional positional
file. With--write, afileis aparser.error.
- a required, mutually exclusive
-
-
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.stderrThe 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
_normalisedandmain -
main's flow:- parse;
-
_mappings(distribution, warn), wherewarnwrites design item 6's prefix and the line to stderr. An_Unmappablewrites its line and returns 2; -
--writewrites_render(...)to stdout and returns 0; -
--checkreadsfilewithPath.read_text(encoding="utf-8"), or stdin for none or-. A text that is blank afterstrip()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; -
yaml.YAMLErrorfromyaml.safe_loadmakes the documentNone; - when
_normalised(committed) == _normalised(image's)and isn'tNone, it returns 0 and prints nothing; - otherwise it writes
difflib.unified_diff(...)with design item 6's file names to stdout, writes the stale line to stderr, and returns 1.
-
_normalisedreturnsNonefor anything but a dict whosesource_code.mappingsis a list of dicts, each holding a listpathof dicts with a stringprefix, a stringlanguageand a dictsource. -
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"Files:
-
Modify:
docs/Telemetry-Guide.md: the H1 becomes# Telemetry Guide, the intro sentence names both subjects, and a new## Source linkssection 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### Addedsection. -
Step 1: The guide's
## Source links, for the operator of a server, in this order:-
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).
-
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)" . -
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 atservice_git_ref, so a file only in the image does nothing. -
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.
-
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
-iis what lets stdin reach the command. -
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"). -
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"-
vcs.repository.url.fullandvcs.ref.head.revisionas resource attributes on traces and metrics. -
SERVICE_ROOT_PATHtoservice_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.
These pages describe what is on main; the spec says what is built and what is only proposed.
kubed-mcp · MIT