evalsuite-python 0.5.1__tar.gz → 0.5.2__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 (110) hide show
  1. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/CHANGELOG.md +19 -0
  2. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/PKG-INFO +2 -2
  3. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/README.md +1 -1
  4. evalsuite_python-0.5.2/src/evalsuite/_lazy.py +32 -0
  5. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/api.py +2 -1
  6. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/calibration.py +7 -1
  7. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/classification/metrics.py +4 -2
  8. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/clinical/report.py +7 -1
  9. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/llmsys/code.py +42 -33
  10. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/llmsys/safety.py +1 -1
  11. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/stats/effect.py +8 -2
  12. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/stats/hypothesis.py +8 -2
  13. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/stats/intervals.py +9 -2
  14. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/stats/paired.py +9 -2
  15. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/text/judge.py +8 -2
  16. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/text/structured.py +5 -1
  17. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/version.py +1 -1
  18. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/vision/segmentation.py +7 -1
  19. evalsuite_python-0.5.2/tests/llmsys/test_hardening.py +52 -0
  20. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/.gitignore +0 -0
  21. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/CONTRIBUTING.md +0 -0
  22. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/LICENSE +0 -0
  23. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/pyproject.toml +0 -0
  24. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/__init__.py +0 -0
  25. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/__main__.py +0 -0
  26. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/_bench_metrics.py +0 -0
  27. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/benchmarks.py +0 -0
  28. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/classification/__init__.py +0 -0
  29. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/classification/_common.py +0 -0
  30. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/cli/__init__.py +0 -0
  31. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/cli/main.py +0 -0
  32. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/clinical/__init__.py +0 -0
  33. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/clinical/metrics.py +0 -0
  34. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/core/__init__.py +0 -0
  35. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/core/context.py +0 -0
  36. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/core/exceptions.py +0 -0
  37. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/core/export.py +0 -0
  38. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/core/registry.py +0 -0
  39. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/core/result.py +0 -0
  40. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/core/types.py +0 -0
  41. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/core/validation.py +0 -0
  42. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/llmsys/__init__.py +0 -0
  43. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/llmsys/_common.py +0 -0
  44. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/llmsys/agents.py +0 -0
  45. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/llmsys/efficiency.py +0 -0
  46. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/llmsys/longcontext.py +0 -0
  47. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/llmsys/multilingual.py +0 -0
  48. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/llmsys/robustness.py +0 -0
  49. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/llmsys/uncertainty.py +0 -0
  50. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/plot.py +0 -0
  51. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/py.typed +0 -0
  52. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/regression/__init__.py +0 -0
  53. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/regression/metrics.py +0 -0
  54. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/reporting.py +0 -0
  55. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/stats/__init__.py +0 -0
  56. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/stats/_resolve.py +0 -0
  57. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/stats/compare.py +0 -0
  58. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/stats/results.py +0 -0
  59. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/text/__init__.py +0 -0
  60. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/text/_common.py +0 -0
  61. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/text/factuality.py +0 -0
  62. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/text/generation.py +0 -0
  63. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/text/qa.py +0 -0
  64. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/text/rag.py +0 -0
  65. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/text/reasoning.py +0 -0
  66. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/text/report.py +0 -0
  67. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/text/retrieval.py +0 -0
  68. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/text/semantic.py +0 -0
  69. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/text/spice.py +0 -0
  70. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/vision/__init__.py +0 -0
  71. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/src/evalsuite/vision/detection.py +0 -0
  72. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/__init__.py +0 -0
  73. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/classification/__init__.py +0 -0
  74. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/classification/test_against_sklearn.py +0 -0
  75. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/clinical/__init__.py +0 -0
  76. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/clinical/test_outputs.py +0 -0
  77. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/clinical/test_v020.py +0 -0
  78. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/conftest.py +0 -0
  79. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/integration/__init__.py +0 -0
  80. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/integration/test_qa.py +0 -0
  81. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/integration/test_readme_examples.py +0 -0
  82. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/integration/test_repo_hygiene.py +0 -0
  83. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/llmsys/__init__.py +0 -0
  84. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/llmsys/test_code_longcontext_efficiency.py +0 -0
  85. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/llmsys/test_edges.py +0 -0
  86. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/llmsys/test_safety_robustness.py +0 -0
  87. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/llmsys/test_uncertainty_agents_multilingual.py +0 -0
  88. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/output/__init__.py +0 -0
  89. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/output/test_benchmarks.py +0 -0
  90. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/output/test_cli.py +0 -0
  91. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/output/test_plot.py +0 -0
  92. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/output/test_reporting.py +0 -0
  93. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/regression/__init__.py +0 -0
  94. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/regression/test_against_sklearn.py +0 -0
  95. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/stats/__init__.py +0 -0
  96. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/stats/test_branches.py +0 -0
  97. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/stats/test_compare.py +0 -0
  98. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/stats/test_reference.py +0 -0
  99. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/text/__init__.py +0 -0
  100. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/text/test_against_references.py +0 -0
  101. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/text/test_text_edges.py +0 -0
  102. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/text/test_v040.py +0 -0
  103. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/unit/__init__.py +0 -0
  104. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/unit/test_core.py +0 -0
  105. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/unit/test_edges.py +0 -0
  106. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/vision/__init__.py +0 -0
  107. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/vision/test_detection.py +0 -0
  108. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/vision/test_edges.py +0 -0
  109. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/vision/test_outputs.py +0 -0
  110. {evalsuite_python-0.5.1 → evalsuite_python-0.5.2}/tests/vision/test_segmentation.py +0 -0
