diffcone 0.1.0__tar.gz → 0.2.0__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 (39) hide show
  1. {diffcone-0.1.0 → diffcone-0.2.0}/PKG-INFO +1 -1
  2. {diffcone-0.1.0 → diffcone-0.2.0}/pyproject.toml +1 -1
  3. {diffcone-0.1.0 → diffcone-0.2.0}/pyproject.toml.orig +1 -1
  4. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/collect.py +232 -18
  5. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/discovery/pytest_static.py +218 -4
  6. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/evidence_plan.py +7 -3
  7. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/execution.py +39 -9
  8. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/indexer/core.py +49 -3
  9. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/indexer/facts.py +14 -0
  10. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/indexer/literals.py +87 -5
  11. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/indexer/references.py +54 -1
  12. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/indexer/scopes.py +4 -3
  13. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/testing.py +2 -1
  14. {diffcone-0.1.0 → diffcone-0.2.0}/LICENSE +0 -0
  15. {diffcone-0.1.0 → diffcone-0.2.0}/README.md +0 -0
  16. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/__init__.py +0 -0
  17. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/cache.py +0 -0
  18. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/check.py +0 -0
  19. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/classify.py +0 -0
  20. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/cli.py +0 -0
  21. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/cython.py +0 -0
  22. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/declarations.py +0 -0
  23. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/discovery/__init__.py +0 -0
  24. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/discovery/asv_static.py +0 -0
  25. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/discovery/common.py +0 -0
  26. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/evidence.py +0 -0
  27. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/indexer/__init__.py +0 -0
  28. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/indexer/definitions.py +0 -0
  29. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/indexer/dynamics.py +0 -0
  30. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/indexer/resolver.py +0 -0
  31. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/indexer/state.py +0 -0
  32. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/indexer/symbols.py +0 -0
  33. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/indexer/syntax.py +0 -0
  34. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/manifest.py +0 -0
  35. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/model.py +0 -0
  36. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/planner.py +0 -0
  37. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/report.py +0 -0
  38. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/selection.py +0 -0
  39. {diffcone-0.1.0 → diffcone-0.2.0}/src/diffcone/snapshot.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: diffcone
3
- Version: 0.1.0
3
+ Version: 0.2.0
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.1.0"
3
+ version = "0.2.0"
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.1.0"
3
+ version = "0.2.0"
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"
@@ -25,8 +25,10 @@ What it records, per test (parameter cases folded into their function, as
25
25
  hooks, ``sqlite3.connect`` and ``ctypes.dlopen`` included, and wrappers
26
26
  of ``os.stat``/``os.lstat``/``os.access``, which never warn, so the extra
27
27
  frame cannot move a warning's ``stacklevel``), with ``/`` separators;
28
- * whether it started a subprocess or a subinterpreter, or left a thread
29
- running (code no record names runs there).
28
+ * whether it started a subprocess (other than a ``python -c`` probe that
29
+ can run no project code) or a subinterpreter: code no record names runs
30
+ there. The project code other threads are in the middle of when a window
31
+ opens is credited to it, as those threads run beside its test.
30
32
 
31
33
  Outside every test window it records the code and paths of imports,
32
34
  collection and hooks; for each code object run by an import, the innermost
@@ -65,6 +67,7 @@ zlib-compressed JSON records, one per run of consecutive items of a test).
65
67
 
66
68
  from __future__ import annotations
67
69
 
70
+ import ast
68
71
  import functools
69
72
  import gc
70
73
  import hashlib
@@ -73,6 +76,7 @@ import json
73
76
  import os
74
77
  import platform
75
78
  import re
79
+ import shlex
76
80
  import struct
77
81
  import sys
78
82
  import threading
@@ -206,7 +210,14 @@ OUT = os.environ.get("DIFFCONE_COLLECT_OUT")
206
210
  _root = os.environ.get("DIFFCONE_COLLECT_ROOT") or os.getcwd()
207
211
  # Both spellings: a code object's file name is the path it was imported by
208
212
  # (``/tmp/x`` on macOS is ``/private/tmp/x``).
209
- ROOTS = tuple(sorted({os.path.abspath(_root) + os.sep, os.path.realpath(_root) + os.sep}))
213
+ ROOTS = tuple(
214
+ sorted(
215
+ {
216
+ os.path.normcase(r) if os.name == "nt" else r
217
+ for r in (os.path.abspath(_root) + os.sep, os.path.realpath(_root) + os.sep)
218
+ }
219
+ )
220
+ )
210
221
  PACKAGES = frozenset(p for p in os.environ.get("DIFFCONE_COLLECT_PACKAGES", "").split(",") if p)
