hyperprobe-agent 1.2.32b5__tar.gz → 1.2.32b10__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 (58) hide show
  1. {hyperprobe_agent-1.2.32b5/hyperprobe_agent.egg-info → hyperprobe_agent-1.2.32b10}/PKG-INFO +2 -1
  2. hyperprobe_agent-1.2.32b10/hyperprobe/core/bytecode/discovery.py +225 -0
  3. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/engine_base.py +33 -1
  4. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10/hyperprobe_agent.egg-info}/PKG-INFO +2 -1
  5. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe_agent.egg-info/SOURCES.txt +2 -0
  6. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe_agent.egg-info/requires.txt +1 -0
  7. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/setup.py +2 -1
  8. hyperprobe_agent-1.2.32b10/tests/test_bytecode_discovery.py +135 -0
  9. hyperprobe_agent-1.2.32b10/tests/test_engine_diagnostics.py +119 -0
  10. hyperprobe_agent-1.2.32b5/hyperprobe/core/bytecode/discovery.py +0 -71
  11. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/LICENSE +0 -0
  12. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/README.md +0 -0
  13. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/__init__.py +0 -0
  14. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/agent.py +0 -0
  15. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/__init__.py +0 -0
  16. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/broker.py +0 -0
  17. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/bytecode/__init__.py +0 -0
  18. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/bytecode/controller.py +0 -0
  19. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/bytecode/engine.py +0 -0
  20. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/bytecode/imports.py +0 -0
  21. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/bytecode/metric_processor.py +0 -0
  22. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/bytecode/records.py +0 -0
  23. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/bytecode/rewriting.py +0 -0
  24. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/evaluator.py +0 -0
  25. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/locations.py +0 -0
  26. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/logger.py +0 -0
  27. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/monitoring_engine.py +0 -0
  28. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/probe_output.py +0 -0
  29. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/probe_processor.py +0 -0
  30. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/quota.py +0 -0
  31. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/redaction.py +0 -0
  32. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/safety.py +0 -0
  33. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/serializer.py +0 -0
  34. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/core/trace_extractor.py +0 -0
  35. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/protos/__init__.py +0 -0
  36. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/protos/agent_pb2.py +0 -0
  37. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe/protos/agent_pb2_grpc.py +0 -0
  38. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe_agent.egg-info/dependency_links.txt +0 -0
  39. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/hyperprobe_agent.egg-info/top_level.txt +0 -0
  40. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/setup.cfg +0 -0
  41. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_agent.py +0 -0
  42. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_agent_backend_integration.py +0 -0
  43. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_bytecode_backend.py +0 -0
  44. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_bytecode_lifecycle.py +0 -0
  45. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_bytecode_token_lifecycle.py +0 -0
  46. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_engine_selection.py +0 -0
  47. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_evaluator.py +0 -0
  48. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_fork.py +0 -0
  49. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_logger.py +0 -0
  50. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_metric_probes.py +0 -0
  51. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_multithreading_integration.py +0 -0
  52. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_p1_regressions.py +0 -0
  53. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_probe_output.py +0 -0
  54. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_redaction.py +0 -0
  55. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_safety.py +0 -0
  56. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_serializer.py +0 -0
  57. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_shared_processor.py +0 -0
  58. {hyperprobe_agent-1.2.32b5 → hyperprobe_agent-1.2.32b10}/tests/test_startup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hyperprobe-agent
3
- Version: 1.2.32b5
3
+ Version: 1.2.32b10
4
4
  Summary: Production-grade, non-breaking live debugger and telemetry agent for Python.
5
5
  Home-page: https://www.hyperprobe.co
6
6
  Author: Arif, Saksham, Karan
@@ -30,6 +30,7 @@ Requires-Dist: grpcio>=1.50.0; extra == "dev"
30
30
  Requires-Dist: grpcio-tools>=1.50.0; extra == "dev"
31
31
  Requires-Dist: protobuf>=4.21.0; extra == "dev"
32
32
  Requires-Dist: pytest>=7.0.0; extra == "dev"
33
+ Requires-Dist: wrapt<3,>=1.16; extra == "dev"
33
34
  Dynamic: author
