Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 55 additions & 1 deletion tests/benchmarks/journeys.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
import tempfile
import time
from collections.abc import Callable, Iterator
from dataclasses import asdict, dataclass, field
from dataclasses import asdict, dataclass, field, replace
from pathlib import Path

import yaml
Expand Down Expand Up @@ -77,6 +77,8 @@
"install-frozen-warm",
"install-global-cold",
"install-global-warm",
"install-cold-auth",
"install-warm-auth",
"update",
"uninstall",
"outdated",
Expand Down Expand Up @@ -676,19 +678,29 @@ class Journey:
name: str
setup: Callable[[Context], None]
steps: Callable[[Context], list[Step]]
# Extra child environment for this journey only (setup, timed steps, profile).
env: tuple[tuple[str, str], ...] = ()


def _noop(_ctx: Context) -> None:
return None


_AUTH = (("GITHUB_APM_PAT", "ghp_" + "0" * 36), ("APM_GITHUB_AUTH_FIRST", "1"))


JOURNEYS: dict[str, Journey] = {
j.name: j
for j in (
Journey("boot-version", _noop, lambda c: [(["--version"], c.elsewhere)]),
Journey("boot-help", _noop, lambda c: [(["--help"], c.elsewhere)]),
Journey("install-cold", _setup_cold, lambda c: _per_root(c, ["install"])),
Journey("install-warm", _setup_warm, lambda c: _per_root(c, ["install"])),
# Authenticated users (private repos, GHE, ADO, GitLab, or a token to
# avoid the anonymous rate limit) take the token-first git CLI path: a
# fixed placeholder token the offline mirror accepts, auth first.
Journey("install-cold-auth", _setup_cold, lambda c: _per_root(c, ["install"]), _AUTH),
Journey("install-warm-auth", _setup_warm, lambda c: _per_root(c, ["install"]), _AUTH),
Comment thread
danielmeppiel marked this conversation as resolved.
Resolved
Journey("install-noop", Context.installed, lambda c: _per_root(c, ["install"])),
Journey("install-frozen", _setup_frozen, lambda c: _per_root(c, ["install", "--frozen"])),
Journey("install-locked-warm", _locked_project, lambda c: _per_root(c, ["install"])),
Expand Down Expand Up @@ -824,7 +836,49 @@ def _profile(ctx: Context, journey: Journey, out: Path) -> str | None:
return str(prof)


@contextlib.contextmanager
def _journey_env(ctx: Context, journey: Journey):
"""Overlay *journey*'s extra environment on the world's child env, then restore it."""
env = ctx.world.env
saved = {key: env.get(key) for key, _value in journey.env}
env.update(journey.env)
try:
yield
finally:
for key, value in saved.items():
if value is None:
env.pop(key, None)
else:
env[key] = value


def _refuse_real_auth(_ctx: Context) -> None:
raise RuntimeError(
"authenticated journeys on the real fixture need the caller's GITHUB_APM_PAT"
)


def _for_world(ctx: Context, journey: Journey) -> Journey:
"""*journey* as run against this world.

The placeholder token only works against the offline mirror. On real
github.com the caller's own token (copied by ``_RealWorld``) is used, and
without one the journey fails instead of measuring a rejected token.
"""
if not ctx.fixture.real or all(key != "GITHUB_APM_PAT" for key, _ in journey.env):
return journey
env = tuple(pair for pair in journey.env if pair[0] != "GITHUB_APM_PAT")
setup = journey.setup if ctx.world.env.get("GITHUB_APM_PAT") else _refuse_real_auth
return replace(journey, env=env, setup=setup)


def measure(ctx: Context, journey: Journey, args: argparse.Namespace) -> dict:
journey = _for_world(ctx, journey)
with _journey_env(ctx, journey):
return _measure(ctx, journey, args)


def _measure(ctx: Context, journey: Journey, args: argparse.Namespace) -> dict:
samples: list[Sample] = []
error = ""
for _ in range(args.runs):
Expand Down
63 changes: 62 additions & 1 deletion tests/benchmarks/spawn_counter/sitecustomize.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,23 @@
def _bump(table, key, by=1):
table[key] = table.get(key, 0) + by

def _split_command_line(text):
"""Split a ``list2cmdline`` string (Windows) on spaces outside double quotes."""
parts, current, quoted, any_char = [], [], False, False
for char in text:
if char == '"':
quoted, any_char = not quoted, True
Comment thread
danielmeppiel marked this conversation as resolved.
Resolved
elif char in " \t" and not quoted:
if current or any_char:
parts.append("".join(current))
current, any_char = [], False
else:
current.append(char)
any_char = True
if current or any_char:
parts.append("".join(current))
return parts

def _git_verb(argv):
rest = iter(argv[1:])
for item in rest:
Expand Down Expand Up @@ -85,7 +102,7 @@ def _hook(event, args):
_bump(_git_verbs, _git_verb(list(argv)))
elif isinstance(argv, (str, bytes)):
text = argv.decode(errors="replace") if isinstance(argv, bytes) else argv
_bump(_git_verbs, _git_verb(text.split()))
_bump(_git_verbs, _git_verb(_split_command_line(text)))

def _flush():
record = {"pid": os.getpid(), "spawns": _counts, "modules": len(sys.modules)}
Expand Down Expand Up @@ -124,6 +141,11 @@ def wrapper(*a, **k):
_bump(_fs, key)
return real(*a, **k)

# Keep platform capability checks (``f in os.supports_dir_fd``) true.
for name in ("supports_dir_fd", "supports_fd", "supports_follow_symlinks"):
capabilities = getattr(os, name, None)
if capabilities is not None and real in capabilities:
capabilities.add(wrapper)
setattr(module, attr, wrapper)
Comment thread
danielmeppiel marked this conversation as resolved.
Resolved

_counted(os.path, "realpath", "realpath_calls")
Expand Down Expand Up @@ -158,3 +180,42 @@ def make(*a, **k):

for _name in ("sha256", "sha1", "sha512", "md5"):
setattr(hashlib, _name, _hash_factory(getattr(hashlib, _name)))

_real_new = hashlib.new

def _new(name, *a, **k):
# ``hashlib.file_digest`` also builds through the module's ``new``.
_bump(_fs, "hash_objects")
Comment thread
danielmeppiel marked this conversation as resolved.
Resolved
data = a[0] if a else k.get("data", k.get("string", b""))
if data:
_bump(_fs, "hashed_bytes", len(data))
return _Hash(_real_new(name, *a, **k))

hashlib.new = _new


def _chain_next_sitecustomize():
"""Run the next ``sitecustomize`` on ``sys.path`` (e.g. a test network guard).

Prepending this directory shadows it, and the counters must never drop
the isolation the measured environment installs.
"""
here = os.path.dirname(os.path.abspath(__file__))
found_self = False
for entry in sys.path:
directory = os.path.abspath(entry or os.curdir)
if directory == here:
found_self = True
continue
candidate = os.path.join(directory, "sitecustomize.py")
if found_self and os.path.isfile(candidate):
import importlib.util

spec = importlib.util.spec_from_file_location("_chained_sitecustomize", candidate)
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return


_chain_next_sitecustomize()
11 changes: 8 additions & 3 deletions tests/integration/test_perf_count_budgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,17 @@ def test_install_stays_within_its_count_budget(journey: str, journey_runs) -> No
assert not over, "count budget exceeded:\n" + "\n".join(over)


def test_cold_install_clones_and_fetches_while_noop_spawns_no_git_fetch(journey_runs) -> None:
"""The counters see the work: a cold install clones over HTTP, a no-op does not."""
def test_cold_install_fetches_while_noop_fetches_nothing(journey_runs) -> None:
"""The counters see the work: a cold install fetches over HTTP, a no-op does not.

A cold install fetches in process (#5330): no ``git clone`` spawn, the work
shows as HTTP requests; a no-op spawns no clone and sends no request.
"""
(cold_run, _, cold), (noop_run, _, noop) = (
journey_runs["install-cold"],
journey_runs["install-noop"],
)
assert (cold_run.returncode, noop_run.returncode) == (0, 0), (cold_run.stderr, noop_run.stderr)
assert cold.get("git.clone", 0) > 0 and cold["http.requests"] > 0, cold
# Engagement oracle: if the in-process fetch stops engaging, clones come back.
assert cold.get("git.clone", 0) == 0 and cold["http.requests"] > 0, cold
assert noop.get("git.clone", 0) == 0 and noop["http.requests"] == 0, noop
78 changes: 24 additions & 54 deletions tests/perf/count_budgets.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,22 @@
"journeys": {
"install-cold": {
"fs.files_written": {
"budget": 1436,
"measured": 1367,
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
"budget": 1819,
"measured": 1732,
"reason": "#5330 in-process pinned fetch: the checkout's files are now written by the apm process (inprocess_fetch.py os.open), which the counter sees, instead of by an uncounted git clone/checkout child; tree-10, offline mirror, rtt 0; max of CI runs 45401098857 (1520) and 45403013362 (1732)",
"pr": "#5340"
},
"fs.hash_objects": {
"budget": 1608,
"measured": 1531,
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
"budget": 1950,
"measured": 1857,
"reason": "re-measured: the counter hook now also counts hashlib.new (checkout verification, file_digest); tree-10, offline mirror, rtt 0; CI run 45398516932 at cc381335",
"pr": "#5340"
},
"fs.hashed_bytes": {
"budget": 2852339,
"measured": 2716513,
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
"budget": 3381038,
"measured": 3220036,
"reason": "re-measured: the counter hook now also counts hashlib.new (checkout verification, file_digest); tree-10, offline mirror, rtt 0; CI run 45398516932 at cc381335",
"pr": "#5340"
},
"fs.lockfile_reads": {
"budget": 11,
Expand All @@ -44,53 +44,23 @@
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
},
"git.cat-file": {
"budget": 21,
"measured": 20,
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
},
"git.checkout": {
"budget": 11,
"measured": 10,
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
},
"git.clone": {
"budget": 21,
"measured": 20,
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
},
"git.config": {
"budget": 55,
"measured": 52,
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
},
"git.init": {
"budget": 11,
"measured": 10,
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
},
"git.ls-tree": {
"budget": 21,
"measured": 20,
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
},
"git.remote": {
"budget": 13,
"measured": 12,
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
},
"git.var": {
"budget": 3,
"measured": 2,
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
"budget": 5,
"measured": 4,
"reason": "#5330 in-process pinned fetch: its attribute-source probe `git var GIT_ATTR_SYSTEM` (memoized per child env) runs before the in-process checkout; tree-10, offline mirror, rtt 0; CI runs 45401098857 and 45403013362 (both 4)",
"pr": "#5340"
},
"http.connects": {
"budget": 14,
Expand All @@ -113,16 +83,16 @@
"pr": "#5338"
},
"fs.hash_objects": {
"budget": 1529,
"measured": 1456,
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
"budget": 1917,
"measured": 1825,
"reason": "re-measured: the counter hook now also counts hashlib.new (checkout verification, file_digest); tree-10, offline mirror, rtt 0; CI run 45398516932 at cc381335",
"pr": "#5340"
},
"fs.hashed_bytes": {
"budget": 2955248,
"measured": 2814521,
"reason": "baseline: tree-10, offline mirror, rtt 0; max of CI runs 45367791683 and 45367797615 on main 22324e63",
"pr": "#5338"
"budget": 3492216,
"measured": 3325920,
"reason": "re-measured: the counter hook now also counts hashlib.new (checkout verification, file_digest); tree-10, offline mirror, rtt 0; CI run 45398516932 at cc381335",
"pr": "#5340"
},
"fs.lockfile_reads": {
"budget": 11,
Expand Down
Loading