211
222
  IGNORED_DIRS = (".git" + os.sep, ".diffcone" + os.sep)
212
223
  INSTALLED = (os.sep + "site-packages" + os.sep, os.sep + "dist-packages" + os.sep)
@@ -255,10 +266,25 @@ def _relative(path: str) -> str | None:
255
266
  (a common conftest idiom) has ``..`` in its code objects' file names."""
256
267
  if os.path.isabs(path):
257
268
  path = os.path.normpath(path)
269
+ rel = _under_root(path)
270
+ if rel is None and os.name == "nt" and "~" in path and os.path.isabs(path):
271
+ # ``C:\\Users\\RUNNER~1`` (an 8.3 short name) and its long name are one
272
+ # directory.
273
+ try:
274
+ rel = _under_root(os.path.realpath(path))
275
+ except (OSError, ValueError):
276
+ rel = None
277
+ return rel
278
+
279
+
280
+ def _under_root(path: str) -> str | None:
281
+ # Windows compares case-folded (``normcase`` keeps the length), and the
282
+ # path keeps its own case.
283
+ folded = os.path.normcase(path) if os.name == "nt" else path
258
284
  for root in ROOTS:
259
- if path + os.sep == root:
285
+ if folded + os.sep == root:
260
286
  return ""
261
- if path.startswith(root):
287
+ if folded.startswith(root):
262
288
  rel = path[len(root) :]
263
289
  if rel.startswith(IGNORED_DIRS) or any(p in rel for p in INSTALLED):
264
290
  return None
@@ -403,7 +429,13 @@ def _actor() -> str:
403
429
  return "other"
404
430
 
405
431
 
406
- def _touch(path, listing: bool = False) -> None:
432
+ def _touch(path, listing: bool = False, own_source: bool = False) -> None:
433
+ """``own_source``: a stat of a source file. While a module is being
434
+ imported, its stat of its *own* file (``Path(__file__).resolve()``)
435
+ sees only that the file exists, recorded as a name seen like a listing;
436
+ every other stat of a source file (``os.path.getsize``, ``linecache``
437
+ checking ``inspect.getsource``'s cached copy) can depend on what the
438
+ file holds and counts as reading it."""
407
439
  if isinstance(path, int) or path is None:
408
440
  return
409
441
  try:
@@ -416,6 +448,8 @@ def _touch(path, listing: bool = False) -> None:
416
448
  actor = _actor()
417
449
  if actor == "import":
418
450
  return
451
+ if own_source and not active and importing and importing[-1] == rel:
452
+ listing = True
419
453
  if active:
420
454
  # Inside a test anything counts: a library or plugin reading a file
421
455
  # for the test (a data-directory fixture copying files) included.
@@ -429,6 +463,9 @@ def _touch(path, listing: bool = False) -> None:
429
463
  seen.setdefault(rel, set()).add(importing[-1] if importing else "")
430
464
 
431
465
 
466
+ _inert_pending = False
467
+
468
+
432
469
  def _audit(event, args):
433
470
  try:
434
471
  if event == "open":
@@ -440,12 +477,179 @@ def _audit(event, args):
440
477
  if args and isinstance(args[0], (str, bytes, os.PathLike)):
441
478
  _touch(args[0])
442
479
  elif event in SUBPROCESS_EVENTS:
443
- for w in _windows():
444
- w["flags"] |= FLAG_SUBPROCESS
480
+ global _inert_pending
481
+ if event == "_winapi.CreateProcess" and _inert_pending:
482
+ # The process an inert ``subprocess.Popen`` just judged
483
+ # (Windows raises both events for one process).
484
+ _inert_pending = False
485
+ elif _inert_probe(event, args):
486
+ _inert_pending = event == "subprocess.Popen"
487
+ else:
488
+ _inert_pending = False
489
+ for w in _windows():
490
+ w["flags"] |= FLAG_SUBPROCESS
445
491
  except Exception as exc:
446
492
  _error(f"audit {event}", exc)
447
493
 
448
494
 