34
35
  Dynamic: author-email
35
36
  Dynamic: classifier
@@ -0,0 +1,225 @@
1
+ """Targeted module lookup; no heap scan and no implicit application imports."""
2
+
3
+ import os
4
+ import sys
5
+ from functools import partial
6
+ from itertools import islice
7
+ from types import (FunctionType, GetSetDescriptorType, MemberDescriptorType,
8
+ MethodType, ModuleType)
9
+
10
+
11
+ _MODULE_DICT = ModuleType.__dict__["__dict__"]
12
+ _CLASS_DICT = type.__dict__["__dict__"]
13
+ _CLASS_MRO = type.__dict__["__mro__"]
14
+ _DESCRIPTORS = (GetSetDescriptorType, MemberDescriptorType)
15
+ _LINK_NAMES = ("__wrapped__", "func", "view_class", "cls", "registry")
16
+ _MAX_LINK_DEPTH = 32
17
+ _MAX_LINK_OBJECTS = 256
18
+ _MAX_CONTAINER_ITEMS = 64
19
+
20
+
21
+ def _module_namespace(module):
22
+ # isinstance() accepts proxies advertising a module's __class__, but the
23
+ # module descriptor requires an actual module. Do not invoke proxy hooks.
24
+ if issubclass(type(module), ModuleType):
25
+ return _MODULE_DICT.__get__(module)
26
+ return None
27
+
28
+
29
+ def _class_attribute(cls, name, default=None):
30
+ """Read raw class storage without invoking metaclass attribute hooks."""
31
+ for base in _CLASS_MRO.__get__(cls):
32
+ namespace = _CLASS_DICT.__get__(base)
33
+ if name in namespace:
34
+ return namespace[name]
35
+ return default
36
+
37
+
38
+ def _static_attribute(value, name):
39
+ """Read metadata without resolving application descriptors or getters."""
40
+ cls = type(value)
41
+ if issubclass(cls, type):
42
+ return _class_attribute(value, name, _class_attribute(cls, name))
43
+ member = _class_attribute(cls, name)
44
+ member_type = type(member)
45
+ if (_class_attribute(member_type, "__get__") is not None
46
+ and (_class_attribute(member_type, "__set__") is not None
47
+ or _class_attribute(member_type, "__delete__") is not None)):
48
+ return member
49
+ descriptor = _class_attribute(cls, "__dict__")
50
+ if type(descriptor) is GetSetDescriptorType:
51
+ # Native wrappers can forward __dict__ into application getters. Check
52
+ # its owner so vendored copies and subclasses cannot bypass the guard.
53
+ wrapped = _class_attribute(descriptor.__objclass__, "__wrapped__")
54
+ if type(wrapped) is GetSetDescriptorType:
55
+ return member
56
+ namespace = descriptor.__get__(value)
57
+ if type(namespace) is dict and name in namespace:
58
+ return namespace[name]
59
+ return member
60
+
61
+
62
+ def _wrapt_reference(value):
63
+ # Optional dependency: use only already-loaded, concrete wrapper types.
64
+ # Calling a generic proxy's __wrapped__ getter could initialize lazy code.
65
+ for name in ("wrapt", "wrapt.wrappers"):
66
+ namespace = _module_namespace(sys.modules.get(name))
67
+ if namespace is None or not any(
68
+ type(value) is namespace.get(key)
69
+ for key in ("FunctionWrapper", "BoundFunctionWrapper")
70
+ ):
71
+ continue
72
+ descriptor = _class_attribute(type(value), "__wrapped__")
73
+ if type(descriptor) in _DESCRIPTORS:
74
+ return descriptor.__get__(value)
75
+ # Pure-Python wrapt can shadow __dict__ with a forwarding property.
76
+ # Read its real storage through the builtin dictionary descriptor.
77
+ for base in _CLASS_MRO.__get__(type(value)):
78
+ descriptor = _CLASS_DICT.__get__(base).get("__dict__")
79
+ if type(descriptor) is GetSetDescriptorType:
80
+ namespace = descriptor.__get__(value)
81
+ if type(namespace) is dict:
82
+ return namespace.get("__wrapped__")
83
+ return None
84
+
85
+
86
+ def _passive_references(value):
87
+ """Read wrapper metadata without calling properties or __getattr__."""
88
+ for name in _LINK_NAMES:
89
+ reference = _static_attribute(value, name)
90
+ if not issubclass(type(reference), property) and type(reference) not in _DESCRIPTORS:
91
+ yield reference
92
+ if type(value) is partial:
93
+ yield value.func
94
+ reference = _wrapt_reference(value)
95
+ if reference is not None:
96
+ yield reference
97
+
98
+
99
+ def canonical_path(path):
100
+ return os.path.abspath(os.path.realpath(path))
101
+
102
+
103
+ def loaded_modules_at(paths, report):
104
+ matches = {path: [] for path in paths}
105
+ if not matches:
106
+ return matches
107
+ basenames = {os.path.basename(path) for path in matches}
108
+ for module in tuple(sys.modules.values()):
109
+ try:
110
+ namespace = _module_namespace(module)
111
+ if namespace is None:
112
+ continue
113
+ filename = namespace.get("__file__")
114
+ if not isinstance(filename, str):
115
+ filename = _static_attribute(namespace.get("__spec__"), "origin")
116
+ if not isinstance(filename, str) or os.path.basename(filename) not in basenames:
117
+ continue
118
+ path = canonical_path(filename)
119
+ if path in matches:
120
+ matches[path].append(module)
121
+ except BaseException as error:
122
+ report("module inspection", error)
123
+ return matches
124
+
125
+
126
+ def functions_in_module(module, report):
127
+ seen_functions, seen_classes, seen_containers = set(), set(), set()
128
+ namespace = _module_namespace(module)
129
+ if namespace is None:
130
+ return
131
+ module_name = namespace.get("__name__")
132
+
133
+ def walk(value, depth=0, link_depth=0, budget=None):
134
+ try:
135
+ state = (id(value), min(depth, 2))
136
+ if budget is None:
137
+ # Output deduplication is global; expansion is local to this
138
+ # root so a truncated path cannot hide a later, shorter path.
139
+ budget = [_MAX_LINK_OBJECTS, {state: 0}]
140
+ if link_depth:
141
+ previous_depth = budget[1].get(state)
142
+ if (link_depth > _MAX_LINK_DEPTH or budget[0] <= 0
143
+ or (previous_depth is not None and previous_depth <= link_depth)):
144
+ return
145
+ budget[0] -= 1
146
+ budget[1][state] = link_depth
147
+ next_link = link_depth + 1 if link_depth else 0
148
+ if type(value) is FunctionType:
149
+ if id(value) not in seen_functions:
150
+ seen_functions.add(id(value))
151
+ yield value
152
+ # Prefer explicit links over incidental closure state, which
153
+ # may consume the budget before the wrapped target is reached.
154
+ for reference in _passive_references(value):
155
+ if reference is not None:
156
+ yield from walk(reference, depth, link_depth + 1, budget)
157
+ # Decorators without metadata (including DRF generated handlers)
158
+ # can retain their target in closure cells or default arguments.
159
+ for cell in (value.__closure__ or ())[:_MAX_CONTAINER_ITEMS]:
160
+ try:
161
+ reference = cell.cell_contents
162
+ except ValueError: # Empty cell during function initialization.
163
+ continue
164
+ yield from walk(reference, depth, link_depth + 1, budget)
165
+ for defaults in (value.__defaults__, value.__kwdefaults__):
166
+ yield from walk(defaults, depth, link_depth + 1, budget)
167
+ return
168
+ elif issubclass(type(value), (MethodType, staticmethod, classmethod)):
169
+ base = MethodType if type(value) is MethodType else (
170
+ staticmethod if issubclass(type(value), staticmethod) else classmethod
171
+ )
172
+ function = base.__dict__["__func__"].__get__(value)
173
+ yield from walk(function, depth, link_depth, budget)
174
+ return
175
+ elif issubclass(type(value), property):
176
+ for name in ("fget", "fset", "fdel"):
177
+ accessor = property.__dict__[name].__get__(value)
178
+ if accessor is not None:
179
+ yield from walk(accessor, depth, link_depth, budget)
180
+ return
181
+ elif issubclass(type(value), type):
182
+ members = _CLASS_DICT.__get__(value)
183
+ owner = members.get("__module__")
184
+ if type(owner) is not str or type(module_name) is not str or owner != module_name:
185
+ return
186
+ # An earlier bounded expansion must not hide members from the
187
+ # original, unbounded module/class namespace traversal.
188
+ if not link_depth:
189
+ if id(value) in seen_classes:
190
+ return
191
+ seen_classes.add(id(value))
192
+ values = members.values()
193
+ if link_depth:
194
+ values = islice(values, budget[0])
195
+ for member in tuple(values):
196
+ yield from walk(member, depth + 1, next_link, budget if link_depth else None)
197
+ return
198
+ elif depth < 2 and (link_depth or id(value) not in seen_containers):
199
+ if type(value) in (tuple, list, set, frozenset) and len(value) <= _MAX_CONTAINER_ITEMS:
200
+ if not link_depth:
201
+ seen_containers.add(id(value))
202
+ for member in tuple(islice(value, _MAX_CONTAINER_ITEMS)):
203
+ yield from walk(member, depth + 1, next_link, budget if link_depth else None)
204
+ return
205
+ # A mappingproxy can forward to an arbitrary application
206
+ # mapping. Only concrete builtin storage is safe to iterate.
207
+ elif type(value) is dict and len(value) <= _MAX_CONTAINER_ITEMS:
208
+ if not link_depth:
209
+ seen_containers.add(id(value))
210
+ for member in tuple(islice(value.values(), _MAX_CONTAINER_ITEMS)):
211
+ yield from walk(member, depth + 1, next_link, budget if link_depth else None)
212
+ return
213
+ # Only callable/descriptor metadata is relevant. Inspect it
214
+ # statically so application getters and proxies are never executed.
215
+ if callable(value) or _class_attribute(type(value), "__get__") is not None:
216
+ for reference in _passive_references(value):
217
+ if reference is not None:
218
+ yield from walk(reference, depth, link_depth + 1, budget)
219
+ except GeneratorExit:
220
+ raise
221
+ except BaseException as error:
222
+ report("function discovery", error)
223
+
224
+ for value in tuple(namespace.values()):
225
+ yield from walk(value)
@@ -37,6 +37,7 @@ class EngineBase:
37
37
  self.total_hits = 0