@@ -6,6 +6,25 @@ All notable changes to this project are documented here. The format follows
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.5.2] - 2026-11-07
10
+
11
+ Security and performance hardening. No API changes.
12
+
13
+ ### Security
14
+ - The built-in PII e-mail detector no longer backtracks quadratically: `detect_pii` / `pii_leakage_rate`
15
+ on 60 kB of adversarial text went from ~6 s to ~10 ms.
16
+ - `codebleu`, `code_complexity` and `syntax_validity_rate` handle source nested too deeply for CPython's
17
+ parser (MemoryError / RecursionError) instead of crashing: invalid for syntax validity, an
18
+ `InputValidationError` for complexity, no syntax match for CodeBLEU.
19
+ - Internal `assert` type checks replaced by explicit errors, so behaviour is the same under `python -O`.
20
+ - CI and release workflows pin every action to a commit SHA; Dependabot keeps them and the dependencies current.
21
+ - Documented that user-supplied regular expressions (`format_compliance`) run on a backtracking engine.
22
+
23
+ ### Performance
24
+ - `import evalsuite` no longer imports SciPy; it is loaded on first use (import time ~0.6 s → ~0.07 s).
25
+ - CodeBLEU syntax match uses interned subtree ids instead of serialised strings: linear in the size of the
26
+ program rather than quadratic.
27
+
9
28
  ## [0.5.1] - 2026-10-10
10
29
 
11
30
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: evalsuite-python
3
- Version: 0.5.1
3
+ Version: 0.5.2
4
4
  Summary: A unified Python framework for machine-learning, clinical, statistical, segmentation, object-detection, uncertainty, and model evaluation.
5
5
  Project-URL: Homepage, https://evalsuite-nine.vercel.app
6
6
  Project-URL: Documentation, https://evalsuite-nine.vercel.app/docs
@@ -83,7 +83,7 @@ Description-Content-Type: text/markdown
83
83
  EvalSuite brings classification, regression, clinical, statistical, segmentation and object-detection
84
84
  evaluation into one consistent, validated, documented framework.
85
85
 
