diffcone 0.5.0__tar.gz → 0.6.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. {diffcone-0.5.0 → diffcone-0.6.1}/PKG-INFO +1 -1
  2. {diffcone-0.5.0 → diffcone-0.6.1}/pyproject.toml +1 -1
  3. {diffcone-0.5.0 → diffcone-0.6.1}/pyproject.toml.orig +1 -1
  4. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/cache.py +34 -1
  5. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/ci_report.py +108 -0
  6. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/classify.py +28 -1
  7. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/cli.py +16 -0
  8. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/collect.py +84 -9
  9. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/discovery/pytest_static.py +191 -9
  10. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/evidence.py +49 -1
  11. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/evidence_plan.py +542 -142
  12. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/execution.py +15 -5
  13. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/__init__.py +18 -2
  14. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/core.py +295 -4
  15. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/definitions.py +3 -0
  16. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/facts.py +130 -2
  17. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/references.py +190 -18
  18. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/resolver.py +112 -17
  19. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/scopes.py +17 -2
  20. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/state.py +1 -0
  21. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/syntax.py +4 -0
  22. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/uses.py +399 -20
  23. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/writes.py +1609 -92
  24. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/model.py +100 -3
  25. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/planner.py +395 -46
  26. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/report.py +34 -5
  27. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/snapshot.py +72 -37
  28. {diffcone-0.5.0 → diffcone-0.6.1}/LICENSE +0 -0
  29. {diffcone-0.5.0 → diffcone-0.6.1}/README.md +0 -0
  30. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/__init__.py +0 -0
  31. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/check.py +0 -0
  32. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/child.py +0 -0
  33. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/cython.py +0 -0
  34. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/declarations.py +0 -0
  35. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/discovery/__init__.py +0 -0
  36. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/discovery/asv_static.py +0 -0
  37. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/discovery/common.py +0 -0
  38. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/discovery/session_state.py +0 -0
  39. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/aliases.py +0 -0
  40. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/dynamics.py +0 -0
  41. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/lazy.py +0 -0
  42. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/literals.py +0 -0
  43. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/patches.py +0 -0
  44. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/process.py +0 -0
  45. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/scripts.py +0 -0
  46. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/indexer/symbols.py +0 -0
  47. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/manifest.py +0 -0
  48. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/selection.py +0 -0
  49. {diffcone-0.5.0 → diffcone-0.6.1}/src/diffcone/testing.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: diffcone
3
- Version: 0.5.0
3
+ Version: 0.6.1
4
4
  Summary: Static-first, function-level change-impact engine for Python: which tests and benchmarks a change can affect, and why
5
5
  Keywords: test selection,test impact analysis,change impact,pytest,asv,ci
6
6
  Author: Bearing Research
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "diffcone"
3
- version = "0.5.0"
3
+ version = "0.6.1"
4
4
  description = "Static-first, function-level change-impact engine for Python: which tests and benchmarks a change can affect, and why"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "diffcone"