38
38
  self.total_skips = 0
39
39
  self._errors = []
40
+ self._error_keys = set()
40
41
  self._processor = ProbeProcessor(self)
41
42
 
42
43
  @property
@@ -48,9 +49,40 @@ class EngineBase:
48
49
  """Bound diagnostics and make even a failing logger harmless."""
49
50
  try:
50
51
  message = "[HyperProbe] %s failed (%s)." % (operation, type(error).__name__)
52
+ key = message
51
53
  with self.lock:
52
- if message in self._errors or len(self._errors) >= 32:
54
+ if key in self._error_keys or len(self._errors) >= 32:
53
55
  return
56
+ values_re = self._redact_values_re
57
+ try:
58
+ message += " pid=%s" % os.getpid()
59
+ # Read only code locations; formatting exceptions or locals can
60
+ # execute application code or expose request data.
61
+ locations = []
62
+ tb = BaseException.__traceback__.__get__(error)
63
+ for _ in range(8):
64
+ if tb is None:
65
+ break
66
+ code = tb.tb_frame.f_code
67
+ # Redact before truncation so complete patterns still match.
68
+ # Bypass custom str-subclass methods in location metadata.
69
+ filename = redact_text(str.__str__(code.co_filename), values_re)[-256:]
70
+ function = redact_text(str.__str__(code.co_name), values_re)[:128]
71
+ locations.append("%r:%s in %r" % (
72
+ filename, tb.tb_lineno, function,
73
+ ))
74
+ tb = tb.tb_next
75
+ if tb is not None:
76
+ locations.append("...")
77
+ if locations:
78
+ message += " traceback=" + " -> ".join(locations)
79
+ except BaseException:
80
+ # Still record the original diagnostic if enrichment fails.
81
+ pass
82
+ with self.lock:
83
+ if key in self._error_keys or len(self._errors) >= 32:
84
+ return
85
+ self._error_keys.add(key)
54
86
  self._errors.append(message)