86
- > **Status: stable (0.5.1).** Every item on the 0.1.0–0.5.0 roadmaps is implemented and verified, including SPICE.
86
+ > **Status: stable (0.5.2).** Every item on the 0.1.0–0.5.0 roadmaps is implemented and verified, including SPICE.
87
87
  > **LLM systems arrive in 0.5.0**: safety, robustness, calibration and uncertainty, agents and tool use,
88
88
  > multilingual, code generation, long context and summarization, and inference efficiency and cost.
89
89
 
@@ -10,7 +10,7 @@
10
10
  EvalSuite brings classification, regression, clinical, statistical, segmentation and object-detection
11
11
  evaluation into one consistent, validated, documented framework.
12
12
 
13
- > **Status: stable (0.5.1).** Every item on the 0.1.0–0.5.0 roadmaps is implemented and verified, including SPICE.
13
+ > **Status: stable (0.5.2).** Every item on the 0.1.0–0.5.0 roadmaps is implemented and verified, including SPICE.
14
14
  > **LLM systems arrive in 0.5.0**: safety, robustness, calibration and uncertainty, agents and tool use,
15
15
  > multilingual, code generation, long context and summarization, and inference efficiency and cost.
16
16
 
@@ -0,0 +1,32 @@
1
+ """Deferred imports for heavy optional-at-import-time dependencies (SciPy submodules).
2
+
3
+ ``import evalsuite`` should not pay for SciPy until a function that needs it runs.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import importlib
9
+ from types import ModuleType
10
+ from typing import Any
11
+
12
+
13
+ class LazyModule(ModuleType):
14
+ """Module proxy that imports the real module on first attribute access."""
15
+
16
+ def __init__(self, name: str) -> None:
17
+ super().__init__(name)
18
+ self.__dict__["_mod"] = None
19
+
20
+ def _load(self) -> ModuleType:
21
+ mod = self.__dict__["_mod"]
22
+ if mod is None:
23
+ mod = importlib.import_module(self.__name__)
24
+ self.__dict__["_mod"] = mod
25
+ return mod # type: ignore[no-any-return]
26
+
27
+ def __getattr__(self, attr: str) -> Any:
28
+ return getattr(self._load(), attr)
29
+
30
+
31
+ def lazy_module(name: str) -> Any:
32
+ return LazyModule(name)
@@ -63,7 +63,8 @@ def _classification_registry(
63
63
 
64
64
  def _hamming(ctx: ClassificationContext) -> MetricResult:
65
65
  if ctx.target_type == "multilabel":
66
- assert ctx.y_pred is not None # noqa: S101
66
+ if ctx.y_pred is None:
67
+ raise InputValidationError("y_pred is required for this metric.")
67
68
  wrong = (ctx.y_true != ctx.y_pred).mean(axis=1)
68
69
  else:
69
70
  wrong = (ctx.true_idx != ctx.pred_idx).astype(float)
@@ -14,7 +14,13 @@ from typing import TYPE_CHECKING, Any, Literal, Optional, cast
14
14
 
15
15
  import numpy as np
16
16
  from numpy.typing import NDArray
17
- from scipy import stats
17
+
18
+ if TYPE_CHECKING:
19
+ from scipy import stats
20
+ else:
21
+ from ._lazy import lazy_module
22
+
23
+ stats = lazy_module("scipy.stats")
18
24
 
19
25
  from .classification.metrics import (
20
26
  _binary_target,
@@ -109,7 +109,8 @@ def accuracy(y_true: ArrayLike, y_pred: ArrayLike, *, sample_weight: Optional[Ar
109
109
 
110
110
  def _accuracy(ctx: ClassificationContext) -> MetricResult:
111
111
  if ctx.target_type == "multilabel":
112
- assert ctx.y_pred is not None # noqa: S101 - ensured by context for label metrics
112
+ if ctx.y_pred is None:
113
+ raise InputValidationError("y_pred is required for this metric.")
113
114
  correct = (ctx.y_true == ctx.y_pred).all(axis=1)
114
115
  else:
115
116
  correct = ctx.true_idx == ctx.pred_idx
@@ -491,7 +492,8 @@ def hamming_loss(
491
492
  """Hamming loss."""
492
493
  ctx = _ctx(y_true, y_pred, sample_weight=sample_weight)
493
494
  if ctx.target_type == "multilabel":
494
- assert ctx.y_pred is not None # noqa: S101
495
+ if ctx.y_pred is None:
496
+ raise InputValidationError("y_pred is required for this metric.")
495
497
  wrong = (ctx.y_true != ctx.y_pred).mean(axis=1)
496
498
  else:
497
499
  wrong = (ctx.true_idx != ctx.pred_idx).astype(float)
@@ -10,7 +10,13 @@ from typing import TYPE_CHECKING, Any, Optional, cast
10
10
 
11
11
  import numpy as np
12
12
  from numpy.typing import NDArray
13
- from scipy import special
13
+
14
+ if TYPE_CHECKING:
15
+ from scipy import special
16
+ else:
17
+ from .._lazy import lazy_module
18
+
19
+ special = lazy_module("scipy.special")
14
20
 
15
21
  from ..core.exceptions import InputValidationError
16
22
  from ..core.export import PathLike, csv_text, html_document, html_table, save_as
@@ -40,6 +40,10 @@ __all__ = [
40
40
  ]
41
41
 
42
42
  _C = "code"
43
+
44
+ # Errors CPython raises for source it cannot parse: syntax errors, null bytes (ValueError), and input nested
45
+ # too deeply for the parser (MemoryError "parser stack overflowed") or for the compiler (RecursionError).
46
+ _PARSE_ERRORS = (SyntaxError, ValueError, MemoryError, RecursionError)
43
47
  _REF_HUMANEVAL = (
44
48
  "Chen M, Tworek J, Jun H, et al. Evaluating large language models trained on code. arXiv:2107.03374. 2021."
45
49
  )
@@ -141,7 +145,7 @@ def syntax_validity_rate(
141
145
  with warnings.catch_warnings():
142
146
  warnings.simplefilter("ignore", SyntaxWarning)
143
147
  compile(src, "<generated>", "exec", dont_inherit=True) # parses only; nothing runs
144
- except (SyntaxError, ValueError):
148
+ except _PARSE_ERRORS:
145
149
  return False
146
150
  return True
147
151
 
@@ -562,12 +566,16 @@ def code_complexity(code: Any) -> MetricResult:
562
566
  with warnings.catch_warnings():
563
567
  warnings.simplefilter("ignore", SyntaxWarning)
564
568
  tree = ast.parse(src)
569
+ visitor = _Complexity.run(tree)
570
+ v = _halstead_volume(tree)
565
571
  except SyntaxError as exc:
566
572
  raise InputValidationError(f"code[{i}] is not valid Python: {exc.msg} (line {exc.lineno}).") from exc
567
- visitor = _Complexity.run(tree)
573
+ except _PARSE_ERRORS as exc:
574
+ raise InputValidationError(
575
+ f"code[{i}] is too deeply nested to analyse ({type(exc).__name__})."
576
+ ) from exc
568
577
  blocks = visitor.blocks
569
578
  funcs += [c for _, c in blocks]
570
- v = _halstead_volume(tree)
571
579
  g = visitor.total
572
580
  lloc, sloc, comments = _raw(src)
573
581
  c_pct = comments / sloc * 100 if sloc else 0.0
@@ -720,38 +728,38 @@ def _parse(src: str) -> Optional[ast.AST]:
720
728
  with warnings.catch_warnings():
721
729
  warnings.simplefilter("ignore", SyntaxWarning)
722
730
  return ast.parse(_strip(src))
723
- except SyntaxError:
731
+ except _PARSE_ERRORS:
724
732
  return None
725
733
 
726
734
 
727
- def _sexp(node: ast.AST, memo: dict[int, str]) -> str:
728
- key = id(node)
729
- if key in memo:
730
- return memo[key]
731
- kids = [
732
- c
733
- for c in ast.iter_child_nodes(node)
734
- if not isinstance(c, (ast.expr_context, ast.operator, ast.unaryop, ast.boolop, ast.cmpop))
735
- ]
736
- tag = type(node).__name__
737
- if isinstance(node, (ast.BinOp, ast.UnaryOp, ast.BoolOp, ast.AugAssign)):
738
- tag += ":" + type(node.op).__name__
739
- s = f"({tag}{''.join(' ' + _sexp(c, memo) for c in kids)})"
740
- memo[key] = s
741
- return s
742
-
743
-
744
- def _subtrees(tree: ast.AST) -> list[str]:
745
- memo: dict[int, str] = {}
746
- out = []
747
- for node in ast.walk(tree):
748
- kids = [
749
- c
750
- for c in ast.iter_child_nodes(node)
751
- if not isinstance(c, (ast.expr_context, ast.operator, ast.unaryop, ast.boolop, ast.cmpop))
752
- ]
735
+ _SKIP_NODES = (ast.expr_context, ast.operator, ast.unaryop, ast.boolop, ast.cmpop)
736
+
737
+
738
+ def _kids(node: ast.AST) -> list[ast.AST]:
739
+ return [c for c in ast.iter_child_nodes(node) if not isinstance(c, _SKIP_NODES)]
740
+
741
+
742
+ def _subtrees(tree: ast.AST, table: dict[tuple[Any, ...], int]) -> list[int]:
743
+ """Every subtree with children (and the root), as ids that are equal exactly when the subtrees are
744
+ structurally equal. Built bottom-up without recursion: ``table`` interns (node type, child ids), so the
745
+ cost is linear in the tree size (comparing serialised subtrees would be quadratic)."""
746
+ ids: dict[int, int] = {}
747
+ out: list[int] = []
748
+ stack: list[tuple[ast.AST, bool]] = [(tree, False)]
749
+ while stack:
750
+ node, ready = stack.pop()
751
+ kids = _kids(node)
752
+ if not ready:
753
+ stack.append((node, True))
754
+ stack.extend((k, False) for k in kids)
755
+ continue
756
+ tag = type(node).__name__
757
+ if isinstance(node, (ast.BinOp, ast.UnaryOp, ast.BoolOp, ast.AugAssign)):
758
+ tag += ":" + type(node.op).__name__
759
+ sid = table.setdefault((tag, tuple(ids[id(k)] for k in kids)), len(table))
760
+ ids[id(node)] = sid
753
761
  if kids or node is tree:
754
- out.append(_sexp(node, memo))
762
+ out.append(sid)
755
763
  return out
756
764
 
757
765
 
@@ -878,15 +886,16 @@ def codebleu(
878
886
  ngram = _corpus_bleu(t_refs, t_hyps, None)
879
887
  weighted = _corpus_bleu(t_refs, t_hyps, kw)
880
888
  match = total = df_match = df_total = 0
889
+ table: dict[tuple[Any, ...], int] = {}
881
890
  for rs, p in zip(refs, preds):
882
891
  cand = _parse(p)
883
- cand_sub = set(_subtrees(cand)) if cand is not None else set()
892
+ cand_sub = set(_subtrees(cand, table)) if cand is not None else set()
884
893
  cand_flow = _normalize_flow(_dataflow(cand)) if cand is not None else []
885
894
  for r in rs:
886
895
  ref = _parse(r)
887
896
  if ref is None:
888
897
  continue
889
- ref_sub = _subtrees(ref)
898
+ ref_sub = _subtrees(ref, table)
890
899
  match += sum(s in cand_sub for s in ref_sub)
891
900
  total += len(ref_sub)
892
901
  ref_flow = _normalize_flow(_dataflow(ref))
@@ -362,7 +362,7 @@ def _luhn(digits: str) -> bool:
362
362
 
363
363
 
364
364
  PII_PATTERNS: dict[str, str] = {
365
- "email": r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}",
365
+ "email": r"(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}",
366
366
  "phone": r"(?<!\d[\s.-])(?<!\w)(?:\+?\d{1,3}[\s.-]?)?(?:\(\d{2,4}\)[\s.-]?)?\d{3,4}[\s.-]\d{3,4}"
367
367
  r"(?:[\s.-]\d{2,4})?(?![\s.-]?\d)(?!\w)",
368
368
  "credit_card": r"(?<!\d)\d(?:[ -]?\d){12,18}(?!\d)",
@@ -2,11 +2,17 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import Literal
5
+ from typing import TYPE_CHECKING, Literal
6
6
 
7
7
  import numpy as np
8
8
  from numpy.typing import NDArray
9
- from scipy import special
9
+
10
+ if TYPE_CHECKING:
11
+ from scipy import special
12
+ else:
13
+ from .._lazy import lazy_module
14
+
15
+ special = lazy_module("scipy.special")
10
16
 
11
17
  from ..core.exceptions import InputValidationError, StatisticalTestError
12
18
  from ..core.types import ArrayLike
@@ -8,11 +8,17 @@ implementations are the reference; EvalSuite adds input validation, effect sizes
8
8
  from __future__ import annotations
9
9
 
10
10
  import math
11
- from typing import Literal
11
+ from typing import TYPE_CHECKING, Literal
12
12
 
13
13
  import numpy as np
14
14
  from numpy.typing import NDArray
15
- from scipy import stats
15
+
16
+ if TYPE_CHECKING:
17
+ from scipy import stats
18
+ else:
19
+ from .._lazy import lazy_module
20
+
21
+ stats = lazy_module("scipy.stats")
16
22
 
17
23
  from ..core.exceptions import InputValidationError, StatisticalTestError
18
24
  from ..core.types import ArrayLike
@@ -3,11 +3,18 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import warnings
6
- from typing import Any, Literal, Optional
6
+ from typing import TYPE_CHECKING, Any, Literal, Optional
7
7
 
8
8
  import numpy as np
9
9
  from numpy.typing import NDArray
10
- from scipy import special, stats
10
+
11
+ if TYPE_CHECKING:
12
+ from scipy import special, stats
13
+ else:
14
+ from .._lazy import lazy_module
15
+
16
+ special = lazy_module("scipy.special")
17
+ stats = lazy_module("scipy.stats")
11
18
 
12
19
  from ..core.exceptions import EvalSuiteError, InputValidationError, StatisticalTestError
13
20
  from ..core.types import ArrayLike
@@ -2,10 +2,17 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import Any, Literal, Optional
5
+ from typing import TYPE_CHECKING, Any, Literal, Optional
6
6
 
7
7
  import numpy as np
8
- from scipy import special, stats
8
+
9
+ if TYPE_CHECKING:
10
+ from scipy import special, stats
11
+ else:
12
+ from .._lazy import lazy_module
13
+
14
+ special = lazy_module("scipy.special")
15
+ stats = lazy_module("scipy.stats")
9
16
 
10
17
  from ..core.exceptions import InputValidationError
11
18
  from ..core.types import ArrayLike
@@ -9,10 +9,16 @@ from __future__ import annotations
9
9
 
10
10
  import math
11
11
  from collections.abc import Sequence
12
- from typing import Any, Optional
12
+ from typing import TYPE_CHECKING, Any, Optional
13
13
 
14
14
  import numpy as np
15
- from scipy import stats
15
+
16
+ if TYPE_CHECKING:
17
+ from scipy import stats
18
+ else:
19
+ from .._lazy import lazy_module
20
+
21
+ stats = lazy_module("scipy.stats")
16
22
 
17
23
  from ..core.exceptions import InputValidationError
18
24
  from ..core.registry import register
@@ -712,7 +712,11 @@ def constraint_satisfaction_rate(checks: Any) -> MetricResult:
712
712
  def format_compliance(
713
713
  outputs: Any, pattern: str, *, flags: int = re.S, average: Optional[str] = "mean"
714
714
  ) -> MetricResult:
715
- """``re.fullmatch(pattern, output.strip())`` per output."""
715
+ """``re.fullmatch(pattern, output.strip())`` per output.
716
+
717
+ The pattern is compiled with Python's backtracking ``re`` engine; patterns with nested quantifiers such as
718
+ ``(a+)+$`` can take exponential time on some outputs, so only pass patterns you trust.
719
+ """
716
720
  outs = _outputs(outputs)
717
721
  try:
718
722
  rx = re.compile(pattern, flags)
@@ -1,3 +1,3 @@
1
1
  """Package version (single source of truth, read by the build backend)."""
2
2
 
3
- __version__ = "0.5.1"
3
+ __version__ = "0.5.2"
@@ -27,7 +27,13 @@ from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
27
27
 
28
28
  import numpy as np
29
29
  from numpy.typing import NDArray
30
- from scipy import ndimage
30
+
31
+ if TYPE_CHECKING:
32
+ from scipy import ndimage
33
+ else:
34
+ from .._lazy import lazy_module
35
+
36
+ ndimage = lazy_module("scipy.ndimage")
31
37
 
32
38
  from ..core.exceptions import InputValidationError, UndefinedMetricWarning
33
39
  from ..core.export import PathLike, csv_text, html_document, html_table, save_as
@@ -0,0 +1,52 @@
1
+ """Regression tests for adversarial inputs (parser exhaustion, regex backtracking) and lazy imports."""
2
+
3
+ import subprocess
4
+ import sys
5
+ import time
6
+
7
+ import pytest
8
+
9
+ import evalsuite as es
10
+ from evalsuite.core.exceptions import InputValidationError
11
+
12
+ DEEP = "x=" + "-" * 100_000 + "1"
13
+
14
+
15
+ def test_syntax_validity_survives_parser_stack_overflow():
16
+ assert float(es.syntax_validity_rate([DEEP, "x = 1"])) == 0.5
17
+
18
+
19
+ @pytest.mark.parametrize("src", [DEEP, "x=" + "-" * 900 + "1"])
20
+ def test_code_complexity_rejects_too_deep_code_cleanly(src):
21
+ with pytest.raises(InputValidationError, match=r"too deeply nested|not valid Python"):
22
+ es.code_complexity([src])
23
+
24
+
25
+ def test_codebleu_deep_input_does_not_crash():
26
+ r = es.codebleu([DEEP], [DEEP])
27
+ assert 0.0 <= float(r) <= 1.0
28
+
29
+
30
+ def test_codebleu_large_program_is_fast():
31
+ src = "\n".join(f"def f{i}(a, b):\n return [x * b for x in range(a + {i})]\n" for i in range(2000))
32
+ start = time.perf_counter()
33
+ es.codebleu([src], [src])
34
+ assert time.perf_counter() - start < 5
35
+
36
+
37
+ @pytest.mark.parametrize("text", ["1-" * 30_000, "a" * 30_000 + "@" + "b." * 10_000, "a." * 30_000, "a@" * 30_000])
38
+ def test_detect_pii_is_linear_on_adversarial_text(text):
39
+ start = time.perf_counter()
40
+ es.detect_pii(text)
41
+ assert time.perf_counter() - start < 1
42
+
43
+
44
+ def test_detect_pii_still_finds_emails():
45
+ found = es.detect_pii("write to a.b@x.org or c@d.co.uk")
46
+ assert found["email"] == ["a.b@x.org", "c@d.co.uk"]
47
+
48
+
49
+ def test_import_does_not_load_scipy():
50
+ code = "import sys, evalsuite; print('scipy' in sys.modules)"
51
+ out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, check=True) # noqa: S603
52
+ assert out.stdout.strip() == "False"