benchset 0.0.8__tar.gz → 0.0.9__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 (134) hide show
  1. {benchset-0.0.8 → benchset-0.0.9}/Cargo.lock +1 -1
  2. {benchset-0.0.8 → benchset-0.0.9}/Cargo.toml +1 -1
  3. {benchset-0.0.8 → benchset-0.0.9}/PKG-INFO +22 -4
  4. {benchset-0.0.8 → benchset-0.0.9}/Package.swift +2 -2
  5. {benchset-0.0.8 → benchset-0.0.9}/README.md +21 -3
  6. {benchset-0.0.8 → benchset-0.0.9}/benchset/_native.py +43 -19
  7. benchset-0.0.9/benchset/_signal_state.py +177 -0
  8. {benchset-0.0.8 → benchset-0.0.9}/benchset.egg-info/PKG-INFO +22 -4
  9. {benchset-0.0.8 → benchset-0.0.9}/benchset.egg-info/SOURCES.txt +2 -0
  10. {benchset-0.0.8 → benchset-0.0.9}/native/src/aggregate_protocol_tests.rs +3 -1
  11. {benchset-0.0.8 → benchset-0.0.9}/native/src/aggregation_ffi.rs +42 -39
  12. {benchset-0.0.8 → benchset-0.0.9}/native/src/config_ffi.rs +4 -2
  13. {benchset-0.0.8 → benchset-0.0.9}/native/src/configured_suite_tests.rs +80 -4
  14. {benchset-0.0.8 → benchset-0.0.9}/native/src/ffi.rs +101 -62
  15. {benchset-0.0.8 → benchset-0.0.9}/native/src/ffi_reference_tests.rs +2 -2
  16. {benchset-0.0.8 → benchset-0.0.9}/native/src/ffi_tests.rs +23 -5
  17. {benchset-0.0.8 → benchset-0.0.9}/native/src/suite_ffi.rs +76 -80
  18. {benchset-0.0.8 → benchset-0.0.9}/native/src/suite_ffi_tests.rs +30 -18
  19. {benchset-0.0.8 → benchset-0.0.9}/pyproject.toml +2 -2
  20. benchset-0.0.9/scripts/cargo.py +251 -0
  21. {benchset-0.0.8 → benchset-0.0.9}/tests/helpers.py +27 -0
  22. {benchset-0.0.8 → benchset-0.0.9}/tests/test_benchset.py +31 -9
  23. {benchset-0.0.8 → benchset-0.0.9}/tests/test_build_native.py +6 -2
  24. {benchset-0.0.8 → benchset-0.0.9}/tests/test_cli.py +22 -4
  25. {benchset-0.0.8 → benchset-0.0.9}/tests/test_cli_progress_streams.py +57 -17
  26. {benchset-0.0.8 → benchset-0.0.9}/tests/test_interpreter_boundary.py +6 -1
  27. benchset-0.0.9/tests/test_loader_signals.py +1685 -0
  28. {benchset-0.0.8 → benchset-0.0.9}/tests/test_metadata.py +19 -6
  29. {benchset-0.0.8 → benchset-0.0.9}/tests/test_publication.py +48 -1
  30. benchset-0.0.9/tests/test_publication_signals.py +1656 -0
  31. {benchset-0.0.8 → benchset-0.0.9}/tests/test_python_core.py +20 -1
  32. {benchset-0.0.8 → benchset-0.0.9}/tests/test_setup.py +5 -2
  33. benchset-0.0.9/tests/test_signal_state_contracts.py +373 -0
  34. benchset-0.0.8/scripts/cargo.py +0 -111
  35. benchset-0.0.8/tests/test_loader_signals.py +0 -497
  36. benchset-0.0.8/tests/test_publication_signals.py +0 -576
  37. {benchset-0.0.8 → benchset-0.0.9}/LICENSE +0 -0
  38. {benchset-0.0.8 → benchset-0.0.9}/MANIFEST.in +0 -0
  39. {benchset-0.0.8 → benchset-0.0.9}/Sources/Benchset/Benchset.swift +0 -0
  40. {benchset-0.0.8 → benchset-0.0.9}/benchset/__init__.py +0 -0
  41. {benchset-0.0.8 → benchset-0.0.9}/benchset/__main__.py +0 -0
  42. {benchset-0.0.8 → benchset-0.0.9}/benchset/_aggregate.py +0 -0
  43. {benchset-0.0.8 → benchset-0.0.9}/benchset/_metadata.json +0 -0
  44. {benchset-0.0.8 → benchset-0.0.9}/benchset/_metadata.py +0 -0
  45. {benchset-0.0.8 → benchset-0.0.9}/benchset/api.py +0 -0
  46. {benchset-0.0.8 → benchset-0.0.9}/benchset/cli.py +0 -0
  47. {benchset-0.0.8 → benchset-0.0.9}/benchset/models.py +0 -0
  48. {benchset-0.0.8 → benchset-0.0.9}/benchset/py.typed +0 -0
  49. {benchset-0.0.8 → benchset-0.0.9}/benchset/reference.py +0 -0
  50. {benchset-0.0.8 → benchset-0.0.9}/benchset.egg-info/dependency_links.txt +0 -0
  51. {benchset-0.0.8 → benchset-0.0.9}/benchset.egg-info/entry_points.txt +0 -0
  52. {benchset-0.0.8 → benchset-0.0.9}/benchset.egg-info/requires.txt +0 -0
  53. {benchset-0.0.8 → benchset-0.0.9}/benchset.egg-info/top_level.txt +0 -0
  54. {benchset-0.0.8 → benchset-0.0.9}/examples/native/c.c +0 -0
  55. {benchset-0.0.8 → benchset-0.0.9}/examples/native/rust.rs +0 -0
  56. {benchset-0.0.8 → benchset-0.0.9}/examples/native/swift.swift +0 -0
  57. {benchset-0.0.8 → benchset-0.0.9}/include/benchset.h +0 -0
  58. {benchset-0.0.8 → benchset-0.0.9}/include/module.modulemap +0 -0
  59. {benchset-0.0.8 → benchset-0.0.9}/native/build.rs +0 -0
  60. {benchset-0.0.8 → benchset-0.0.9}/native/reference-calibration.json +0 -0
  61. {benchset-0.0.8 → benchset-0.0.9}/native/src/aggregation_ffi_tests.rs +0 -0
  62. {benchset-0.0.8 → benchset-0.0.9}/native/src/catalog.rs +0 -0
  63. {benchset-0.0.8 → benchset-0.0.9}/native/src/config_ffi_tests.rs +0 -0
  64. {benchset-0.0.8 → benchset-0.0.9}/native/src/kernel.rs +0 -0
  65. {benchset-0.0.8 → benchset-0.0.9}/native/src/kernel_tests.rs +0 -0
  66. {benchset-0.0.8 → benchset-0.0.9}/native/src/lib.rs +0 -0
  67. {benchset-0.0.8 → benchset-0.0.9}/native/src/observed_suite_tests.rs +0 -0
  68. {benchset-0.0.8 → benchset-0.0.9}/native/src/reference.rs +0 -0
  69. {benchset-0.0.8 → benchset-0.0.9}/native/src/reference_tests.rs +0 -0
  70. {benchset-0.0.8 → benchset-0.0.9}/native/src/runtime_tests.rs +0 -0
  71. {benchset-0.0.8 → benchset-0.0.9}/native/src/suite_tests.rs +0 -0
  72. {benchset-0.0.8 → benchset-0.0.9}/rust-toolchain.toml +0 -0
  73. {benchset-0.0.8 → benchset-0.0.9}/scripts/__init__.py +0 -0
  74. {benchset-0.0.8 → benchset-0.0.9}/scripts/build_backend.py +0 -0
  75. {benchset-0.0.8 → benchset-0.0.9}/scripts/build_native.py +0 -0
  76. {benchset-0.0.8 → benchset-0.0.9}/scripts/check_native_coverage.py +0 -0
  77. {benchset-0.0.8 → benchset-0.0.9}/scripts/check_source_install.py +0 -0
  78. {benchset-0.0.8 → benchset-0.0.9}/scripts/package_native.py +0 -0
  79. {benchset-0.0.8 → benchset-0.0.9}/scripts/release.py +0 -0
  80. {benchset-0.0.8 → benchset-0.0.9}/scripts/version.py +0 -0
  81. {benchset-0.0.8 → benchset-0.0.9}/setup.cfg +0 -0
  82. {benchset-0.0.8 → benchset-0.0.9}/setup.py +0 -0
  83. {benchset-0.0.8 → benchset-0.0.9}/tests/__init__.py +0 -0
  84. {benchset-0.0.8 → benchset-0.0.9}/tests/swift/AggregationTests.swift +0 -0
  85. {benchset-0.0.8 → benchset-0.0.9}/tests/swift/BenchsetTests.swift +0 -0
  86. {benchset-0.0.8 → benchset-0.0.9}/tests/swift/ReferenceTests.swift +0 -0
  87. {benchset-0.0.8 → benchset-0.0.9}/tests/test_aggregate_exponential.py +0 -0
  88. {benchset-0.0.8 → benchset-0.0.9}/tests/test_aggregate_getters.py +0 -0
  89. {benchset-0.0.8 → benchset-0.0.9}/tests/test_aggregate_memory.py +0 -0
  90. {benchset-0.0.8 → benchset-0.0.9}/tests/test_aggregate_protocols.py +0 -0
  91. {benchset-0.0.8 → benchset-0.0.9}/tests/test_aggregate_tuple_inputs.py +0 -0
  92. {benchset-0.0.8 → benchset-0.0.9}/tests/test_aggregation_boundary.py +0 -0
  93. {benchset-0.0.8 → benchset-0.0.9}/tests/test_approved_python_contracts.py +0 -0
  94. {benchset-0.0.8 → benchset-0.0.9}/tests/test_build.py +0 -0
  95. {benchset-0.0.8 → benchset-0.0.9}/tests/test_cli_active_signal_policy.py +0 -0
  96. {benchset-0.0.8 → benchset-0.0.9}/tests/test_cli_cleanup_signals.py +0 -0
  97. {benchset-0.0.8 → benchset-0.0.9}/tests/test_cli_embedded_signals.py +0 -0
  98. {benchset-0.0.8 → benchset-0.0.9}/tests/test_cli_final_signal_restore.py +0 -0
  99. {benchset-0.0.8 → benchset-0.0.9}/tests/test_cli_loader_validation.py +0 -0
  100. {benchset-0.0.8 → benchset-0.0.9}/tests/test_cli_loading_signals.py +0 -0
  101. {benchset-0.0.8 → benchset-0.0.9}/tests/test_cli_observer_signals.py +0 -0
  102. {benchset-0.0.8 → benchset-0.0.9}/tests/test_cli_signal_policy.py +0 -0
  103. {benchset-0.0.8 → benchset-0.0.9}/tests/test_cli_terminal_errors.py +0 -0
  104. {benchset-0.0.8 → benchset-0.0.9}/tests/test_core_contract.py +0 -0
  105. {benchset-0.0.8 → benchset-0.0.9}/tests/test_errors.py +0 -0
  106. {benchset-0.0.8 → benchset-0.0.9}/tests/test_exception_contexts.py +0 -0
  107. {benchset-0.0.8 → benchset-0.0.9}/tests/test_float_transport.py +0 -0
  108. {benchset-0.0.8 → benchset-0.0.9}/tests/test_installer_copy.py +0 -0
  109. {benchset-0.0.8 → benchset-0.0.9}/tests/test_loader_failures.py +0 -0
  110. {benchset-0.0.8 → benchset-0.0.9}/tests/test_loader_imports.py +0 -0
  111. {benchset-0.0.8 → benchset-0.0.9}/tests/test_name_diagnostics.py +0 -0
  112. {benchset-0.0.8 → benchset-0.0.9}/tests/test_name_operands.py +0 -0
  113. {benchset-0.0.8 → benchset-0.0.9}/tests/test_native_coverage.py +0 -0
  114. {benchset-0.0.8 → benchset-0.0.9}/tests/test_native_lifetimes.py +0 -0
  115. {benchset-0.0.8 → benchset-0.0.9}/tests/test_packaging.py +0 -0
  116. {benchset-0.0.8 → benchset-0.0.9}/tests/test_quiet_validation.py +0 -0
  117. {benchset-0.0.8 → benchset-0.0.9}/tests/test_reference.py +0 -0
  118. {benchset-0.0.8 → benchset-0.0.9}/tests/test_reference_artifacts.py +0 -0
  119. {benchset-0.0.8 → benchset-0.0.9}/tests/test_reference_native.py +0 -0
  120. {benchset-0.0.8 → benchset-0.0.9}/tests/test_release.py +0 -0
  121. {benchset-0.0.8 → benchset-0.0.9}/tests/test_resources.py +0 -0
  122. {benchset-0.0.8 → benchset-0.0.9}/tests/test_runner_thread_safety.py +0 -0
  123. {benchset-0.0.8 → benchset-0.0.9}/tests/test_rust_api.py +0 -0
  124. {benchset-0.0.8 → benchset-0.0.9}/tests/test_semantics.py +0 -0
  125. {benchset-0.0.8 → benchset-0.0.9}/tests/test_signals.py +0 -0
  126. {benchset-0.0.8 → benchset-0.0.9}/tests/test_suite.py +0 -0
  127. {benchset-0.0.8 → benchset-0.0.9}/tests/test_suite_options.py +0 -0
  128. {benchset-0.0.8 → benchset-0.0.9}/tests/test_suite_signal_policy.py +0 -0
  129. {benchset-0.0.8 → benchset-0.0.9}/tests/test_validation_lifetime.py +0 -0
  130. {benchset-0.0.8 → benchset-0.0.9}/tests/test_version.py +0 -0
  131. {benchset-0.0.8 → benchset-0.0.9}/tests/typing/__init__.py +0 -0
  132. {benchset-0.0.8 → benchset-0.0.9}/tests/typing/reference_negative.py +0 -0
  133. {benchset-0.0.8 → benchset-0.0.9}/tests/typing/reference_positive.py +0 -0
  134. {benchset-0.0.8 → benchset-0.0.9}/tests/typing/test_reference_types.py +0 -0
