runtimeconditions-profiler 0.5.0__py3-none-any.whl

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.
@@ -0,0 +1,2 @@
1
+ """Runtime Conditions Python profiler."""
2
+
@@ -0,0 +1,128 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import sys
7
+ import tempfile
8
+ from importlib import metadata
9
+ from pathlib import Path
10
+
11
+ from .errors import RuntimeConditionsError
12
+ from .profile.writer import ProfileYamlWriter
13
+ from .project.installed import InstalledBindingDiscovery
14
+ from .project.verify import InstalledBindingVerifier, VerifiedBindingSet
15
+ from .profile.generated import GeneratedBindingExtractor
16
+ from .profile.semantic import CORE_VERSION, GeneratedProfileValidator
17
+
18
+ NAME = "runtimeconditions-python-profiler"
19
+ COMMANDS = ("generate", "verify-bindings")
20
+
21
+
22
+ def version() -> str:
23
+ try:
24
+ return metadata.version("runtimeconditions-profiler")
25
+ except metadata.PackageNotFoundError:
26
+ return "0.0.0+unknown"
27
+
28
+
29
+ def main(argv: list[str] | None = None) -> int:
30
+ argv = list(sys.argv[1:] if argv is None else argv)
31
+ if argv[:1] == ["--version"]:
32
+ # The rc command asks for this to see which core profile schema the add-on emits.
33
+ if "--json" in argv[1:]:
34
+ print(json.dumps({"name": NAME, "version": version(), "coreSchemas": [CORE_VERSION]}, separators=(",", ":")))
35
+ else:
36
+ print(version())
37
+ return 0
38
+ if argv[:1] and argv[0] in COMMANDS:
39
+ # The profile prefix is optional, so rc can pass the subcommand straight through.
40
+ argv = ["profile", *argv]
41
+ parser = argparse.ArgumentParser(prog=NAME)
42
+ subparsers = parser.add_subparsers(dest="command", required=True)
43
+
44
+ profile = subparsers.add_parser("profile")
45
+ profile_commands = profile.add_subparsers(dest="profile_command", required=True)
46
+ profile_generate = profile_commands.add_parser("generate")
47
+ profile_generate.add_argument("--project", default=".")
48
+ profile_generate.add_argument("--name", required=True)
49
+ profile_generate.add_argument("--workload-uri", required=True)
50
+ profile_generate.add_argument("--workload-version")
51
+ profile_generate.add_argument("--out")
52
+ profile_verify = profile_commands.add_parser(
53
+ "verify-bindings",
54
+ help="verify installed generated bindings without running application or binding code",
55
+ )
56
+ profile_verify.add_argument("--project", default=".")
57
+ profile_verify.add_argument("--json", action="store_true")
58
+
59
+ args = parser.parse_args(argv)
60
+ command = args.command
61
+ try:
62
+ if command == "profile" and args.profile_command == "generate":
63
+ return run_profile_generate(args)
64
+ if command == "profile" and args.profile_command == "verify-bindings":
65
+ return run_profile_verify_bindings(args)
66
+ except RuntimeConditionsError as exc:
67
+ print(f"runtimeconditions: {exc}", file=sys.stderr)
68
+ return 1
69
+ return 0
70
+
71
+
72
+ def run_profile_generate(args: argparse.Namespace) -> int:
73
+ verified = verified_installed_bindings(Path(args.project))
74
+ extracted = GeneratedBindingExtractor(verified).extract(Path(args.project))
75
+ profile = GeneratedProfileValidator(verified).build(
76
+ extracted, args.name, args.workload_uri, args.workload_version,
77
+ )
78
+ yaml_text = ProfileYamlWriter.write(profile)
79
+ if args.out:
80
+ destination = Path(args.out)
81
+ temporary: Path | None = None
82
+ try:
83
+ descriptor, name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent)
84
+ temporary = Path(name)
85
+ with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
86
+ stream.write(yaml_text)
87
+ stream.flush()
88
+ os.fsync(stream.fileno())
89
+ os.replace(temporary, destination)
90
+ except OSError as exc:
91
+ raise RuntimeConditionsError(f"cannot write profile {destination}: {exc}") from exc
92
+ finally:
93
+ if temporary is not None:
94
+ temporary.unlink(missing_ok=True)
95
+ else:
96
+ print(yaml_text, end="")
97
+ return 0
98
+
99
+
100
+ def verified_installed_bindings(project: Path) -> VerifiedBindingSet:
101
+ discovery = InstalledBindingDiscovery().discover(project)
102
+ return InstalledBindingVerifier().verify(discovery)
103
+
104
+
105
+ def run_profile_verify_bindings(args: argparse.Namespace) -> int:
106
+ verified = verified_installed_bindings(Path(args.project))
107
+ direct = {item.installed.distribution for item in verified.imported_packages}
108
+ packages = [
109
+ {
110
+ "distribution": item.installed.distribution,
111
+ "direct": item.installed.distribution in direct,
112
+ "version": item.installed.version,
113
+ "importPackage": item.installed.import_package,
114
+ "extensionId": item.model["rootExtension"]["id"],
115
+ "extensionVersion": item.model["rootExtension"]["version"],
116
+ "modelSha256": item.model["metadata"]["semanticSha256"],
117
+ }
118
+ for item in verified.packages
119
+ ]
120
+ if args.json:
121
+ print(json.dumps({"packages": packages}, sort_keys=True))
122
+ else:
123
+ for item in packages:
124
+ marker = "" if item["direct"] else " (dependency)"
125
+ print(f"verified {item['distribution']}=={item['version']} ({item['importPackage']}){marker}")
126
+ return 0
127
+
128
+
@@ -0,0 +1 @@
1
+ API_VERSION = "runtimeconditions.io/v1alpha1"
@@ -0,0 +1,3 @@
1
+ class RuntimeConditionsError(Exception):
2
+ pass
3
+
File without changes
@@ -0,0 +1,51 @@
1
+ """Helpers for exact extension release references and metadata."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ from ..errors import RuntimeConditionsError
7
+
8
+
9
+ def parse_identifier(reference: object) -> tuple[str, str]:
10
+ """Read extension metadata or a string reference as (id, optional version)."""
11
+ if isinstance(reference, str) and reference:
12
+ marker = reference.rfind(":")
13
+ scheme_end = reference.find("://")
14
+ if marker > 0 and marker > scheme_end + 2 and marker > reference.rfind("/"):
15
+ if marker == len(reference) - 1:
16
+ raise RuntimeConditionsError("extension reference version suffix must be non-empty")
17
+ return reference[:marker], reference[marker + 1 :]
18
+ return reference, ""
19
+ if not isinstance(reference, dict):
20
+ raise RuntimeConditionsError("extension reference requires a non-empty string")
21
+ identifier, version = reference.get("id"), reference.get("version", "")
22
+ if not isinstance(identifier, str) or not identifier or ("version" in reference and (not isinstance(version, str) or not version)) or "uri" in reference:
23
+ raise RuntimeConditionsError("extension metadata requires id and an optional string version; metadata.uri is unsupported")
24
+ return identifier, version or ""
25
+
26
+
27
+ EXTENSION_FILENAME = "runtimeconditions.extension.yaml"
28
+
29
+
30
+ def short_identifier(identifier: str, version: str) -> str:
31
+ """Drop the /<version>/runtimeconditions.extension.yaml tail of an https extension id.
32
+
33
+ Ids that are not https URLs, or that do not end that way, stay unchanged.
34
+ """
35
+ tail = f"/{version}/{EXTENSION_FILENAME}"
36
+ if version and identifier.startswith("https://") and identifier.endswith(tail):
37
+ return identifier[: -len(tail)]
38
+ return identifier
39
+
40
+
41
+ def profile_reference(reference: tuple[str, str]) -> str:
42
+ """Serialize an extension reference for a Runtime Conditions Profile as <short-url>:<version>."""
43
+ identifier, version = reference
44
+ short = short_identifier(identifier, version)
45
+ return f"{short}:{version}" if version else short
46
+
47
+
48
+ def definition_identifier(metadata: dict[str, object]) -> str:
49
+ """Return the ID declared by valid extension metadata."""
50
+ return parse_identifier(metadata)[0]
51
+
@@ -0,0 +1,3 @@
1
+ from .writer import ProfileYamlWriter
2
+
3
+ __all__ = ["ProfileYamlWriter"]
@@ -0,0 +1,314 @@
1
+ """Coordinate-driven extraction from verified, installed Python bindings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from ..errors import RuntimeConditionsError
11
+ from ..extension.identity import parse_identifier
12
+ from ..project.verify import VerifiedBindingPackage, VerifiedBindingSet, resolve_marker_declaration
13
+ from .static_values import NativeSymbol, SourceCall, StaticCall, StaticProject
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class ExtractedCondition:
18
+ source: Path
19
+ line: int
20
+ column: int
21
+ condition: dict[str, Any]
22
+ direct_extensions: tuple[tuple[str, str], ...]
23
+ structural_fallbacks: tuple[str, ...] = ()
24
+
25
+
26
+ class StructuralError(ValueError):
27
+ def __init__(self, coordinate: str, message: str) -> None:
28
+ self.coordinate = coordinate
29
+ super().__init__(message)
30
+
31
+
32
+ def _coordinate(item: dict[str, Any]) -> str:
33
+ ref = item.get("modelRef", item)
34
+ return ref["coordinate"] + ref.get("jsonPointer", "")
35
+
36
+
37
+ def _native(symbol: Any) -> tuple[str, str] | None:
38
+ if not isinstance(symbol, NativeSymbol):
39
+ return None
40
+ path = symbol.path[1:] if symbol.path[:1] == ("bindings",) else symbol.path
41
+ if len(path) != 1:
42
+ return None
43
+ return symbol.package, path[0]
44
+
45
+
46
+ def _json_value(value: Any, coordinate: str) -> Any:
47
+ if value is None or type(value) in (str, bool, int):
48
+ return value
49
+ if type(value) is float and math.isfinite(value):
50
+ return value
51
+ if isinstance(value, list):
52
+ return [_json_value(item, coordinate) for item in value]
53
+ if isinstance(value, dict) and all(isinstance(key, str) for key in value):
54
+ return {key: _json_value(item, coordinate) for key, item in value.items()}
55
+ raise StructuralError(coordinate, "value is not static JSON data")
56
+
57
+
58
+ class GeneratedBindingExtractor:
59
+ def __init__(self, verified: VerifiedBindingSet) -> None:
60
+ self.verified = verified
61
+ self.packages = {item.installed.import_package: item for item in verified.packages}
62
+ self.declarations: dict[tuple[str, str], tuple[VerifiedBindingPackage, dict[str, Any]]] = {}
63
+ self.types: dict[str, dict[str, dict[str, Any]]] = {}
64
+ self.roots: list[tuple[VerifiedBindingPackage, dict[str, Any]]] = []
65
+ self._structural_fallbacks: set[str] = set()
66
+ for package in verified.packages:
67
+ root = package.installed.import_package
68
+ self.types[root] = {item["nativeName"]: item for item in package.manifest["types"]}
69
+ for declaration in package.manifest["declarations"]:
70
+ key = (root, declaration["function"])
71
+ if key in self.declarations:
72
+ raise RuntimeConditionsError(f"duplicate declaration symbol {root}.{key[1]}")
73
+ self.declarations[key] = (package, declaration)
74
+ for contract in package.manifest.get("importedMarkerContracts", []):
75
+ provider, declaration = resolve_marker_declaration(
76
+ contract, verified.packages,
77
+ {parse_identifier(item) for item in package.model["extensions"]},
78
+ )
79
+ key = (root, declaration["function"])
80
+ if key in self.declarations:
81
+ raise RuntimeConditionsError(f"duplicate declaration symbol {root}.{key[1]}")
82
+ self.declarations[key] = (provider, declaration)
83
+ self.roots.extend((package, item) for item in package.manifest["rootBindings"])
84
+
85
+ def extract(self, project_root: Path) -> tuple[ExtractedCondition, ...]:
86
+ project = StaticProject(project_root, set(self.packages))
87
+ result: list[ExtractedCondition] = []
88
+ for site in project.calls:
89
+ candidate = project.maybe_native(site.node.func, site.environment)
90
+ key = _native(candidate)
91
+ if key not in self.declarations:
92
+ continue
93
+ package, declaration = self.declarations[key]
94
+ coordinate = _coordinate(declaration)
95
+ symbol = f"{key[0]}.{key[1]}"
96
+ try:
97
+ if site.dynamic:
98
+ raise StructuralError(coordinate, "declaration appears under dynamic control flow")
99
+ value = project.evaluate(site.node, site.environment)
100
+ if not isinstance(value, StaticCall) or value.callee != candidate:
101
+ raise StructuralError(coordinate, "declaration symbol is ambiguous or rebound")
102
+ self._structural_fallbacks = set()
103
+ result.append(self._condition(site, package, declaration, value))
104
+ except (ValueError, RecursionError) as exc:
105
+ detail = f"{exc.coordinate}: {exc}" if isinstance(exc, StructuralError) else f"{coordinate}: {exc}"
106
+ raise RuntimeConditionsError(f"{site.location}: {symbol}: {detail}") from exc
107
+ return tuple(result)
108
+
109
+ def _condition(
110
+ self, site: SourceCall, package: VerifiedBindingPackage,
111
+ declaration: dict[str, Any], call: StaticCall,
112
+ ) -> ExtractedCondition:
113
+ coordinate = _coordinate(declaration)
114
+ if call.kwargs:
115
+ raise StructuralError(coordinate, "declaration accepts positional field objects only")
116
+ condition: dict[str, Any] = {"kind": declaration["sourceName"]}
117
+ contributing = {parse_identifier(package.model["rootExtension"])}
118
+ selected_interface: str | None = None
119
+ for argument in call.args:
120
+ if not isinstance(argument, StaticCall):
121
+ raise StructuralError(coordinate, "declaration argument is not a generated field object")
122
+ native = _native(argument.callee)
123
+ if native is None or native[0] not in self.types:
124
+ raise StructuralError(coordinate, "declaration argument has no verified binding type")
125
+ field_type = self.types[native[0]].get(native[1])
126
+ if field_type is None:
127
+ raise StructuralError(coordinate, f"unresolved generated field type {native[0]}.{native[1]}")
128
+ edges = [
129
+ (owner, edge)
130
+ for owner, edge in self.roots
131
+ if owner.installed.import_package == native[0]
132
+ and edge["declarationCoordinate"] == declaration["modelRef"]["coordinate"]
133
+ and edge["value"] == {"type": native[1]}
134
+ and edge["scope"]["kind"] == declaration["sourceName"]
135
+ ]
136
+ if not edges:
137
+ raise StructuralError(_coordinate(field_type), "field has no root binding for this declaration")
138
+ if len(edges) != 1:
139
+ raise StructuralError(_coordinate(field_type), "field has ambiguous root bindings")
140
+ owner, edge = edges[0]
141
+ implements = field_type.get("implements", [])
142
+ if not any(item["declarationCoordinate"] == edge["declarationCoordinate"] for item in implements):
143
+ raise StructuralError(_coordinate(field_type), "field does not implement the declaration marker")
144
+ interface = edge["scope"].get("interfaceType")
145
+ if selected_interface is not None and interface is not None and interface != selected_interface:
146
+ raise StructuralError(_coordinate(edge), "fields have conflicting interface scopes")
147
+ selected_interface = interface or selected_interface
148
+ value = self._serialize_type(argument, owner, field_type, _coordinate(edge), set())
149
+ if edge["role"] == "interface":
150
+ if not isinstance(value, dict):
151
+ raise StructuralError(_coordinate(edge), "interface value must be an object")
152
+ if "type" in value and value["type"] != edge["fixedInterfaceType"]:
153
+ raise StructuralError(_coordinate(edge), "interface type conflicts with fixed scope")
154
+ value = {"type": edge["fixedInterfaceType"], **value}
155
+ self._put_path(condition, edge["path"], value, _coordinate(edge))
156
+ contributing.add(parse_identifier(owner.model["rootExtension"]))
157
+ if selected_interface is not None:
158
+ current = condition.get("interface")
159
+ if current is None:
160
+ condition["interface"] = {"type": selected_interface}
161
+ elif not isinstance(current, dict) or current.get("type") != selected_interface:
162
+ raise StructuralError(coordinate, "interface conflicts with field scope")
163
+ return ExtractedCondition(
164
+ site.source, site.node.lineno, site.node.col_offset + 1,
165
+ condition, tuple(sorted(contributing)), tuple(sorted(self._structural_fallbacks)),
166
+ )
167
+
168
+ @staticmethod
169
+ def _put_path(condition: dict[str, Any], path: list[dict[str, Any]], value: Any, coordinate: str) -> None:
170
+ current = condition
171
+ for segment in path[:-1]:
172
+ if segment.get("array"):
173
+ raise StructuralError(coordinate, "array-valued root path is ambiguous")
174
+ name = segment["name"]
175
+ existing = current.setdefault(name, {})
176
+ if not isinstance(existing, dict):
177
+ raise StructuralError(coordinate, f"root path {name!r} conflicts with another field")
178
+ current = existing
179
+ final = path[-1]
180
+ if final.get("array"):
181
+ raise StructuralError(coordinate, "array-valued root path is ambiguous")
182
+ name = final["name"]
183
+ if name in current:
184
+ raise StructuralError(coordinate, f"duplicate serialized field {name!r}")
185
+ current[name] = value
186
+
187
+ def _serialize_reference(
188
+ self, value: Any, package: VerifiedBindingPackage,
189
+ reference: dict[str, Any], coordinate: str, active: set[tuple[int, int]],
190
+ ) -> Any:
191
+ if value is None and reference.get("nullable"):
192
+ return None
193
+ if "type" in reference:
194
+ named = self.types[package.installed.import_package].get(reference["type"])
195
+ if named is None:
196
+ raise StructuralError(coordinate, f"unresolved native type {reference['type']}")
197
+ return self._serialize_type(value, package, named, coordinate, active)
198
+ builtin = reference["builtin"]
199
+ if builtin in ("any", "JSONValue"):
200
+ return _json_value(value, coordinate)
201
+ expected = {"str": str, "string": str, "bool": bool, "int": int, "int64": int,
202
+ "float": (float, int), "float64": (float, int), "None": type(None), "struct{}": type(None)}[builtin]
203
+ if not isinstance(value, expected) or (builtin in ("int", "int64", "float", "float64") and isinstance(value, bool)):
204
+ raise StructuralError(coordinate, f"expected {builtin} value")
205
+ if isinstance(value, float) and not math.isfinite(value):
206
+ raise StructuralError(coordinate, "non-finite number is not serializable")
207
+ return value
208
+
209
+ def _serialize_type(
210
+ self, value: Any, package: VerifiedBindingPackage,
211
+ named: dict[str, Any], coordinate: str, active: set[tuple[int, int]],
212
+ ) -> Any:
213
+ token = (id(value), id(named))
214
+ if token in active:
215
+ raise StructuralError(coordinate, "cyclic structural value")
216
+ if len(active) >= 256:
217
+ raise StructuralError(coordinate, "structural value exceeds nesting limit")
218
+ active.add(token)
219
+ try:
220
+ return self._serialize_type_body(value, package, named, coordinate, active)
221
+ finally:
222
+ active.remove(token)
223
+
224
+ def _serialize_type_body(
225
+ self, value: Any, package: VerifiedBindingPackage,
226
+ named: dict[str, Any], coordinate: str, active: set[tuple[int, int]],
227
+ ) -> Any:
228
+ kind = named["construct"]
229
+ name = named["nativeName"]
230
+ package_name = package.installed.import_package
231
+ if kind == "scalar":
232
+ members = named.get("members", [])
233
+ if members:
234
+ symbol = value if isinstance(value, NativeSymbol) else None
235
+ path = symbol.path[1:] if symbol and symbol.path[:1] == ("bindings",) else symbol.path if symbol else ()
236
+ if symbol is None or symbol.package != package_name or len(path) != 2 or path[0] != name:
237
+ if isinstance(value, str):
238
+ self._structural_fallbacks.add(coordinate)
239
+ return value
240
+ if symbol is not None and len(path) == 2:
241
+ other_type = self.types.get(symbol.package, {}).get(path[0])
242
+ if other_type is not None and other_type["construct"] == "scalar":
243
+ other_member = next(
244
+ (item for item in other_type.get("members", []) if item["nativeName"] == path[1]),
245
+ None,
246
+ )
247
+ if other_member is not None:
248
+ self._structural_fallbacks.add(coordinate)
249
+ return other_member["value"]
250
+ raise StructuralError(coordinate, f"expected {package_name}.{name} enum member")
251
+ member = next((item for item in members if item["nativeName"] == path[1]), None)
252
+ if member is None:
253
+ raise StructuralError(coordinate, f"unknown {name} enum member {path[1]}")
254
+ return member["value"]
255
+ return self._serialize_reference(value, package, {"builtin": named["underlying"]}, coordinate, active)
256
+ if kind in ("object", "wrapper"):
257
+ if not isinstance(value, StaticCall) or _native(value.callee) != (package_name, name):
258
+ raise StructuralError(coordinate, f"expected {package_name}.{name} keyword-only constructor")
259
+ if value.args:
260
+ raise StructuralError(coordinate, f"{name} constructor is keyword-only")
261
+ fields = {item["nativeName"]: item for item in named["fields"]}
262
+ unknown = set(value.kwargs) - set(fields)
263
+ if unknown:
264
+ raise StructuralError(coordinate, f"unknown {name} field {sorted(unknown)[0]}")
265
+ result: dict[str, Any] = {}
266
+ for native_name, field in fields.items():
267
+ if native_name not in value.kwargs:
268
+ if field["required"]:
269
+ raise StructuralError(_coordinate(field), f"missing required field {native_name}")
270
+ continue
271
+ item = value.kwargs[native_name]
272
+ if item is None and not field["required"]:
273
+ if not field["value"].get("nullable"):
274
+ raise StructuralError(_coordinate(field), f"field {native_name} cannot be None")
275
+ continue
276
+ result[field["sourceName"]] = self._serialize_reference(
277
+ item, package, field["value"], _coordinate(field), active,
278
+ )
279
+ if kind == "wrapper":
280
+ if len(fields) != 1 or len(result) != 1:
281
+ raise StructuralError(coordinate, f"{name} wrapper must provide one value")
282
+ return next(iter(result.values()))
283
+ return result
284
+ if kind == "collection":
285
+ if not isinstance(value, list):
286
+ raise StructuralError(coordinate, f"expected sequence for {name}")
287
+ edge = named["element"]
288
+ return [self._serialize_reference(item, package, edge["value"], _coordinate(edge), active) for item in value]
289
+ if kind == "map":
290
+ if not isinstance(value, dict):
291
+ raise StructuralError(coordinate, f"expected map for {name}")
292
+ edge = named["element"]
293
+ return {key: self._serialize_reference(item, package, edge["value"], _coordinate(edge), active)
294
+ for key, item in value.items()}
295
+ if kind == "union":
296
+ successes: list[Any] = []
297
+ for variant in named["variants"]:
298
+ try:
299
+ successes.append(self._serialize_reference(
300
+ value, package, variant["value"], _coordinate(variant), active,
301
+ ))
302
+ except StructuralError:
303
+ continue
304
+ if not successes:
305
+ if value is None or type(value) in (str, bool, int, float, list, dict):
306
+ self._structural_fallbacks.add(coordinate)
307
+ return _json_value(value, coordinate)
308
+ raise StructuralError(coordinate, f"no structural variant of {name} accepts value")
309
+ if len(successes) > 1:
310
+ raise StructuralError(coordinate, f"ambiguous structural variants of {name}")
311
+ return successes[0]
312
+ if kind == "any":
313
+ return _json_value(value, coordinate)
314
+ raise StructuralError(coordinate, f"unsupported structural construct {kind}")