3
- version = "0.5.0"
3
+ version = "0.6.1"
4
4
  description = "Static-first, function-level change-impact engine for Python: which tests and benchmarks a change can affect, and why"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -62,6 +62,31 @@ from diffcone.model import (
62
62
  # 64: typed_calls and shared_instances; receiver attribute stores keep
63
63
  # their name (``@self.x``), re-initialisation is ``@init``; memoisers
64
64
  # applied by a call (audit round 7, U4, U5, U14, U15, U16, U17, U18);
65
+ # 65: open classes include those with an ``abc.ABC``, ``Protocol``,
66
+ # ``NamedTuple`` or ``TypedDict`` base (audit round 8, V4);
67
+ # 66: what an install in sys.modules installs (``>`` sources, ``installs``
68
+ # edges, SourceIndex.installed_names), readers of a name outside the
69
+ # roots depend on the installing code (audit round 8, V10, V11);
70
+ # 67: the logging library's callbacks and records, writes through ``*args``/
71
+ # ``**kwargs`` and starred arguments and through what a fresh object
72
+ # holds, module-level ``locals()`` (audit round 8, V1, V4, V7, V8, V9);
73
+ # 68: open classes include those whose body hands ``locals()``/``vars()`` on
74
+ # (audit round 8, V4, evidence);
75
+ # 69: a call's result written writes what the callee may return of what it was
76
+ # handed (``result_calls``, ``param_returns``), elements of a parameter
77
+ # handed on, a function stored as a logging callback called by name
78
+ # (audit round 8, V7, V19, V20);
79
+ # 70: the variables logging callbacks write depend on the log sites through
80
+ # one pseudo-node per set of callbacks (model.LOG_CALLBACKS);
81
+ # 71: SourceIndex.open_installs (the code installing, under a name outside
82
+ # the roots, what no module of the analysis names; discovery's plugins);
83
+ # 72: SourceIndex.definition_writes and definition_calls (what only a
84
+ # function's decorators, defaults and annotations write or call; audit
85
+ # round 8, V28);
86
+ # 73: a library module reached through a project module's import binding is
87
+ # read for what follows it, and the receiver of a call naming its
88
+ # attributes literally (``monkeypatch.setattr(m.sys, "x", v)``) for those
89
+ # attributes only (audit round 8, V30);
65
90
  # 59: a class attribute bound once to a value that cannot change in place
66
91
  # is no root of its class (audit round 6, T24); an instance holds the
67
92
  # arguments its constructor was handed, and only a write that may reach
@@ -120,7 +145,7 @@ from diffcone.model import (
120
145
  # and modules (indexer.uses); 28: __subclasses__ reads; 27: type
121
146
  # parameters, unnameable build scripts as other files; 26: escaped values;
122
147
  # 25: external sites; 24: docstring decorators; 23: open classes
123
- INDEX_FORMAT = 64
148
+ INDEX_FORMAT = 74
124
149
 
125
150
 
126
151
  def _indexer_fingerprint() -> str:
@@ -198,6 +223,8 @@ def index_to_dict(index: SourceIndex) -> dict:
198
223
  "attribute_modules": sorted(index.attribute_modules),
199
224
  "any_module_readers": sorted(index.any_module_readers),
200
225
  "module_writers": {m: list(w) for m, w in sorted(index.module_writers.items())},
226
+ "installed_names": {n: list(v) for n, v in sorted(index.installed_names.items())},
227
+ "open_installs": {n: [list(w) for w in v] for n, v in sorted(index.open_installs.items())},
201
228
  "other_files": dict(sorted(index.other_files.items())),
202
229
  "file_modes": dict(sorted(index.file_modes.items())),
203
230
  "symbols": [asdict(s) for _, s in sorted(index.symbols.items())],
@@ -228,6 +255,8 @@ def index_to_dict(index: SourceIndex) -> dict:
228
255
  "typed_calls": sorted(list(t) for t in index.typed_calls),
229
256
  "shared_instances": sorted(index.shared_instances),
230
257
  "lazy_constants": dict(sorted(index.lazy_constants.items())),
258
+ "definition_writes": sorted(list(w) for w in index.definition_writes),
259
+ "definition_calls": sorted(list(c) for c in index.definition_calls),
231
260
  "cython": {
232
261
  path: {
233
262
  "functions": [{**asdict(f), "names": sorted(f.names)} for f in module.functions],
@@ -271,6 +300,8 @@ def index_from_dict(data: dict) -> SourceIndex:
271
300
  attribute_modules=set(data["attribute_modules"]),
272
301
  any_module_readers=set(data["any_module_readers"]),
273
302
  module_writers={m: tuple(w) for m, w in data["module_writers"].items()},
303
+ installed_names={n: tuple(v) for n, v in data["installed_names"].items()},
304
+ open_installs={n: tuple((w, a) for w, a in v) for n, v in data["open_installs"].items()},
274
305
  other_files=dict(data["other_files"]),
275
306
  file_modes=dict(data["file_modes"]),
276
307
  reflection={(s, d) for s, d in data["reflection"]},
@@ -292,6 +323,8 @@ def index_from_dict(data: dict) -> SourceIndex:
292
323
  typed_calls={(a, b) for a, b in data["typed_calls"]},
293
324
  shared_instances=set(data["shared_instances"]),
294
325
  lazy_constants=dict(data["lazy_constants"]),
326
+ definition_writes={(a, b) for a, b in data["definition_writes"]},
327
+ definition_calls={(a, b) for a, b in data["definition_calls"]},
295
328
  cython={
296
329
  path: CythonModule(
297
330
  path,
@@ -16,13 +16,21 @@ pull-request runs (selected share, plans made from the code instead of a
16
16
  recording and why, refusals) and checked pushes (checked or not and why,
17
17
  new failures, flaky re-runs, confirmed misses), then each confirmed miss.
18
18
  It reads files only and runs nothing, like ``check``.
19
+
20
+ ``python -m diffcone.ci_report ARCHIVE DIR`` writes from one downloaded
21
+ artifact (a zip) only what the report reads (``extract``): the report
22
+ action runs it on each artifact as it downloads, so a day of runs takes
23
+ what the report keeps, not what they uploaded.
19
24
  """
20
25
 
21
26
  from __future__ import annotations
22
27
 
23
28
  import copy
24
29
  import json
30
+ import os
25
31
  import statistics
32
+ import sys
33
+ import zipfile
26
34
  from collections import Counter
27
35
  from dataclasses import dataclass, field
28
36
  from pathlib import Path
@@ -31,6 +39,8 @@ from typing import Any
31
39
  ARTIFACT_FILES = frozenset(
32
40
  {"context.json", "plan.json", "ran.json", "verdict.json", "rerun-verdict.json"}
33
41
  )
42
+ # The plans, in the order ``load`` reads them: ran.json, else plan.json.
43
+ PLAN_FILES = ("ran.json", "plan.json")
34
44
 
35
45
 
36
46
  # The events a recording runs on. A ``record`` context from any other run (a
@@ -168,6 +178,98 @@ def _plan_read(plan: dict[str, Any] | None) -> dict[str, Any] | None:
168
178
  return out
169
179
 
170
180
 
181
+ def _plan_text(text: str) -> Any:
182
+ """``json.loads`` of a plan, skipping ``dependency_explanations`` where
183
+ the plan is laid out as diffcone writes it (indented by two): nine
184
+ tenths of a large plan, which the report does not read. A raw newline
185
+ cannot fall inside a JSON string, so a newline, two spaces and a quote
186
+ starts a key of the top-level object; a cut anywhere else leaves text
187
+ that does not parse, and the whole is parsed instead."""
188
+ key = '\n "dependency_explanations": '
189
+ start = text.find(key)
190
+ if start != -1:
191
+ end = text.find('\n "', start + len(key))
192
+ if end != -1:
193
+ try:
194
+ data = json.loads(text[:start] + text[end:])
195
+ except ValueError:
196
+ pass
197
+ else:
198
+ if isinstance(data, dict):
199
+ return data
200
+ return json.loads(text)
201
+
202
+
203
+ def _member(info: zipfile.ZipInfo) -> str | None:
204
+ """The file of ``ARTIFACT_FILES`` an archive member is when the whole
205
+ archive is extracted (``ZipFile.extractall``), or None: an absolute
206
+ name, a drive, empty, ``.`` and ``..`` parts are dropped, so
207
+ ``./context.json`` and ``/context.json`` are context.json and
208
+ ``sub/context.json`` is none of them."""
209
+ if info.is_dir():
210
+ return None
211
+ name = info.filename
212
+ if os.sep != "/":
213
+ name = name.replace("/", os.sep)
214
+ if os.altsep and os.altsep != "/":
215
+ name = name.replace(os.altsep, os.sep)
216
+ name = os.path.splitdrive(name)[1]
217
+ parts = [p for p in name.split(os.sep) if p not in ("", os.curdir, os.pardir)]
218
+ return parts[0] if len(parts) == 1 and parts[0] in ARTIFACT_FILES else None
219
+
220
+
221
+ def _archived_plan(zf: zipfile.ZipFile, info: zipfile.ZipInfo) -> tuple[dict | None, bool]:
222
+ """A plan member as ``_read`` reads it (None when unreadable or not an
223
+ object), and whether it is truthy there. ``_plan_text`` cuts the
224
+ explanations only when another key follows them, so what it returns is
225
+ empty exactly when the plan is."""
226
+ try:
227
+ text = zf.read(info).decode("utf-8")
228
+ plan = _plan_text(text)
229
+ except ValueError:
230
+ return None, False
231
+ if not isinstance(plan, dict):
232
+ return None, False
233
+ return plan, bool(plan)
234
+
235
+
236
+ def extract(archive: str | Path, directory: str | Path) -> list[str]:
237
+ """Write into ``directory`` the files of a downloaded artifact that
238
+ ``load`` reads, the plan cut to what ``_plan_read`` keeps: what ``load``
239
+ then reads is what it reads of the whole artifact extracted. ``load``
240
+ reads ran.json, or plan.json when ran.json is missing, unreadable or
241
+ empty (``{}``): only the plan it would read is written, under its own
242
+ name, with a key ``_plan_read`` drops so that it never reads as empty
243
+ (a ran.json of no key the report reads is not plan.json's). Returns
244
+ the names written."""
245
+ target = Path(directory)
246
+ written: list[str] = []
247
+ with zipfile.ZipFile(archive) as zf:
248
+ target.mkdir(parents=True, exist_ok=True)
249
+ # Only these fixed names are written, wherever the archive points;
250
+ # of two members extracted as one file, the later is what is left.
251
+ members: dict[str, zipfile.ZipInfo] = {}
252
+ for info in zf.infolist():
253
+ name = _member(info)
254
+ if name is not None:
255
+ members[name] = info
256
+ for name in sorted(members.keys() - set(PLAN_FILES)):
257
+ (target / name).write_bytes(zf.read(members[name]))
258
+ written.append(name)
259
+ ran, truthy = (None, False)
260
+ if "ran.json" in members:
261
+ ran, truthy = _archived_plan(zf, members["ran.json"])
262
+ name, plan = ("ran.json", ran) if truthy else ("plan.json", None)
263
+ if plan is None and "plan.json" in members:
264
+ plan = _archived_plan(zf, members["plan.json"])[0]
265
+ if plan is not None:
266
+ (target / name).write_text(
267
+ json.dumps({"cut": True, **(_plan_read(plan) or {})}), "utf-8"
268
+ )
269
+ written.append(name)
270
+ return written
271
+
272
+
171
273
  def load(directory: str | Path) -> list[Artifact]:
172
274
  root = Path(directory)
173
275
  if not root.is_dir():
@@ -614,3 +716,9 @@ def to_markdown(report: Report) -> str:
614
716
  )
615
717
  lines.append("")
616
718
  return "\n".join(lines)
719
+
720
+
721
+ if __name__ == "__main__":
722
+ if len(sys.argv) != 3:
723
+ sys.exit("usage: python -m diffcone.ci_report ARCHIVE DIR")
724
+ extract(sys.argv[1], sys.argv[2])
@@ -12,6 +12,8 @@ from diffcone.model import (
12
12
  SourceIndex,
13
13
  Symbol,
14
14
  SymbolKind,
15
+ is_log_callbacks,
16
+ log_callback_sites,
15
17
  )
16
18
 
17
19
 
@@ -107,7 +109,9 @@ def _dependency_signatures(index: SourceIndex) -> dict[str, frozenset[tuple[str,
107
109
  symbol does as much as a new edge does."""
108
110
  grouped: dict[str, set[tuple[str, str, str]]] = defaultdict(set)
109
111
  for e in index.edges:
110
- if e.kind != EdgeKind.DEFINED_IN:
112
+ # The edges of a pseudo-node of logging callbacks are its variables'
113
+ # (_with_log_sites).
114
+ if e.kind != EdgeKind.DEFINED_IN and not is_log_callbacks(e.source):
111
115
  grouped[e.source].add((e.kind, e.target, e.detail))
112
116
  for u in index.unresolved:
113
117
  grouped[u.symbol].add((UNRESOLVED_SIG, f"{u.kind}:{u.name}", ""))
@@ -116,6 +120,24 @@ def _dependency_signatures(index: SourceIndex) -> dict[str, frozenset[tuple[str,
116
120
  return {source: frozenset(sig) for source, sig in grouped.items()}
117
121
 
118
122
 
123
+ def _with_log_sites(
124
+ symbol_id: str, signature: frozenset[tuple[str, str, str]], sites: dict[str, set[str]]
125
+ ) -> frozenset[tuple[str, str, str]]:
126
+ """``signature`` with an edge to the pseudo-node of a set of logging
127
+ callbacks (model.LOG_CALLBACKS) as the edges to the log sites it stands
128
+ for: what the symbol depended on before the pseudo-node joined them. Two
129
+ revisions' signatures with the same pseudo-nodes are equal as they are
130
+ (a pseudo-node is named by the sites it joins); only a symbol whose
131
+ signature differs needs them."""
132
+ hubs = [d for d in signature if is_log_callbacks(d[1])]
133
+ if not hubs:
134
+ return signature
135
+ found = set(signature) - set(hubs)
136
+ for kind, hub, detail in hubs:
137
+ found.update((kind, site, detail) for site in sites.get(hub, ()) if site != symbol_id)
138
+ return frozenset(found)
139
+
140
+
119
141
  def _is_subsequence(before: tuple[str, ...], after: tuple[str, ...]) -> bool:
120
142
  """Whether ``after`` is ``before`` with entries inserted: every import
121
143
  kept its block and its order relative to the others."""
@@ -259,6 +281,8 @@ def classify(base: SourceIndex, head: SourceIndex) -> list[SymbolChange]:
259
281
  changes: list[SymbolChange] = []
260
282
  base_deps = _dependency_signatures(base)
261
283
  head_deps = _dependency_signatures(head)
284
+ base_sites = log_callback_sites(base.edges)
285
+ head_sites = log_callback_sites(head.edges)
262
286
  base_closures = _import_closures(base)
263
287
  base_modules = {s.id for s in base.symbols.values() if s.kind == SymbolKind.MODULE}
264
288
  empty: frozenset[tuple[str, str, str]] = frozenset()
@@ -308,6 +332,9 @@ def classify(base: SourceIndex, head: SourceIndex) -> list[SymbolChange]:
308
332
  )
309
333
  before = base_deps.get(symbol_id, empty)
310
334
  after = head_deps.get(symbol_id, empty)
335
+ if before != after and (base_sites or head_sites):
336
+ before = _with_log_sites(symbol_id, before, base_sites)
337
+ after = _with_log_sites(symbol_id, after, head_sites)
311
338
  if ChangeKind.BODY_CHANGED in kinds or ChangeKind.DEFINITION_CHANGED in kinds:
312
339
  # The edit itself explains new unresolved and external references;
313
340
  # they matter on their own only when a binding moved under them.
@@ -617,6 +617,20 @@ def _collect(args: argparse.Namespace) -> int:
617
617
  ),
618
618
  file=sys.stderr,
619
619
  )
620
+ if ev.flag_causes:
621
+ # What flagged the most tests: a process left running flags every
622
+ # test after it, and the flag selects the test on every change.
623
+ top = list(ev.flag_causes.items())[:FLAG_CAUSES_SHOWN]
624
+ print(
625
+ "diffcone: what flagged them: "
626
+ + "; ".join(f"{n} test(s): {cause}" for cause, n in top)
627
+ + (
628
+ f"; and {len(ev.flag_causes) - len(top)} other cause(s)"
629
+ if len(ev.flag_causes) > len(top)
630
+ else ""
631
+ ),
632
+ file=sys.stderr,
633
+ )
620
634
  unrecorded = sorted(ev.collected - set(ev.tests)) if ev.collected is not None else []
621
635
  if unrecorded:
622
636
  print(
@@ -748,6 +762,8 @@ CACHE_OPTIONS = {
748
762
  "--stepwise-skip": "stepwise",
749
763
  }
750
764
  NAME_OPTIONS = ("-k", "-m", "--deselect")
765
+ # How many causes of the subprocess flag ``collect`` names.
766
+ FLAG_CAUSES_SHOWN = 3
751
767
 
752
768
 
753
769
  def _deselecting_options(plan) -> list[str]:
@@ -149,6 +149,7 @@ import sys
149
149
  import threading
150
150
  import types
151
151
  import zlib
152
+ from collections.abc import Callable
152
153
  from pathlib import Path
153
154
  from typing import Any
154
155
  from urllib.parse import urlparse
@@ -368,6 +369,13 @@ import_spawns: list[tuple[tuple, str]] = []
368
369
  # The modules whose import ran what no record shows ("" for none).
369
370
  import_flagged: set[str] = set()
370
371
  flags_raised = 0 # how many times _flag ran: did a call flag its window?
372
+ # Why a window was flagged, for ``diffcone collect`` to name what flagged
373
+ # the most tests: a window's ``causes`` index ``cause_table``. And what
374
+ # started each process in ``unfollowed``.
375
+ cause_table: list[str] = []
376
+ cause_ids: dict[str, int] = {}
377
+ unfollowed_why: dict[int, str] = {}
378
+ _CAUSES = 500 # distinct causes kept; any more share one
371
379
  caches: list = []
372
380
  recording = False
373
381
  # The checkout files of the modules imported before the recorder started.
@@ -380,7 +388,7 @@ _real = child.RealPaths()
380
388
  # process (an xdist worker) set up is credited too. ``spawns``: (spawner,
381
389
  # pid, start, argv, inert) of the processes it started, or that were still
382
390
  # running when it opened, through ``subprocess.Popen``.
383
- _SETS = ("codes", "paths", "dirs", "fixtures", "spawns")
391
+ _SETS = ("codes", "paths", "dirs", "fixtures", "spawns", "causes")
384
392
 
385
393
 
386
394
  def _window() -> dict:
@@ -463,16 +471,75 @@ def _code_index(code, rel: str) -> int:
463
471
  return i
464
472
 
465
473
 
466
- def _flag(flag: int = FLAG_SUBPROCESS) -> None:
474
+ def _flag(flag: int = FLAG_SUBPROCESS, cause: str | Callable[[], str] = "") -> None:
467
475
  """Something ran that no record shows: in the open windows, or outside
468
476
  every window in the phase it belongs to (the module being imported, or
469
- none: a hook or collection)."""
477
+ none: a hook or collection). ``cause`` says what, for the summary (a
478
+ callable is called for it). The flag is raised first: describing the
479
+ cause is a diagnostic, and nothing that goes wrong there costs the flag
480
+ or the store."""
470
481
  global flags_raised
471
482
  flags_raised += 1
472
- for w in _windows():
483
+ windows = _windows()
484
+ for w in windows:
473
485
  w["flags"] |= flag
474
486
  if not active:
475
487
  import_flagged.add(importing[-1] if importing else "")
488
+ if flag != FLAG_SUBPROCESS:
489
+ return
490
+ try:
491
+ cause_id = _cause(cause if isinstance(cause, str) else cause())
492
+ except Exception: # a diagnostic only
493
+ cause_id = _cause("a cause that could not be described")
494
+ for w in windows:
495
+ w["causes"].add(cause_id)
496
+
497
+
498
+ def _summary(args) -> str:
499
+ """The command an audit event's arguments name, short."""
500
+ for arg in args or ():
501
+ if isinstance(arg, (str, bytes, os.PathLike)):
502
+ return os.fsdecode(arg)[:120]
503
+ if isinstance(arg, (list, tuple)) and arg:
504
+ return " ".join(os.fsdecode(a) if isinstance(a, (str, bytes)) else str(a) for a in arg)[
505
+ :120
506
+ ]
507
+ return ""
508
+
509
+
510
+ def _cause(cause: str) -> int:
511
+ """The id of ``cause``, with the checkout code calling in, in
512
+ ``cause_table``."""
513
+ return _cause_text(f"{cause or 'something no record shows'} ({_site()})")
514
+
515
+
516
+ def _cause_text(text: str) -> int:
517
+ text = text[:300]
518
+ i = cause_ids.get(text)
519
+ if i is None:
520
+ if len(cause_table) >= _CAUSES:
521
+ text = "other causes"
522
+ i = cause_ids.get(text)
523
+ if i is None:
524
+ i = cause_ids[text] = len(cause_table)
525
+ cause_table.append(text)
526
+ return i
527
+
528
+
529
+ def _site() -> str:
530
+ """Where the checkout's innermost code calling in is, ``path:line``."""
531
+ try:
532
+ frame = sys._getframe(1)
533
+ while frame is not None:
534
+ name = frame.f_code.co_filename
535
+ if os.path.isabs(name) and name != __file__:
536
+ rel = _relative(name)
537
+ if rel is not None:
538
+ return f"{rel}:{frame.f_lineno}"
539
+ frame = frame.f_back
540
+ except Exception: # a diagnostic only
541
+ pass
542
+ return "no checkout code calling"
476
543
 
477
544
 
478
545
  def _error(where: str, exc: BaseException) -> None:
@@ -724,7 +791,7 @@ def _touch(path, listing: bool = False, own_source: bool = False, scanned: bool
724
791
  path = child.fd_path(path)
725
792
  if path is None:
726
793
  if listing:
727
- _flag()
794
+ _flag(cause="a listing of a descriptor nothing resolves")
728
795
  return
729
796
  try:
730
797
  path = os.fsdecode(os.fspath(path))
@@ -817,7 +884,7 @@ def _audit(event, args):
817
884
  _inert_pending = event == "subprocess.Popen"
818
885
  else:
819
886
  _inert_pending = False
820
- _flag()
887
+ _flag(cause=lambda: f"{event} {_summary(args)}".rstrip())
821
888
  elif event == "exec":
822
889
  caller = sys._getframe().f_back
823
890
  # An annotation evaluated from text: credited with what it reads
@@ -995,6 +1062,9 @@ def _credit_live_children(window: dict) -> None:
995
1062
  running = [pid for pid in unfollowed if _running(pid)]
996
1063
  if running:
997
1064
  window["flags"] |= FLAG_SUBPROCESS
1065
+ for pid in running:
1066
+ why = unfollowed_why.get(pid, "a process no record follows")
1067
+ window["causes"].add(_cause_text(f"still running: {why}"))
998
1068
  unfollowed[:] = running
999
1069
  if not live or OUT is None:
1000
1070
  return
@@ -1082,6 +1152,8 @@ def _follow_pid(owner, name: str, pid_of, flagged: bool = False) -> None:
1082
1152
  if isinstance(pid, int) and pid > 0:
1083
1153
  known.add(pid)
1084
1154
  unfollowed.append(pid)
1155
+ owner_name = getattr(owner, "__name__", type(owner).__name__)
1156
+ unfollowed_why[pid] = f"{owner_name}.{name} ({_site()})"
1085
1157
  except Exception as exc:
1086
1158
  _error(f"follow {name}", exc)
1087
1159
  return result
@@ -1097,7 +1169,7 @@ def _flag_calls(module, name: str) -> None:
1097
1169
 
1098
1170
  @functools.wraps(original)
1099
1171
  def flagged(*args, **kwargs):
1100
- _flag()
1172
+ _flag(cause=f"{module.__name__}.{name}")
1101
1173
  result = original(*args, **kwargs)
1102
1174
  if isinstance(result, int):
1103
1175
  # A forkserver or resource tracker: flagged here, and the
@@ -1136,7 +1208,8 @@ def _unaccounted_children() -> None:
1136
1208
  continue
1137
1209
  known.add(pid)
1138
1210
  unfollowed.append(pid)
1139
- _flag()
1211
+ unfollowed_why[pid] = "a Python process started where no wrapper sees"
1212
+ _flag(cause=unfollowed_why[pid])
1140
1213
 
1141
1214
 
1142
1215
  def _is_source(path) -> bool:
@@ -1160,7 +1233,7 @@ def _wrap_stat(original):
1160
1233
  if dir_fd is not None:
1161
1234
  joined = child.joined(path, dir_fd)
1162
1235
  if joined is None:
1163
- _flag()
1236
+ _flag(cause="a path relative to a descriptor nothing resolves")
1164
1237
  else:
1165
1238
  _touch(joined, own_source=_is_source(joined))
1166
1239
  else:
@@ -1704,6 +1777,8 @@ def _finish():
1704
1777
  # import running -> the checkout files collected.
1705
1778
  "collect_by": {str(k): sorted(v) for k, v in collect_by.items()},
1706
1779
  "hook_phase": sorted(hook_codes),
1780
+ # What the windows' ``causes`` name (a diagnostic only).
1781
+ "causes": cause_table,
1707
1782
  "preloaded": preloaded,
1708
1783
  "outside_modules": sorted(outside),
1709
1784
  # What each shared fixture ran here: a fixture computed once for