@@ -4,4 +4,4 @@ version = 3
4
4
 
5
5
  [[package]]
6
6
  name = "benchset"
7
- version = "0.0.8"
7
+ version = "0.0.9"
@@ -1,7 +1,7 @@
1
1
  [package]
2
2
  name = "benchset"
3
3
  # Generated from [project].version in pyproject.toml by scripts/version.py.
4
- version = "0.0.8"
4
+ version = "0.0.9"
5
5
  edition = "2021"
6
6
  rust-version = "1.74"
7
7
  build = "native/build.rs"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: benchset
3
- Version: 0.0.8
3
+ Version: 0.0.9
4
4
  Summary: Sustained scalar CPU benchmarks with an embeddable Rust core
5
5
  Author-email: Evgeniy Blinov <zheni-b@yandex.ru>
6
6
  Project-URL: Source, https://github.com/mutating/benchset
@@ -279,7 +279,25 @@ or separately linked copies of the library can still compete for CPU time.
279
279
 
280
280
  With Python's default SIGINT handler, Ctrl+C during a main-thread call cancels
281
281
  the native work and raises `KeyboardInterrupt` after cleanup. Custom signal
282
- handlers are preserved.
282
+ handlers are preserved. During the first native load, the first deferred
283
+ SIGINT goes to the original Python handler, and any later deferred SIGINT
284
+ uses the handler active at delivery.
285
+
286
+ On Linux and macOS, the loader preserves the Unix `SA_RESTART` flag across
287
+ temporary handler changes. An audit hook that denies access to `sigaction`
288
+ can prevent this. A simultaneous change to the SIGINT disposition between
289
+ the native snapshot and Python's handler installation can also reset the flag.
290
+ Concurrent changes during native restoration can cause an interrupt in that
291
+ window to miss its intended delivery. The loader reconciles policy changes
292
+ observed after restoration with the OS.
293
+ During snapshot initialization, a `PermissionError` is treated as an audit
294
+ refusal unless the traceback identifies a Python signal or tracing callback. A handler that
295
+ changes its signal arguments or a restriction on traceback inspection can
296
+ prevent that identification.
297
+
298
+ Source-build publication preserves recognizable signal, audit and tracing
299
+ vetoes. Global I/O replacements that imitate those callback argument and
300
+ event protocols can also be treated as host callbacks.
283
301
 