495
+ # Single-letter interpreter options that take no value and load no code.
496
+ _PLAIN_OPTIONS = frozenset({"-I", "-E", "-S", "-s", "-B", "-u", "-O", "-OO", "-q", "-P"})
497
+ # Other programs' queries that run no Python of the project: (program, the
498
+ # arguments that start the command line). ``uv run``, ``git`` (hooks) and
499
+ # console scripts can run project code and are not here.
500
+ _INERT_QUERIES = (
501
+ ("uv", ("python", "list")),
502
+ ("uv", ("python", "find")),
503
+ ("uv", ("python", "dir")),
504
+ ("uv", ("--version",)),
505
+ ("uv", ("-V",)),
506
+ )
507
+ # A ``-c`` snippet is inert only when everything it imports is built into
508
+ # the interpreter (nothing on ``sys.path``, the working directory or
509
+ # ``PYTHONPATH`` can stand in for it), and it names nothing that loads or
510
+ # runs code by other means.
511
+ _LOADING_NAMES = frozenset(
512
+ {
513
+ "exec",
514
+ "eval",
515
+ "compile",
516
+ "open",
517
+ "__import__",
518
+ "__builtins__",
519
+ "builtins",
520
+ "__loader__",
521
+ "__spec__",
522
+ "breakpoint",
523
+ "_imp",
524
+ "execfile",
525
+ "system",
526
+ "popen",
527
+ "spawnl",
528
+ "spawnv",
529
+ "execv",
530
+ "execl",
531
+ "fork",
532
+ "startfile",
533
+ "modules",
534
+ "path",
535
+ "meta_path",
536
+ "path_hooks",
537
+ "setprofile",
538
+ "settrace",
539
+ "addaudithook",
540
+ }
541
+ )
542
+ # Environment variables that make an interpreter run or find other code.
543
+ _LOADING_ENV = ("PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP", "PYTHONUSERBASE", "PYTHONSAFEPATH")
544
+ _INTERPRETER = re.compile(r"python[0-9.]*(\.exe)?", re.IGNORECASE)
545
+
546
+
547
+ def _inert_snippet(code: str) -> bool:
548
+ try:
549
+ tree = ast.parse(code)
550
+ except (SyntaxError, ValueError):
551
+ return False
552
+ for node in ast.walk(tree):
553
+ if isinstance(node, ast.Import):
554
+ modules = [a.name for a in node.names]
555
+ elif isinstance(node, ast.ImportFrom):
556
+ modules = [node.module or ""] if not node.level else [""]
557
+ else:
558
+ modules = []
559
+ if any(m.split(".")[0] not in sys.builtin_module_names for m in modules):
560
+ return False
561
+ if isinstance(node, ast.Name) and node.id in _LOADING_NAMES:
562
+ return False
563
+ if isinstance(node, ast.Attribute) and node.attr in _LOADING_NAMES:
564
+ return False
565
+ return True
566
+
567
+
568
+ def _inert_probe(event: str, args: tuple) -> bool:
569
+ """Whether a subprocess cannot run project code: a Python interpreter
570
+ (by name, ``python3.13``, ``python.exe``) running nothing but a ``-c``
571
+ snippet that imports only built-in modules and names nothing that loads
572
+ code, with no environment pointing it at other code (``python -c
573
+ "import sys; print(sys.version_info)"``, how tools probe an interpreter's
574
+ version); or one of ``_INERT_QUERIES`` (``uv python list``). Anything
575
+ else (``-m``, a script, another program, ``os.system``) may run project
576
+ code where this process cannot see it."""
577
+ executable = env = None
578
+ if event == "subprocess.Popen":
579
+ executable, argv = args[0], args[1] if len(args) > 1 else None
580
+ env = args[3] if len(args) > 3 else None
581
+ elif event in ("os.posix_spawn", "os.exec"):
582
+ argv = args[1] if len(args) > 1 else None
583
+ env = args[2] if len(args) > 2 else None
584
+ else:
585
+ return False
586
+ if isinstance(argv, str) and os.name == "nt":
587
+ # Windows raises the event with the command line ``list2cmdline``
588
+ # built. An escaped quote is beyond this simple split: not inert.
589
+ if '\\"' in argv:
590
+ return False
591
+ argv = [
592
+ a[1:-1] if len(a) > 1 and a[0] == a[-1] == '"' else a
593
+ for a in shlex.split(argv, posix=False)
594
+ ]
595
+ if isinstance(argv, (str, bytes)) or argv is None:
596
+ return False
597
+ try:
598
+ argv = [os.fsdecode(a) for a in argv]
599
+ except TypeError:
600
+ return False
601
+ if not argv:
602
+ return False
603
+ program = argv[0]
604
+ name = os.path.basename(program)
605
+ try:
606
+ runs = os.path.basename(os.fsdecode(executable)) if executable is not None else name
607
+ except TypeError:
608
+ return False
609
+ if runs == name and any(
610
+ name == tool and tuple(argv[1 : 1 + len(start)]) == start for tool, start in _INERT_QUERIES
611
+ ):
612
+ return True
613
+ if not (_INTERPRETER.fullmatch(name) or program == sys.executable):
614
+ return False
615
+ if not _INTERPRETER.fullmatch(runs) and executable != sys.executable:
616
+ return False
617
+ if env is not None:
618
+ try:
619
+ if any(k in env for k in _LOADING_ENV):
620
+ return False
621
+ except TypeError:
622
+ return False
623
+ i = 1
624
+ while i < len(argv) and argv[i] in _PLAIN_OPTIONS:
625
+ i += 1
626
+ # ``-c CODE`` and nothing after it (an argument could be a path the
627
+ # snippet puts on ``sys.path``).
628
+ if len(argv) != i + 2 or argv[i] != "-c":
629
+ return False
630
+ return _inert_snippet(argv[i + 1])
631
+
632
+
633
+ def _credit_running_threads(window: dict) -> None:
634
+ """Credit ``window`` with the project code every other thread is in the
635
+ middle of. A long-lived thread looping in one frame raises no event while
636
+ a later window is open, yet it runs beside that window's test."""
637
+ me = threading.get_ident()
638
+ for ident, frame in sys._current_frames().items():
639
+ if ident == me:
640
+ continue
641
+ while frame is not None:
642
+ code = frame.f_code
643
+ rel = _code_path(code.co_filename)
644
+ if rel is not None:
645
+ i = codes.get(code)
646
+ if i is None:
647
+ i = codes[code] = len(table)
648
+ table.append([rel, code.co_firstlineno, code.co_qualname])
649
+ window["codes"].add(i)
650
+ frame = frame.f_back
651
+
652
+
449
653
  def _flag_multiprocessing_spawns() -> None:
