runhpc 0.1.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.
runhpc/cli.py ADDED
@@ -0,0 +1,37 @@
1
+ """Command-line entry point for runhpc."""
2
+
3
+ import argparse
4
+ import json
5
+ import logging
6
+ import sys
7
+ from collections.abc import Sequence
8
+ from contextlib import redirect_stdout
9
+
10
+ from runhpc.doctor import run_doctor
11
+ from runhpc.logger import Logger
12
+
13
+
14
+ def main(argv: Sequence[str] | None = None) -> int:
15
+ """Run doctor and optionally write its JSON document to stdout."""
16
+ parser = argparse.ArgumentParser(prog="runhpc")
17
+ commands = parser.add_subparsers(required=True)
18
+ doctor_parser = commands.add_parser("doctor", help="Check the runtime environment.")
19
+ doctor_parser.add_argument(
20
+ "--json",
21
+ action="store_true",
22
+ help="Print the complete report as JSON to stdout.",
23
+ )
24
+ arguments = parser.parse_args(argv)
25
+
26
+ logger = Logger(
27
+ level=logging.DEBUG if arguments.json else logging.INFO, stream=sys.stderr
28
+ )
29
+ try:
30
+ with redirect_stdout(sys.stderr):
31
+ report = run_doctor(logger=logger, terminal_stream=sys.stderr)
32
+ except (OSError, ValueError) as error:
33
+ logger.error("%s", error)
34
+ return 1
35
+ if arguments.json:
36
+ print(json.dumps(report, indent=2))
37
+ return 0
runhpc/config.py ADDED
@@ -0,0 +1,495 @@
1
+ """Strict TOML configuration reading with optional reproduction records."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from collections.abc import Callable, Mapping
7
+ from dataclasses import MISSING, fields, is_dataclass
8
+ from datetime import date, datetime, time
9
+ from pathlib import Path
10
+ from types import UnionType
11
+ from typing import (
12
+ Any,
13
+ Literal,
14
+ TypeVar,
15
+ Union,
16
+ cast,
17
+ get_args,
18
+ get_origin,
19
+ get_type_hints,
20
+ )
21
+
22
+ import tomli_w
23
+
24
+ from runhpc.logger import Logger
25
+ from runhpc.logger import logger as default_logger
26
+
27
+ Configuration = TypeVar("Configuration")
28
+
29
+
30
+ def read_config(
31
+ configuration_classes: Mapping[str, type[Any]],
32
+ path: Path | str,
33
+ *,
34
+ write_config: bool = False,
35
+ run_result_directory: Path | str | None = None,
36
+ output_directory: Path | str | None = None,
37
+ logger: Logger | None = None,
38
+ ) -> dict[str, Any]:
39
+ """Read named dataclass configurations without requiring a ConfigReader.
40
+
41
+ Do not mutate the supplied section-to-class mapping. Return fresh dataclass
42
+ instances; log omitted fields using the supplied logger or package logger.
43
+ Write records only when requested, defaulting to <run_result_directory>/configs
44
+ unless output_directory is supplied. Reading alone needs no output location.
45
+ """
46
+ source_path = Path(path)
47
+ log = logger if logger is not None else default_logger
48
+ destination = None
49
+ if write_config:
50
+ if output_directory is not None:
51
+ destination = Path(output_directory)
52
+ elif run_result_directory is not None:
53
+ destination = Path(run_result_directory) / "configs"
54
+ else:
55
+ raise ValueError(
56
+ "Writing configurations requires a run_result_directory or output_directory."
57
+ )
58
+
59
+ for section_name, configuration_class in configuration_classes.items():
60
+ _validate_configuration_dataclass(
61
+ configuration_class, section_name=section_name
62
+ )
63
+
64
+ original_contents = source_path.read_bytes()
65
+ try:
66
+ parsed = tomllib.loads(original_contents.decode("utf-8"))
67
+ except (ValueError, UnicodeError) as error:
68
+ raise ValueError(f"{source_path}: {error}") from error
69
+
70
+ for section_name in parsed:
71
+ if section_name not in configuration_classes:
72
+ raise ValueError(f"{source_path}: unknown section {section_name!r}.")
73
+
74
+ for section_name, configuration_class in configuration_classes.items():
75
+ _validate_configuration_input(
76
+ parsed.get(section_name, {}),
77
+ configuration_class,
78
+ field_path=section_name,
79
+ source_path=source_path,
80
+ )
81
+
82
+ configurations = {}
83
+ for section_name, configuration_class in configuration_classes.items():
84
+ configurations[section_name] = _instantiate_configuration(
85
+ configuration_class,
86
+ parsed.get(section_name, {}),
87
+ section_path=section_name,
88
+ source_path=source_path,
89
+ logger=log,
90
+ )
91
+ if destination is not None:
92
+ _write_configuration_records(
93
+ original_contents, configurations, output_directory=destination
94
+ )
95
+ return configurations
96
+
97
+
98
+ class ConfigReader:
99
+ """Build a section-to-dataclass mapping and optionally delegate reading."""
100
+
101
+ configuration_classes: dict[str, type[Any]]
102
+
103
+ def __init__(self) -> None:
104
+ """Create the empty public configuration_classes registration dictionary."""
105
+ self.configuration_classes = {}
106
+
107
+ def register_class(
108
+ self, configuration_class: type[Configuration], *, section_name: str
109
+ ) -> None:
110
+ """Register a dataclass; reject duplicate names and unsupported types."""
111
+ if section_name in self.configuration_classes:
112
+ raise ValueError(f"Section {section_name!r} is already registered.")
113
+ _validate_configuration_dataclass(
114
+ configuration_class, section_name=section_name
115
+ )
116
+ self.configuration_classes[section_name] = configuration_class
117
+
118
+ def register_name(
119
+ self, section_name: str
120
+ ) -> Callable[[type[Configuration]], type[Configuration]]:
121
+ """Return a decorator that registers and preserves the class."""
122
+
123
+ def register_configuration_class(
124
+ configuration_class: type[Configuration],
125
+ ) -> type[Configuration]:
126
+ """Register the decorated dataclass and return it unchanged."""
127
+ self.register_class(configuration_class, section_name=section_name)
128
+ return configuration_class
129
+
130
+ return register_configuration_class
131
+
132
+ def read(
133
+ self,
134
+ path: Path | str,
135
+ *,
136
+ write_config: bool = False,
137
+ run_result_directory: Path | str | None = None,
138
+ output_directory: Path | str | None = None,
139
+ logger: Logger | None = None,
140
+ ) -> dict[str, Any]:
141
+ """Forward configuration_classes and all arguments to read_config."""
142
+ return read_config(
143
+ self.configuration_classes,
144
+ path,
145
+ write_config=write_config,
146
+ run_result_directory=run_result_directory,
147
+ output_directory=output_directory,
148
+ logger=logger,
149
+ )
150
+
151
+
152
+ def _validate_configuration_dataclass(
153
+ configuration_class: type[Any], *, section_name: str
154
+ ) -> None:
155
+ """Validate the dataclass schema, including types in nested dataclasses."""
156
+ if not isinstance(configuration_class, type) or not is_dataclass(
157
+ configuration_class
158
+ ):
159
+ raise TypeError(
160
+ f"{section_name}: expected a dataclass class, got {configuration_class!r}."
161
+ )
162
+ pending = [(configuration_class, section_name)]
163
+ visited = set()
164
+ while pending:
165
+ current_class, current_path = pending.pop()
166
+ if current_class in visited:
167
+ continue
168
+ visited.add(current_class)
169
+ try:
170
+ annotations = get_type_hints(current_class, include_extras=True)
171
+ except (NameError, TypeError) as error:
172
+ raise TypeError(
173
+ f"{current_path}: cannot resolve configuration annotations: {error}"
174
+ ) from error
175
+ for configuration_field in fields(current_class):
176
+ if not configuration_field.init:
177
+ continue
178
+ field_path = f"{current_path}.{configuration_field.name}"
179
+ annotation = annotations[configuration_field.name]
180
+ _validate_supported_configuration_type(annotation, field_path=field_path)
181
+ nested_annotations = [annotation]
182
+ while nested_annotations:
183
+ nested_annotation = nested_annotations.pop()
184
+ if isinstance(nested_annotation, type) and is_dataclass(
185
+ nested_annotation
186
+ ):
187
+ pending.append((nested_annotation, field_path))
188
+ elif get_origin(nested_annotation) is not Literal:
189
+ nested_annotations.extend(get_args(nested_annotation))
190
+
191
+
192
+ def _validate_supported_configuration_type(annotation: Any, *, field_path: str) -> None:
193
+ """Check supported type expressions; nested class schemas are checked separately."""
194
+ if annotation in (str, bool, int, float, date, datetime, time, type(None)):
195
+ return
196
+ if isinstance(annotation, type) and is_dataclass(annotation):
197
+ return
198
+ origin = get_origin(annotation)
199
+ arguments = get_args(annotation)
200
+ if origin in (Union, UnionType):
201
+ for argument in arguments:
202
+ _validate_supported_configuration_type(argument, field_path=field_path)
203
+ return
204
+ if origin is Literal and arguments:
205
+ if all(
206
+ type(argument) in (str, bool, int, float, type(None))
207
+ for argument in arguments
208
+ ):
209
+ return
210
+ if origin is list and len(arguments) == 1:
211
+ _validate_supported_configuration_type(arguments[0], field_path=field_path)
212
+ return
213
+ if origin is dict and len(arguments) == 2 and arguments[0] is str:
214
+ _validate_supported_configuration_type(arguments[1], field_path=field_path)
215
+ return
216
+ raise TypeError(f"{field_path}: unsupported configuration type {annotation!r}.")
217
+
218
+
219
+ def _validate_configuration_input(
220
+ value: Any,
221
+ annotation: Any,
222
+ *,
223
+ field_path: str,
224
+ source_path: Path,
225
+ require_dataclass_instances: bool = False,
226
+ ) -> None:
227
+ """Check a value recursively without constructing objects or logging.
228
+
229
+ Accept a mapping or an existing instance for a nested dataclass. Check unknown
230
+ fields and missing required fields in mappings. Used to select union branches
231
+ without running constructors for unsuccessful branches.
232
+
233
+ Set require_dataclass_instances when checking constructed objects: nested
234
+ dataclass values must then be instances, including inside containers and
235
+ unions. Parsed TOML mappings are accepted only before construction.
236
+ """
237
+ context = f"{source_path}: {field_path}"
238
+ origin = get_origin(annotation)
239
+ arguments = get_args(annotation)
240
+ if origin in (Union, UnionType):
241
+ for argument in arguments:
242
+ try:
243
+ _validate_configuration_input(
244
+ value,
245
+ argument,
246
+ field_path=field_path,
247
+ source_path=source_path,
248
+ require_dataclass_instances=require_dataclass_instances,
249
+ )
250
+ except (TypeError, ValueError):
251
+ continue
252
+ return
253
+ raise TypeError(f"{context}: value {value!r} does not match {annotation!r}.")
254
+ if origin is Literal:
255
+ if any(
256
+ type(value) is type(argument) and value == argument
257
+ for argument in arguments
258
+ ):
259
+ return
260
+ elif isinstance(annotation, type) and is_dataclass(annotation):
261
+ constructor_fields = {
262
+ item.name: item for item in fields(annotation) if item.init
263
+ }
264
+ annotations = get_type_hints(annotation, include_extras=True)
265
+ if isinstance(value, Mapping) and not require_dataclass_instances:
266
+ for name in value:
267
+ if name not in constructor_fields:
268
+ raise ValueError(f"{context}.{name}: unknown constructor field.")
269
+ for name, configuration_field in constructor_fields.items():
270
+ if name in value:
271
+ _validate_configuration_input(
272
+ value[name],
273
+ annotations[name],
274
+ field_path=f"{field_path}.{name}",
275
+ source_path=source_path,
276
+ require_dataclass_instances=require_dataclass_instances,
277
+ )
278
+ elif (
279
+ configuration_field.default is MISSING
280
+ and configuration_field.default_factory is MISSING
281
+ ):
282
+ raise ValueError(
283
+ f"{context}.{name}: required field is not presented and has no default."
284
+ )
285
+ return
286
+ if isinstance(value, annotation):
287
+ for name in constructor_fields:
288
+ _validate_configuration_input(
289
+ getattr(value, name),
290
+ annotations[name],
291
+ field_path=f"{field_path}.{name}",
292
+ source_path=source_path,
293
+ require_dataclass_instances=True,
294
+ )
295
+ return
296
+ elif origin is list and type(value) is list:
297
+ for index, item in enumerate(value):
298
+ _validate_configuration_input(
299
+ item,
300
+ arguments[0],
301
+ field_path=f"{field_path}[{index}]",
302
+ source_path=source_path,
303
+ require_dataclass_instances=require_dataclass_instances,
304
+ )
305
+ return
306
+ elif origin is dict and type(value) is dict:
307
+ for key, item in value.items():
308
+ if type(key) is not str:
309
+ raise TypeError(f"{context}: dictionary key {key!r} must be a string.")
310
+ _validate_configuration_input(
311
+ item,
312
+ arguments[1],
313
+ field_path=f"{field_path}[{key!r}]",
314
+ source_path=source_path,
315
+ require_dataclass_instances=require_dataclass_instances,
316
+ )
317
+ return
318
+ elif type(value) is annotation:
319
+ return
320
+ raise TypeError(
321
+ f"{context}: expected {annotation!r}, got {type(value).__name__} ({value!r})."
322
+ )
323
+
324
+
325
+ def _instantiate_configuration(
326
+ configuration_class: type[Configuration],
327
+ configuration_values: Mapping[str, Any],
328
+ *,
329
+ section_path: str,
330
+ source_path: Path,
331
+ logger: Logger,
332
+ ) -> Configuration:
333
+ """Construct a dataclass, validate defaults, and log each omitted field.
334
+
335
+ Let the dataclass invoke default factories and __post_init__. Log actual
336
+ resolved default values after construction; do not invoke factories twice.
337
+ """
338
+ annotations = get_type_hints(configuration_class, include_extras=True)
339
+ constructor_fields = fields(cast(Any, configuration_class))
340
+ constructor_arguments = {}
341
+ for configuration_field in constructor_fields:
342
+ name = configuration_field.name
343
+ if configuration_field.init and name in configuration_values:
344
+ constructor_arguments[name] = _instantiate_configuration_value(
345
+ configuration_values[name],
346
+ annotations[name],
347
+ field_path=f"{section_path}.{name}",
348
+ source_path=source_path,
349
+ logger=logger,
350
+ )
351
+ instance = configuration_class(**constructor_arguments)
352
+ # Factories and __post_init__ have now run, so their results can be checked.
353
+ _validate_configuration_input(
354
+ instance,
355
+ configuration_class,
356
+ field_path=section_path,
357
+ source_path=source_path,
358
+ require_dataclass_instances=True,
359
+ )
360
+ for configuration_field in constructor_fields:
361
+ if (
362
+ configuration_field.init
363
+ and configuration_field.name not in configuration_values
364
+ ):
365
+ logger.warning(
366
+ "%s is not presented in %s, using default value: %s",
367
+ configuration_field.name,
368
+ section_path,
369
+ getattr(instance, configuration_field.name),
370
+ )
371
+ return instance
372
+
373
+
374
+ def _instantiate_configuration_value(
375
+ value: Any,
376
+ annotation: Any,
377
+ *,
378
+ field_path: str,
379
+ source_path: Path,
380
+ logger: Logger,
381
+ ) -> Any:
382
+ """Instantiate nested dataclasses within previously validated input.
383
+
384
+ Preserve already instantiated defaults. For unions, use the first matching
385
+ annotation in declaration order. Only union selection rechecks input; it must
386
+ select a branch without executing constructors. Do not coerce scalar values.
387
+ """
388
+ origin = get_origin(annotation)
389
+ arguments = get_args(annotation)
390
+ if origin in (Union, UnionType):
391
+ for argument in arguments:
392
+ try:
393
+ _validate_configuration_input(
394
+ value, argument, field_path=field_path, source_path=source_path
395
+ )
396
+ except (TypeError, ValueError):
397
+ continue
398
+ return _instantiate_configuration_value(
399
+ value,
400
+ argument,
401
+ field_path=field_path,
402
+ source_path=source_path,
403
+ logger=logger,
404
+ )
405
+ if (
406
+ isinstance(annotation, type)
407
+ and is_dataclass(annotation)
408
+ and isinstance(value, Mapping)
409
+ ):
410
+ return _instantiate_configuration(
411
+ annotation,
412
+ value,
413
+ section_path=field_path,
414
+ source_path=source_path,
415
+ logger=logger,
416
+ )
417
+ if origin is list:
418
+ return [
419
+ _instantiate_configuration_value(
420
+ item,
421
+ arguments[0],
422
+ field_path=f"{field_path}[{index}]",
423
+ source_path=source_path,
424
+ logger=logger,
425
+ )
426
+ for index, item in enumerate(value)
427
+ ]
428
+ if origin is dict:
429
+ return {
430
+ key: _instantiate_configuration_value(
431
+ item,
432
+ arguments[1],
433
+ field_path=f"{field_path}[{key!r}]",
434
+ source_path=source_path,
435
+ logger=logger,
436
+ )
437
+ for key, item in value.items()
438
+ }
439
+ return value
440
+
441
+
442
+ def _serialize_configuration_value(value: Any, *, field_path: str) -> Any:
443
+ """Produce TOML-compatible values using constructor fields only.
444
+
445
+ Omit None-valued mapping entries; reject None in lists because TOML has no
446
+ null element. Retain empty nested tables so required nested objects reload.
447
+ """
448
+ if is_dataclass(value) and not isinstance(value, type):
449
+ return {
450
+ configuration_field.name: _serialize_configuration_value(
451
+ getattr(value, configuration_field.name),
452
+ field_path=f"{field_path}.{configuration_field.name}",
453
+ )
454
+ for configuration_field in fields(value)
455
+ if configuration_field.init
456
+ and getattr(value, configuration_field.name) is not None
457
+ }
458
+ if isinstance(value, dict):
459
+ return {
460
+ key: _serialize_configuration_value(
461
+ item, field_path=f"{field_path}[{key!r}]"
462
+ )
463
+ for key, item in value.items()
464
+ if item is not None
465
+ }
466
+ if isinstance(value, list):
467
+ return [
468
+ _serialize_configuration_value(item, field_path=f"{field_path}[{index}]")
469
+ for index, item in enumerate(value)
470
+ ]
471
+ if value is None:
472
+ raise TypeError(f"{field_path}: TOML cannot represent None inside a list.")
473
+ return value
474
+
475
+
476
+ def _write_configuration_records(
477
+ original_contents: bytes,
478
+ configurations: Mapping[str, Any],
479
+ *,
480
+ output_directory: Path,
481
+ ) -> None:
482
+ """Write config.original.toml verbatim and config.completed.toml.
483
+
484
+ Serialize before writing and create the output directory as needed. The caller
485
+ is responsible for run-directory protection. No environment overrides apply.
486
+ """
487
+ completed = {}
488
+ for section_name, configuration in configurations.items():
489
+ completed[section_name] = _serialize_configuration_value(
490
+ configuration, field_path=section_name
491
+ )
492
+ completed_contents = tomli_w.dumps(completed).encode("utf-8")
493
+ output_directory.mkdir(parents=True, exist_ok=True)
494
+ (output_directory / "config.original.toml").write_bytes(original_contents)
495
+ (output_directory / "config.completed.toml").write_bytes(completed_contents)