284
302
  ## What one iteration does
285
303
 
@@ -476,7 +494,7 @@ pinned release toolchain described under [Publishing](#publishing).
476
494
 
477
495
  ```toml
478
496
  [dependencies]
479
- benchset = "0.0.8"
497
+ benchset = "0.0.9"
480
498
  # For changes from a local source checkout, use:
481
499
  # benchset = { path = "../benchset" }
482
500
  ```
@@ -642,7 +660,7 @@ the same repository. Rust is not required by the consumer.
642
660
  For a Swift manifest, add:
643
661
 
644
662
  ```swift
645
- .package(url: "https://github.com/mutating/benchset.git", .exact("0.0.8"))
663
+ .package(url: "https://github.com/mutating/benchset.git", .exact("0.0.9"))
646
664
  ```
647
665
 
648
666
  Add `.product(name: "Benchset", package: "benchset")` to your target's
@@ -9,8 +9,8 @@ let package = Package(
9
9
  products: [.library(name: "Benchset", targets: ["Benchset"])],
10
10
  targets: [
11
11
  .binaryTarget(name: "CBenchset",
12
- url: "https://github.com/mutating/benchset/releases/download/v0.0.8/Benchset.xcframework.zip",
13
- checksum: "dbac0aa83bcb256b908a9ddf040324d0f675fb1da5e073b5f11b3bc06723f3eb"),
12
+ url: "https://github.com/mutating/benchset/releases/download/v0.0.9/Benchset.xcframework.zip",
13
+ checksum: "619d13ae2e632f6d2971846be6e82395746a74927819d8185fde3c8c0d68f1bc"),
14
14
  .target(name: "Benchset", dependencies: ["CBenchset"]),
15
15
  .testTarget(name: "BenchsetTests", dependencies: ["Benchset"], path: "tests/swift")
16
16
  ]
@@ -245,7 +245,25 @@ or separately linked copies of the library can still compete for CPU time.
245
245
 
246
246
  With Python's default SIGINT handler, Ctrl+C during a main-thread call cancels
247
247
  the native work and raises `KeyboardInterrupt` after cleanup. Custom signal
248
- handlers are preserved.
248
+ handlers are preserved. During the first native load, the first deferred
249
+ SIGINT goes to the original Python handler, and any later deferred SIGINT
250
+ uses the handler active at delivery.
251
+
252
+ On Linux and macOS, the loader preserves the Unix `SA_RESTART` flag across
253
+ temporary handler changes. An audit hook that denies access to `sigaction`
254
+ can prevent this. A simultaneous change to the SIGINT disposition between
255
+ the native snapshot and Python's handler installation can also reset the flag.
256
+ Concurrent changes during native restoration can cause an interrupt in that
257
+ window to miss its intended delivery. The loader reconciles policy changes
258
+ observed after restoration with the OS.
259
+ During snapshot initialization, a `PermissionError` is treated as an audit
260
+ refusal unless the traceback identifies a Python signal or tracing callback. A handler that
261
+ changes its signal arguments or a restriction on traceback inspection can
262
+ prevent that identification.
263
+
264
+ Source-build publication preserves recognizable signal, audit and tracing
265
+ vetoes. Global I/O replacements that imitate those callback argument and
266
+ event protocols can also be treated as host callbacks.
249
267
 
250
268
  ## What one iteration does
251
269
 
@@ -442,7 +460,7 @@ pinned release toolchain described under [Publishing](#publishing).
442
460
 
443
461
  ```toml
444
462
  [dependencies]
445
- benchset = "0.0.8"
463
+ benchset = "0.0.9"
446
464
  # For changes from a local source checkout, use:
447
465
  # benchset = { path = "../benchset" }
448
466
  ```
@@ -608,7 +626,7 @@ the same repository. Rust is not required by the consumer.
608
626
  For a Swift manifest, add:
609
627
 
610
628
  ```swift
611
- .package(url: "https://github.com/mutating/benchset.git", .exact("0.0.8"))
629
+ .package(url: "https://github.com/mutating/benchset.git", .exact("0.0.9"))
612
630
  ```
613
631
 
614
632
  Add `.product(name: "Benchset", package: "benchset")` to your target's
@@ -10,9 +10,26 @@ from os.path import abspath
10
10
  from pathlib import Path
11
11
  from threading import current_thread, main_thread
12
12
  from types import FrameType
13
- from typing import TYPE_CHECKING, Any, Callable, List, NoReturn, Optional, Tuple, cast
13
+ from typing import (
14
+ TYPE_CHECKING,
15
+ Any,
16
+ Callable,
17
+ List,
18
+ Optional,
19
+ Tuple,
20
+ cast,
21
+ )
14
22
 
15
23
  from benchset._metadata import DATA, canonical_name
24
+ from benchset._signal_state import (
25
+ _direct_error,
26
+ _get_signal,
27
+ _native_sigaction,
28
+ _raise_original as _raise_original, # noqa: PLC0414 — Shared with the host adapters.
29
+ _restore_sigint,
30
+ _set_signal,
31
+ _SignalHandler,
32
+ )
16
33
  from benchset.models import (
17
34
  AggregatedScores,
18
35
  BenchmarkResult,
@@ -87,31 +104,49 @@ def _load_library(path: str) -> _CDLL:
87
104
  handler = signal.getsignal(signal.SIGINT)
88
105
  if current_thread() is not main_thread() or not callable(handler):
89
106
  return _shared_library(path)
107
+ native = _native_sigaction()
108
+ # Resolving the native symbol can run a caller's audit hook.
109
+ handler = _get_signal(signal.SIGINT)
110
+ if not callable(handler):
111
+ return _shared_library(path)
90
112
  pending: List[Tuple[int, Optional[FrameType]]] = []
113
+ deferring = True
91
114
 
92
115
  def defer(signum: int, frame: Optional[FrameType]) -> None:
93
- pending.append((signum, frame))
116
+ if deferring:
117
+ pending.append((signum, frame))
118
+ elif callable(handler):
119
+ handler(signum, frame)
94
120
 
95
121
  try:
96
- signal.signal(signal.SIGINT, defer)
97
- except ValueError: # Subinterpreters cannot install or receive Python signal handlers.
98
- return _shared_library(path)
99
- try:
122
+ try:
123
+ previous = _set_signal(signal.SIGINT, defer, native)
124
+ if previous is not None:
125
+ handler = previous
126
+ except ValueError as error:
127
+ if (not _direct_error(error, _set_signal) or _get_signal(signal.SIGINT) is defer or error.args not in (
128
+ ('signal only works in main thread',),
129
+ ('signal only works in main thread of the main interpreter',),
130
+ ('signal only works in main thread or with __pypy__.thread.enable_signals()',),
131
+ )):
132
+ raise
100
133
  return _shared_library(path)
101
134
  finally:
102
135
  try:
103
- signal.signal(signal.SIGINT, handler)
136
+ _restore_sigint(defer, handler, native, _set_signal)
137
+ callback: Optional[_SignalHandler] = handler
104
138
  while pending:
105
139
  arguments = pending.pop(0)
106
140
  try:
107
- callback = signal.getsignal(signal.SIGINT)
108
141
  if callable(callback):
109
142
  callback(*arguments)
110
143
  elif callback != signal.SIG_IGN:
111
144
  signal.raise_signal(signal.SIGINT)
145
+ callback = _get_signal(signal.SIGINT)
112
146
  finally:
113
147
  del arguments
114
148
  finally:
149
+ deferring = False
115
150
  pending.clear() # Frames can refer back to this queue, even with cyclic GC disabled.
116
151
 
117
152
 
@@ -134,17 +169,6 @@ class _Functions:
134
169
  return function
135
170
 
136
171
 
137
- def _raise_original(error: BaseException) -> NoReturn:
138
- """Preserve host context without retaining the exception in its own traceback."""
139
- descriptor = BaseException.__dict__['__context__']
140
- context = descriptor.__get__(error)
141
- try:
142
- raise error
143
- finally:
144
- descriptor.__set__(error, context)
145
- del error
146
-
147
-
148
172
  class Config(ctypes.Structure):
149
173
  _fields_ = [ # noqa: RUF012 — ctypes requires this mutable class attribute.
150
174
  ('abi_version', ctypes.c_uint32),
@@ -0,0 +1,177 @@
1
+ """Process SIGINT policy shared by the Python loader and source publisher."""
2
+
3
+ import _signal # type: ignore[import-not-found] # The low-level stdlib signal setter.
4
+ import signal
5
+ import sys
6
+ from functools import lru_cache
7
+ from os import getpid
8
+ from threading import local
9
+ from types import FrameType, TracebackType
10
+ from typing import Any, Callable, List, NoReturn, Optional, Union, cast
11
+
12
+ _SignalHandler = Union[Callable[[int, Optional[FrameType]], None], int]
13
+ _NativeSigaction = Callable[[int, Optional[object], Optional[object]], int]
14
+
15
+
16
+ _sigaction_resolution = local()
17
+
18
+
19
+ class _SigactionUnavailableError(Exception):
20
+ """The optional native snapshot could not be initialized."""
21
+
22
+
23
+ def _from_callback(trace: Optional[TracebackType], *, include_audit: bool = False) -> bool:
24
+ # Signal and tracing callbacks receive their originating frame. Audit
25
+ # callbacks receive (event, args). Inspect the actual invocation so
26
+ # callbacks and ordinary wrappers can share the same Python code.
27
+ # Skip our own except frame. Its cached locals would retain the error
28
+ # after the exception variable is cleared.
29
+ try:
30
+ trace = trace.tb_next if trace is not None else None
31
+ while trace is not None:
32
+ frame = trace.tb_frame
33
+ code, variables = frame.f_code, frame.f_locals
34
+ arguments = tuple(variables.get(name) for name in code.co_varnames[:code.co_argcount])
35
+ if code.co_flags & 0x04: # CO_VARARGS, without importing a potentially half-initialized inspect module.
36
+ rest = variables.get(code.co_varnames[code.co_argcount + code.co_kwonlyargcount])
37
+ if type(rest) is tuple:
38
+ arguments += rest
39
+ caller = frame.f_back
40
+ if caller is not None and any(
41
+ (type(value) is int and other is caller) or (
42
+ value is caller and type(other) is str and other in (
43
+ 'call', 'return', 'exception', 'line', 'opcode', 'c_call', 'c_return', 'c_exception',
44
+ )
45
+ )
46
+ for value, other in zip(arguments, arguments[1:])
47
+ ):
48
+ return True
49
+ if include_audit and any(type(value) is str and type(other) is tuple
50
+ for value, other in zip(arguments, arguments[1:])):
51
+ return True
52
+ trace = trace.tb_next
53
+ except PermissionError:
54
+ pass # Auditing can deny frame inspection as well as the symbol.
55
+ return False
56
+
57
+
58
+ @lru_cache(maxsize=1)
59
+ def _sigaction() -> _NativeSigaction:
60
+ pid = getpid()
61
+ if getattr(_sigaction_resolution, 'pid', None) == pid:
62
+ raise RuntimeError('reentrant native SIGINT disposition lookup')
63
+ try:
64
+ _sigaction_resolution.pid = pid
65
+ try:
66
+ try:
67
+ import ctypes # noqa: PLC0415 — Native snapshots are optional in the source publisher.
68
+ except ImportError as error:
69
+ if _from_callback(BaseException.__dict__['__traceback__'].__get__(error)):
70
+ raise
71
+ raise _SigactionUnavailableError from None
72
+
73
+ process = getattr(ctypes, 'pythonapi', None)
74
+ if process is None:
75
+ factory = getattr(ctypes, 'CDLL', None)
76
+ if factory is None:
77
+ raise _SigactionUnavailableError
78
+ process = factory(None)
79
+ function = process['sigaction']
80
+ except PermissionError as error:
81
+ if _from_callback(BaseException.__dict__['__traceback__'].__get__(error)):
82
+ raise
83
+ raise _SigactionUnavailableError from None
84
+ function.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p]
85
+ function.restype = ctypes.c_int
86
+ return cast(_NativeSigaction, function)
87
+ finally:
88
+ _sigaction_resolution.pid = None
89
+
90
+
91
+ def _native_sigaction() -> Optional[_NativeSigaction]:
92
+ if sys.platform in ('darwin', 'linux'):
93
+ try:
94
+ return _sigaction()
95
+ except _SigactionUnavailableError:
96
+ pass
97
+ return None
98
+
99
+
100
+ def _get_signal(signum: int) -> Optional[_SignalHandler]:
101
+ handler: Optional[_SignalHandler] = _signal.getsignal(signum)
102
+ return signal.Handlers(handler) if type(handler) is int else handler
103
+
104
+
105
+ def _set_signal(signum: int, handler: _SignalHandler, native: Optional[_NativeSigaction]) -> Optional[_SignalHandler]:
106
+ current = _get_signal(signum)
107
+ previous = current
108
+ action = None
109
+ if native is not None and callable(current) and callable(handler):
110
+ import ctypes # noqa: PLC0415 — The native symbol has already initialized ctypes.
111
+
112
+ # Aligned opaque storage for Darwin and Linux libc sigaction structures.
113
+ action = ctypes.byref((ctypes.c_uint64 * 32)())
114
+ if native(signum, None, action) != 0:
115
+ raise OSError('cannot read the native SIGINT disposition')
116
+ try:
117
+ # The handler is already registered or ours. Avoid signal.signal's
118
+ # int conversion, which can execute user code on a callable object.
119
+ selected = int(handler) if type(handler) is signal.Handlers else handler
120
+ previous = _signal.signal(int(signum), selected)
121
+ finally:
122
+ # Python callables share the same native trampoline. Reapply the
123
+ # caller's OS flags and mask while keeping the new Python callable.
124
+ if native is not None and action is not None and previous is current and _get_signal(signum) is handler:
125
+ if native(signum, action, None) != 0:
126
+ raise OSError('cannot restore the native SIGINT disposition')
127
+ replacement = _get_signal(signum)
128
+ if replacement is not None and replacement is not handler:
129
+ _restore_sigint(replacement, replacement, None)
130
+ return signal.Handlers(previous) if type(previous) is int else previous
131
+
132
+
133
+ def _direct_error(error: BaseException, operation: Callable[..., Any]) -> bool:
134
+ # A caller signal adds a frame outside the registration call.
135
+ trace = BaseException.__dict__['__traceback__'].__get__(error)
136
+ called = trace.tb_next if trace is not None else None
137
+ try:
138
+ return called is None or (called.tb_next is None and
139
+ called.tb_frame.f_code is getattr(operation, '__code__', None))
140
+ except PermissionError:
141
+ return True # Only a direct operation's frame remained before inspection was denied.
142
+
143
+
144
+ def _restore_sigint(
145
+ owner: _SignalHandler, target: _SignalHandler, native: Optional[_NativeSigaction],
146
+ setter: Callable[[int, _SignalHandler, Optional[_NativeSigaction]], Optional[_SignalHandler]] = _set_signal,
147
+ ) -> None:
148
+ interruptions: List[BaseException] = []
149
+ while True:
150
+ try:
151
+ if _get_signal(signal.SIGINT) is not owner:
152
+ break
153
+ displaced = setter(signal.SIGINT, target, native)
154
+ except BaseException as error:
155
+ if issubclass(type(error), (OSError, TypeError, ValueError)) and _direct_error(error, setter):
156
+ interruptions.clear()
157
+ raise
158
+ if not interruptions:
159
+ interruptions.append(error)
160
+ continue
161
+ if displaced is owner or displaced is None:
162
+ break
163
+ # A caller changed the handler just before the swap. Give it back.
164
+ owner, target = target, displaced
165
+ if interruptions:
166
+ _raise_original(interruptions.pop())
167
+
168
+
169
+ def _raise_original(error: BaseException) -> NoReturn:
170
+ """Preserve host context without retaining the exception in its own traceback."""
171
+ descriptor = BaseException.__dict__['__context__']
172
+ context = descriptor.__get__(error)
173
+ try:
174
+ raise error
175
+ finally:
176
+ descriptor.__set__(error, context)
177
+ del error
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: benchset
3
- Version: 0.0.8
3
+ Version: 0.0.9
4
4
  Summary: Sustained scalar CPU benchmarks with an embeddable Rust core
5
5
  Author-email: Evgeniy Blinov <zheni-b@yandex.ru>
6
6
  Project-URL: Source, https://github.com/mutating/benchset
@@ -279,7 +279,25 @@ or separately linked copies of the library can still compete for CPU time.
279
279
 
280
280
  With Python's default SIGINT handler, Ctrl+C during a main-thread call cancels
281
281
  the native work and raises `KeyboardInterrupt` after cleanup. Custom signal
282
- handlers are preserved.
282
+ handlers are preserved. During the first native load, the first deferred
283
+ SIGINT goes to the original Python handler, and any later deferred SIGINT
284
+ uses the handler active at delivery.
285
+
286
+ On Linux and macOS, the loader preserves the Unix `SA_RESTART` flag across
287
+ temporary handler changes. An audit hook that denies access to `sigaction`
288
+ can prevent this. A simultaneous change to the SIGINT disposition between
289
+ the native snapshot and Python's handler installation can also reset the flag.
290
+ Concurrent changes during native restoration can cause an interrupt in that
291
+ window to miss its intended delivery. The loader reconciles policy changes
292
+ observed after restoration with the OS.
293
+ During snapshot initialization, a `PermissionError` is treated as an audit
294
+ refusal unless the traceback identifies a Python signal or tracing callback. A handler that
295
+ changes its signal arguments or a restriction on traceback inspection can
296
+ prevent that identification.
297
+
298
+ Source-build publication preserves recognizable signal, audit and tracing
299
+ vetoes. Global I/O replacements that imitate those callback argument and
300
+ event protocols can also be treated as host callbacks.
283
301
 
284
302
  ## What one iteration does
285
303
 
@@ -476,7 +494,7 @@ pinned release toolchain described under [Publishing](#publishing).
476
494
 
477
495
  ```toml
478
496
  [dependencies]
479
- benchset = "0.0.8"
497
+ benchset = "0.0.9"
480
498
  # For changes from a local source checkout, use:
481
499
  # benchset = { path = "../benchset" }
482
500
  ```
@@ -642,7 +660,7 @@ the same repository. Rust is not required by the consumer.
642
660
  For a Swift manifest, add:
643
661
 
644
662
  ```swift
645
- .package(url: "https://github.com/mutating/benchset.git", .exact("0.0.8"))
663
+ .package(url: "https://github.com/mutating/benchset.git", .exact("0.0.9"))
646
664
  ```
647
665
 
648
666
  Add `.product(name: "Benchset", package: "benchset")` to your target's
@@ -14,6 +14,7 @@ benchset/_aggregate.py
14
14
  benchset/_metadata.json
15
15
  benchset/_metadata.py
16
16
  benchset/_native.py
17
+ benchset/_signal_state.py
17
18
  benchset/api.py
18
19
  benchset/cli.py
19
20
  benchset/models.py
@@ -112,6 +113,7 @@ tests/test_runner_thread_safety.py
112
113
  tests/test_rust_api.py
113
114
  tests/test_semantics.py
114
115
  tests/test_setup.py
116
+ tests/test_signal_state_contracts.py
115
117
  tests/test_signals.py
116
118
  tests/test_suite.py
117
119
  tests/test_suite_options.py
@@ -207,6 +207,8 @@ const COMPLETE: [(u64, u32); 16] = [
207
207
 
208
208
  /// Host names use exact borrowed UTF-8 and canonical operands, ignore raw IDs,
209
209
  /// accept noncanonical true flags, and compare the common prefix before length.
210
+ /// Counts above 32 bits still compare both names and cannot match a short suite
211
+ /// after narrowing on a 32-bit target.
210
212
  #[test]
211
213
  fn host_names_preserve_operands_prefix_and_nonzero_flags() {
212
214
  for flag in [1, 7, u32::MAX] {
@@ -220,7 +222,7 @@ fn host_names_preserve_operands_prefix_and_nonzero_flags() {
220
222
  assert_eq!(scores.pi_equivalent, 1.0);
221
223
  assert_eq!(state.calls, trace(&COMPLETE, state.ratios));
222
224
  }
223
- for count in [0, 1, 3, u64::MAX] {
225
+ for count in [0, 1, 3, 1 << 32, (1 << 32) + 1, (1 << 32) + 2, u64::MAX] {
224
226
  let mut state = ReaderState::default();
225
227
  let scores = execute(&mut state, count, 1);
226
228
  assert_eq!(scores.has_pi_equivalent, 0);
@@ -25,24 +25,25 @@ pub unsafe extern "C" fn benchset_aggregate(
25
25
  let equivalent = if count == BENCHMARKS.len() as u64 {
26
26
  aggregate(
27
27
  count as usize,
28
- |index, expected| (*inputs.add(index)).benchmark == expected as u32,
29
- |index| (*inputs.add(index)).status,
28
+ |index, expected| (unsafe { (*inputs.add(index)).benchmark }) == expected as u32,
29
+ |index| unsafe { (*inputs.add(index)).status },
30
30
  |index| {
31
- let value = &*inputs.add(index);
31
+ let value = unsafe { &*inputs.add(index) };
32
32
  (value.has_pi_equivalent != 0).then_some(value.pi_equivalent)
33
33
  },
34
34
  )
35
35
  } else {
36
36
  None
37
37
  };
38
- write_scores(out, equivalent)
38
+ unsafe { write_scores(out, equivalent) }
39
39
  }
40
40
 
41
41
  unsafe fn write_scores(out: *mut CAggregatedScores, equivalent: Option<f64>) -> i32 {
42
- out.write(CAggregatedScores {
42
+ let scores = CAggregatedScores {
43
43
  pi_equivalent: equivalent.unwrap_or(0.0),
44
44
  has_pi_equivalent: u32::from(equivalent.is_some()),
45
- });
45
+ };
46
+ unsafe { out.write(scores) };
46
47
  1
47
48
  }
48
49
 
@@ -112,11 +113,12 @@ pub unsafe extern "C" fn benchset_aggregate_read(
112
113
  out: *mut CAggregatedScores,
113
114
  host_names: u32,
114
115
  ) -> i32 {
115
- if out.is_null() || (benchmarks.is_null() && count != 0) || reader.is_none() {
116
+ let Some(reader) = reader else { return 0 };
117
+ if out.is_null() || (benchmarks.is_null() && count != 0) {
116
118
  return 0;
117
119
  }
118
120
  if host_names == 0 && count != BENCHMARKS.len() as u64 {
119
- return write_scores(out, None);
121
+ return unsafe { write_scores(out, None) };
120
122
  }
121
123
  let read = |index: usize, field, operand, name: &str| {
122
124
  let mut request = CAggregateRequest {
@@ -129,45 +131,46 @@ pub unsafe extern "C" fn benchset_aggregate_read(
129
131
  name: name.as_ptr(),
130
132
  name_size: name.len() as u64,
131
133
  };
132
- (reader.unwrap()(index as u64, field, &mut request, user) != 0).then_some(request.value)
134
+ let success = unsafe { reader(index as u64, field, &mut request, user) };
135
+ (success != 0).then_some(request.value)
133
136
  };
134
- write_scores(
135
- out,
136
- aggregate(
137
- count as usize,
138
- |index, expected| {
139
- if host_names == 0 {
140
- *benchmarks.add(index) == expected as u32
137
+ let equivalent = aggregate(
138
+ usize::try_from(count).unwrap_or(usize::MAX),
139
+ |index, expected| {
140
+ if host_names == 0 {
141
+ (unsafe { *benchmarks.add(index) }) == expected as u32
142
+ } else {
143
+ read(index, 5, 0.0, expected.name())
144
+ .is_some_and(|value| value.has_pi_equivalent != 0)
145
+ }
146
+ },
147
+ |index| read(index, 0, 0.0, "").map_or(u32::MAX, |value| value.status),
148
+ |index| {
149
+ let value = read(index, 1, 0.0, "")?;
150
+ if value.has_pi_equivalent == 0 {
151
+ return None;
152
+ }
153
+ Some(ReadRatio {
154
+ index,
155
+ number: if host_names != 0 {
156
+ read(index, 6, 0.0, "")?.pi_equivalent
141
157
  } else {
142
- read(index, 5, 0.0, expected.name())
143
- .is_some_and(|value| value.has_pi_equivalent != 0)
144
- }
145
- },
146
- |index| read(index, 0, 0.0, "").map_or(u32::MAX, |value| value.status),
147
- |index| {
148
- let value = read(index, 1, 0.0, "")?;
149
- if value.has_pi_equivalent == 0 {
150
- return None;
151
- }
152
- Some(ReadRatio {
153
- index,
154
- number: if host_names != 0 {
155
- read(index, 6, 0.0, "")?.pi_equivalent
156
- } else {
157
- value.pi_equivalent
158
- },
159
- host: host_names != 0,
160
- read: &read,
161
- })
162
- },
163
- ),
164
- )
158
+ value.pi_equivalent
159
+ },
160
+ host: host_names != 0,
161
+ read: &read,
162
+ })
163
+ },
164
+ );
165
+ unsafe { write_scores(out, equivalent) }
165
166
  }
166
167
 
167
168
  #[cfg(test)]
169
+ #[allow(unsafe_op_in_unsafe_fn)]
168
170
  #[path = "aggregation_ffi_tests.rs"]
169
171
  mod tests;
170
172
 
171
173
  #[cfg(test)]
174
+ #[allow(unsafe_op_in_unsafe_fn)]
172
175
  #[path = "aggregate_protocol_tests.rs"]
173
176
  mod protocol_tests;
@@ -16,7 +16,8 @@ pub unsafe extern "C" fn benchset_benchmark_id(name: *const u8, size: u64) -> u3
16
16
  if name.is_null() || size > isize::MAX as u64 {
17
17
  return 0;
18
18
  }
19
- std::str::from_utf8(std::slice::from_raw_parts(name, size as usize))
19
+ let name = unsafe { std::slice::from_raw_parts(name, size as usize) };
20
+ std::str::from_utf8(name)
20
21
  .ok()
21
22
  .and_then(Benchmark::from_name)
22
23
  .map_or(0, |benchmark| benchmark as u32)
@@ -37,7 +38,7 @@ pub unsafe extern "C" fn benchset_benchmark_match(
37
38
  return benchmark as u32;
38
39
  }
39
40
  let name = benchmark.name().as_bytes();
40
- match matcher(name.as_ptr(), name.len() as u64, user) {
41
+ match unsafe { matcher(name.as_ptr(), name.len() as u64, user) } {
41
42
  value if value > 0 => return benchmark as u32,
42
43
  0 => {}
43
44
  _ => return 0,
@@ -75,5 +76,6 @@ pub extern "C" fn benchset_validation_message(error: u32, cli: u32) -> *const c_
75
76
  }
76
77
 
77
78
  #[cfg(test)]
79
+ #[allow(unsafe_op_in_unsafe_fn)]
78
80
  #[path = "config_ffi_tests.rs"]
79
81
  mod tests;