450
654
  """``multiprocessing``'s spawn and forkserver start methods launch their
451
655
  children through ``_posixsubprocess.fork_exec``, which raises no audit
@@ -474,12 +678,19 @@ def _flag_calls(module, name: str) -> None:
474
678
  setattr(module, name, flagged)
475
679
 
476
680
 
681
+ def _is_source(path) -> bool:
682
+ try:
683
+ return os.fsdecode(os.fspath(path)).endswith(".py")
684
+ except TypeError:
685
+ return False
686
+
687
+
477
688
  def _wrap_stat(original):
478
689
  @functools.wraps(original)
479
690
  def stat(path, *args, **kwargs):
480
691
  if recording:
481
692
  try:
482
- _touch(path)
693
+ _touch(path, own_source=_is_source(path))
483
694
  except Exception as exc:
484
695
  _error("stat", exc)
485
696
  return original(path, *args, **kwargs)
@@ -605,6 +816,10 @@ def _start() -> None:
605
816
  os.stat = _wrap_stat(os.stat)
606
817
  os.lstat = _wrap_stat(os.lstat)
607
818
  os.access = _wrap_stat(os.access)
819
+ if os.name == "nt":
820
+ # Python 3.12+ on Windows answers these without os.stat.
821
+ for name in ("exists", "lexists", "isfile", "isdir", "islink"):
822
+ setattr(os.path, name, _wrap_stat(getattr(os.path, name)))
608
823
  # functools.cache goes through it too; a deliberate patch of the stdlib.
609
824
  functools.lru_cache = _tracking_lru_cache # ty: ignore[invalid-assignment]
610
825
  _flag_multiprocessing_spawns()
@@ -684,6 +899,10 @@ def pytest_fixture_setup(fixturedef, request):
684
899
  key = (fixturedef.baseid, fixturedef.argname, fixturedef.scope)
685
900
  w = fixture_windows.setdefault(key, _window())
686
901
  active.append(w)
902
+ try:
903
+ _credit_running_threads(w)
904
+ except Exception as exc:
905
+ _error("threads", exc)
687
906
  # Code this test already ran is disabled; re-arm so the fixture's own
688
907
  # window sees everything its setup runs.
689
908
  mon.restart_events()
@@ -730,21 +949,16 @@ def pytest_runtest_protocol(item, nextitem):
730
949
  mine = _window()
731
950
  active.append(mine)
732
951
  importing.clear() # no import is running when a test starts
733
- threads = set(threading.enumerate())
952
+ try:
953
+ _credit_running_threads(mine)
954
+ except Exception as exc:
955
+ _error("threads", exc)
734
956
  mon.restart_events()
735
957
  try:
736
958
  return (yield)
737
959
  finally:
738
960
  _drop(mine)
739
961
  mon.restart_events()
740
- try:
741
- # A thread the test started that is still running runs code no
742
- # record names (between tests, or credited to later ones): the
743
- # test is flagged like one that started a subprocess.
744
- if any(t.is_alive() and t not in threads for t in threading.enumerate()):
745
- mine["flags"] |= FLAG_SUBPROCESS
746
- except Exception as exc:
747
- _error("threads", exc)
748
962
  try:
749
963
  defs = list(used_fixtures.pop(item.nodeid, ()))
750
964
  info = getattr(item, "_fixtureinfo", None)