55
87
  try:
56
88
  logger.forceError(message)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hyperprobe-agent
3
- Version: 1.2.32b5
3
+ Version: 1.2.32b10
4
4
  Summary: Production-grade, non-breaking live debugger and telemetry agent for Python.
5
5
  Home-page: https://www.hyperprobe.co
6
6
  Author: Arif, Saksham, Karan
@@ -30,6 +30,7 @@ Requires-Dist: grpcio>=1.50.0; extra == "dev"
30
30
  Requires-Dist: grpcio-tools>=1.50.0; extra == "dev"
31
31
  Requires-Dist: protobuf>=4.21.0; extra == "dev"
32
32
  Requires-Dist: pytest>=7.0.0; extra == "dev"
33
+ Requires-Dist: wrapt<3,>=1.16; extra == "dev"
33
34
  Dynamic: author
34
35
  Dynamic: author-email
35
36
  Dynamic: classifier
@@ -36,8 +36,10 @@ hyperprobe_agent.egg-info/top_level.txt
36
36
  tests/test_agent.py
37
37
  tests/test_agent_backend_integration.py
38
38
  tests/test_bytecode_backend.py
39
+ tests/test_bytecode_discovery.py
39
40
  tests/test_bytecode_lifecycle.py
40
41
  tests/test_bytecode_token_lifecycle.py
42
+ tests/test_engine_diagnostics.py
41
43
  tests/test_engine_selection.py
42
44
  tests/test_evaluator.py
43
45
  tests/test_fork.py
@@ -17,3 +17,4 @@ grpcio>=1.50.0
17
17
  grpcio-tools>=1.50.0
18
18
  protobuf>=4.21.0
19
19
  pytest>=7.0.0
20
+ wrapt<3,>=1.16
@@ -7,7 +7,7 @@ long_description = (this_directory / "README.md").read_text() if (this_directory
7
7
 
8
8
  setup(
9
9
  name="hyperprobe-agent",
10
- version="1.2.32beta5",
10
+ version="1.2.32beta10",
11
11
  author="Arif, Saksham, Karan",
12
12
  author_email="arif@hypertest.co, saksham@hypertest.co, karan@hypertest.co",
13
13
  description="Production-grade, non-breaking live debugger and telemetry agent for Python.",
@@ -33,6 +33,7 @@ setup(
33
33
  "grpcio-tools>=1.50.0",
34
34
  "protobuf>=4.21.0",
35
35
  "pytest>=7.0.0",
36
+ "wrapt>=1.16,<3",
36
37
  ]
37
38
  },
38
39
  classifiers=[
@@ -0,0 +1,135 @@
1
+ import importlib
2
+ import sys
3
+ import weakref
4
+ from functools import wraps
5
+ from types import ModuleType
6
+
7
+ import pytest
8
+
9
+ from hyperprobe.core.bytecode.discovery import (
10
+ canonical_path,
11
+ functions_in_module,
12
+ loaded_modules_at,
13
+ )
14
+
15
+
16
+ def discover(module):
17
+ failures = []
18
+ functions = list(functions_in_module(module, lambda *error: failures.append(error)))
19
+ assert failures == []
20
+ return functions
21
+
22
+
23
+ def test_decorated_function_is_discovered_without_replacing_its_wrapper():
24
+ def target(value):
25
+ return value + 1
26
+
27
+ @wraps(target)
28
+ def wrapper(value):
29
+ return target(value)
30
+
31
+ module = ModuleType("discovery_decorated")
32
+ module.view = wrapper
33
+ assert {wrapper, target}.issubset(discover(module))
34
+ assert module.view is wrapper
35
+ assert module.view(41) == 42
36
+
37
+
38
+ def test_discovery_finds_instance_metadata_without_calling_metaclass_hooks():
39
+ calls = []
40
+
41
+ class Meta(type):
42
+ def __getattribute__(cls, name):
43
+ calls.append(name)
44
+ return type.__getattribute__(cls, name)
45
+
46
+ class Wrapper(metaclass=Meta):
47
+ def __init__(self, function):
48
+ self.__wrapped__ = function
49
+
50
+ def __call__(self, value):
51
+ return self.__wrapped__(value)
52
+
53
+ def target(value):
54
+ return value + 1
55
+
56
+ module = ModuleType("discovery_metaclass")
57
+ module.view = Wrapper(target)
58
+ calls.clear()
59
+ assert target in discover(module)
60
+ assert calls == []
61
+ assert module.view(41) == 42
62
+
63
+
64
+ def test_module_proxy_is_skipped_without_hiding_a_real_module(tmp_path, monkeypatch):
65
+ module = ModuleType("discovery_real_module")
66
+ module.__file__ = str(tmp_path / "views.py")
67
+ monkeypatch.setitem(sys.modules, module.__name__, module)
68
+ monkeypatch.setitem(sys.modules, "discovery_module_proxy", weakref.proxy(module))
69
+ failures = []
70
+ path = canonical_path(module.__file__)
71
+ assert loaded_modules_at({path}, lambda *error: failures.append(error)) == {path: [module]}
72
+ assert failures == []
73
+
74
+
75
+ @pytest.fixture
76
+ def vendored_native_wrapt(monkeypatch):
77
+ native = pytest.importorskip("wrapt._wrappers")
78
+ monkeypatch.setitem(sys.modules, "discovery_vendor.wrapt._wrappers", native)
79
+ # The native proxy is available only under the vendor's package name.
80
+ for name in ("wrapt", "wrapt._wrappers", "wrapt.wrappers"):
81
+ monkeypatch.delitem(sys.modules, name, raising=False)
82
+ return native
83
+
84
+
85
+ @pytest.mark.parametrize("shadowed", [False, True])
86
+ def test_vendored_native_proxy_never_calls_application_getters(vendored_native_wrapt, shadowed):
87
+ calls = []
88
+
89
+ class Target:
90
+ @property
91
+ def __dict__(self):
92
+ calls.append("target dictionary")
93
+ return {}
94
+
95
+ def __call__(self):
96
+ return 42
97
+
98
+ native = vendored_native_wrapt
99
+ target = Target()
100
+ if shadowed:
101
+ class Proxy(native.CallableObjectProxy):
102
+ @property
103
+ def __wrapped__(self):
104
+ calls.append("shadowed wrapped property")
105
+ return target
106
+ proxy = Proxy(target)
107
+ else:
108
+ proxy = native.FunctionWrapper(target, lambda wrapped, instance, args, kwargs: wrapped(*args, **kwargs))
109
+ module = ModuleType("discovery_vendored")
110
+ module.proxy = proxy
111
+ module.visible = lambda: 42
112
+ calls.clear()
113
+ assert module.visible in discover(module)
114
+ assert calls == []
115
+
116
+
117
+ @pytest.mark.parametrize("wrapper_module", ["wrapt", "wrapt.wrappers"])
118
+ @pytest.mark.parametrize("bound", [False, True])
119
+ def test_supported_native_and_python_wrappers_keep_the_original_function(wrapper_module, bound):
120
+ wrapper_class = importlib.import_module(wrapper_module).FunctionWrapper
121
+
122
+ if bound:
123
+ class View:
124
+ def method(self, value):
125
+ return value + 1
126
+ target = View.method
127
+ else:
128
+ def target(value):
129
+ return value + 1
130
+
131
+ wrapper = wrapper_class(target, lambda wrapped, instance, args, kwargs: wrapped(*args, **kwargs))
132
+ module = ModuleType("discovery_supported_wrapper")
133
+ module.view = wrapper.__get__(View(), View) if bound else wrapper
134
+ assert target in discover(module)
135
+ assert module.view(41) == 42
@@ -0,0 +1,119 @@
1
+ import re
2
+ from types import CodeType
3
+
4
+ import pytest
5
+
6
+ from hyperprobe.core.engine_base import EngineBase
7
+ from hyperprobe.core.quota import QuotaManager
8
+ from hyperprobe.core.safety import SafetyMonitor
9
+
10
+
11
+ @pytest.fixture
12
+ def engine():
13
+ return EngineBase(QuotaManager(1000), SafetyMonitor(lambda *_: None), lambda event: None)
14
+
15
+
16
+ def record_at(engine, filename, function_name="generated", operation="condition evaluation"):
17
+ def fail():
18
+ raise ValueError("private exception message")
19
+
20
+ code = fail.__code__
21
+ if hasattr(code, "replace"):
22
+ fail.__code__ = code.replace(co_filename=filename, co_name=function_name)
23
+ else: # CPython 3.7 has no CodeType.replace().
24
+ fail.__code__ = CodeType(
25
+ code.co_argcount, code.co_kwonlyargcount, code.co_nlocals,
26
+ code.co_stacksize, code.co_flags, code.co_code, code.co_consts,
27
+ code.co_names, code.co_varnames, filename, function_name,
28
+ code.co_firstlineno, code.co_lnotab, code.co_freevars, code.co_cellvars,
29
+ )
30
+ try:
31
+ fail()
32
+ except ValueError as error:
33
+ engine._record_failure(operation, error)
34
+
35
+
36
+ @pytest.mark.parametrize("field", ["filename", "function"])
37
+ def test_traceback_locations_are_redacted_before_truncation(engine, capsys, field):
38
+ secret = "start-" + "x" * 300 + "-PRIVATE.py" if field == "filename" else "PRIVATE-" + "x" * 140 + "-end"
39
+ engine.set_global_config({"redact_values": ["^" + re.escape(secret) + "$"]})
40
+ record_at(engine, secret if field == "filename" else "generated.py",
41
+ secret if field == "function" else "generated")
42
+ printed = capsys.readouterr().err
43
+ assert len(engine.errors) == 1
44
+ for text in (engine.errors[0], printed):
45
+ assert "PRIVATE" not in text
46
+ assert "private exception message" not in text
47
+ assert "[REDACTED Value]" in text
48
+ assert "traceback=" in text
49
+
50
+
51
+ @pytest.mark.parametrize("redaction", [False, True])
52
+ def test_traceback_string_subclasses_do_not_execute_application_methods(engine, capsys, redaction):
53
+ calls = []
54
+
55
+ class Location(str):
56
+ def __str__(self):
57
+ calls.append("str")
58
+ raise AssertionError("application string method")
59
+
60
+ def __repr__(self):
61
+ calls.append("repr")
62
+ raise AssertionError("application string method")
63
+
64
+ def __len__(self):
65
+ calls.append("len")
66
+ raise AssertionError("application string method")
67
+
68
+ def __getitem__(self, key):
69
+ calls.append("getitem")
70
+ raise AssertionError("application string method")
71
+
72
+ if redaction:
73
+ engine.set_global_config({"redact_values": ["secret"]})
74
+ record_at(engine, Location("generated-secret.py"), Location("generated_secret"))
75
+ assert calls == []
76
+ assert len(engine.errors) == 1
77
+ for text in (engine.errors[0], capsys.readouterr().err):
78
+ assert "traceback=" in text
79
+ if redaction:
80
+ assert "secret" not in text
81
+ assert "[REDACTED Value]" in text
82
+ else:
83
+ assert "generated-secret.py" in text
84
+ assert "generated_secret" in text
85
+
86
+
87
+ def test_repeated_locations_do_not_hide_a_later_delivery_failure(engine, capsys):
88
+ for index in range(32):
89
+ record_at(engine, "condition_%s.py" % index)
90
+
91
+ def fail_delivery(event):
92
+ raise RuntimeError("private delivery message")
93
+
94
+ engine._capture_sink = fail_delivery
95
+ assert not engine._emit_capture({"probe_id": "later"}, engine._generation)
96
+ printed = capsys.readouterr().err
97
+ assert len(engine.errors) == 2
98
+ assert printed.count("condition evaluation failed (ValueError)") == 1
99
+ assert printed.count("capture delivery failed (RuntimeError)") == 1
100
+ assert any("capture delivery failed (RuntimeError)" in error for error in engine.errors)
101
+
102
+
103
+ def test_distinct_failure_categories_still_have_a_bounded_log(engine, capsys):
104
+ for index in range(40):
105
+ engine._record_failure("operation_%s" % index, ValueError())
106
+ assert len(engine.errors) == 32
107
+ assert capsys.readouterr().err.count("[HyperProbe]") == 32
108
+
109
+
110
+ @pytest.mark.parametrize("failure", [OSError("closed stream"), KeyboardInterrupt()])
111
+ def test_broken_logger_keeps_the_in_memory_diagnostic(engine, monkeypatch, failure):
112
+ def broken_logger(message):
113
+ raise failure
114
+
115
+ monkeypatch.setattr("hyperprobe.core.engine_base.logger.forceError", broken_logger)
116
+ record_at(engine, "generated.py")
117
+ assert len(engine.errors) == 1
118
+ assert "generated.py" in engine.errors[0]
119
+ assert "condition evaluation failed (ValueError)" in engine.errors[0]
@@ -1,71 +0,0 @@
1
- """Targeted module lookup; no heap scan and no implicit application imports."""
2
-
3
- import os
4
- import sys
5
- from types import FunctionType, MethodType, ModuleType
6
-
7
-
8
- def canonical_path(path):
9
- return os.path.abspath(os.path.realpath(path))
10
-
11
-
12
- def loaded_modules_at(paths, report):
13
- matches = {path: [] for path in paths}
14
- if not matches:
15
- return matches
16
- basenames = {os.path.basename(path) for path in matches}
17
- for module in tuple(sys.modules.values()):
18
- if not isinstance(module, ModuleType):
19
- continue
20
- try:
21
- namespace = ModuleType.__getattribute__(module, "__dict__")
22
- filename = namespace.get("__file__")
23
- if not isinstance(filename, str):
24
- filename = getattr(namespace.get("__spec__"), "origin", None)
25
- if not isinstance(filename, str) or os.path.basename(filename) not in basenames:
26
- continue
27
- path = canonical_path(filename)
28
- if path in matches:
29
- matches[path].append(module)
30
- except BaseException as error:
31
- report("module inspection", error)
32
- return matches
33
-
34
-
35
- def functions_in_module(module, report):
36
- seen_functions, seen_classes, seen_containers = set(), set(), set()
37
-
38
- def walk(value, depth=0):
39
- try:
40
- if type(value) is FunctionType:
41
- if id(value) not in seen_functions:
42
- seen_functions.add(id(value))
43
- yield value
44
- elif isinstance(value, (MethodType, staticmethod, classmethod)):
45
- yield from walk(value.__func__, depth)
46
- elif isinstance(value, property):
47
- for accessor in (value.fget, value.fset, value.fdel):
48
- if accessor is not None:
49
- yield from walk(accessor, depth)
50
- elif isinstance(value, type) and id(value) not in seen_classes:
51
- if type.__getattribute__(value, "__module__") != module.__name__:
52
- return
53
- seen_classes.add(id(value))
54
- for member in tuple(type.__getattribute__(value, "__dict__").values()):
55
- yield from walk(member, depth + 1)
56
- elif depth < 2 and id(value) not in seen_containers:
57
- if type(value) in (tuple, list, set, frozenset) and len(value) <= 64:
58
- seen_containers.add(id(value))
59
- for member in tuple(value):
60
- yield from walk(member, depth + 1)
61
- elif type(value) is dict and len(value) <= 64:
62
- seen_containers.add(id(value))
63
- for member in tuple(value.values()):
64
- yield from walk(member, depth + 1)
65
- except GeneratorExit:
66
- raise
67
- except BaseException as error:
68
- report("function discovery", error)
69
-
70
- for value in tuple(ModuleType.__getattribute__(module, "__dict__").values()):
71
- yield from walk(value)