blut-core 0.1.0__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.
- blut_core-0.1.0/.gitignore +6 -0
- blut_core-0.1.0/LICENSE +202 -0
- blut_core-0.1.0/PKG-INFO +38 -0
- blut_core-0.1.0/README.md +20 -0
- blut_core-0.1.0/blut_core/__init__.py +54 -0
- blut_core-0.1.0/blut_core/async_io.py +246 -0
- blut_core-0.1.0/blut_core/checkpoint.py +172 -0
- blut_core-0.1.0/blut_core/evaluator.py +98 -0
- blut_core-0.1.0/blut_core/ingredients/__init__.py +20 -0
- blut_core-0.1.0/blut_core/ingredients/_specs.py +2 -0
- blut_core-0.1.0/blut_core/ingredients/checkpoint/__init__.py +0 -0
- blut_core-0.1.0/blut_core/ingredients/checkpoint/_specs.py +162 -0
- blut_core-0.1.0/blut_core/ingredients/data/__init__.py +0 -0
- blut_core-0.1.0/blut_core/ingredients/data/_specs.py +87 -0
- blut_core-0.1.0/blut_core/ingredients/ema/__init__.py +0 -0
- blut_core-0.1.0/blut_core/ingredients/ema/_specs.py +62 -0
- blut_core-0.1.0/blut_core/ingredients/eval/__init__.py +0 -0
- blut_core-0.1.0/blut_core/ingredients/eval/_specs.py +150 -0
- blut_core-0.1.0/blut_core/ingredients/forward/__init__.py +0 -0
- blut_core-0.1.0/blut_core/ingredients/forward/_specs.py +35 -0
- blut_core-0.1.0/blut_core/ingredients/logging/__init__.py +0 -0
- blut_core-0.1.0/blut_core/ingredients/logging/_specs.py +49 -0
- blut_core-0.1.0/blut_core/ingredients/loss/__init__.py +0 -0
- blut_core-0.1.0/blut_core/ingredients/loss/_specs.py +142 -0
- blut_core-0.1.0/blut_core/ingredients/model/__init__.py +0 -0
- blut_core-0.1.0/blut_core/ingredients/model/_specs.py +138 -0
- blut_core-0.1.0/blut_core/ingredients/optimizer/__init__.py +0 -0
- blut_core-0.1.0/blut_core/ingredients/optimizer/_specs.py +164 -0
- blut_core-0.1.0/blut_core/ingredients/optimizer/cautious_wd.py +23 -0
- blut_core-0.1.0/blut_core/ingredients/optimizer/muon_optimizer.py +131 -0
- blut_core-0.1.0/blut_core/ingredients/optimizer/soap_optimizer.py +301 -0
- blut_core-0.1.0/blut_core/ingredients/sampler/__init__.py +0 -0
- blut_core-0.1.0/blut_core/ingredients/sampler/_specs.py +92 -0
- blut_core-0.1.0/blut_core/ingredients/scheduler/__init__.py +0 -0
- blut_core-0.1.0/blut_core/ingredients/scheduler/_specs.py +195 -0
- blut_core-0.1.0/blut_core/ingredients/scheduler/wsd.py +147 -0
- blut_core-0.1.0/blut_core/ingredients/step/__init__.py +0 -0
- blut_core-0.1.0/blut_core/ingredients/step/_specs.py +123 -0
- blut_core-0.1.0/blut_core/load_dataset.py +68 -0
- blut_core-0.1.0/blut_core/metric_log.py +136 -0
- blut_core-0.1.0/blut_core/read_metric.py +296 -0
- blut_core-0.1.0/blut_core/registry.py +109 -0
- blut_core-0.1.0/blut_core/run_ledger.py +346 -0
- blut_core-0.1.0/blut_core/run_manifest.py +204 -0
- blut_core-0.1.0/blut_core/runctx.py +68 -0
- blut_core-0.1.0/blut_core/spec.py +102 -0
- blut_core-0.1.0/blut_core/status.py +90 -0
- blut_core-0.1.0/blut_core/sysgauge.py +82 -0
- blut_core-0.1.0/blut_core/tests/test_async_compute.py +161 -0
- blut_core-0.1.0/blut_core/tests/test_async_io_contract.py +466 -0
- blut_core-0.1.0/blut_core/tests/test_import_contract.py +32 -0
- blut_core-0.1.0/blut_core/tests/test_load_dataset.py +39 -0
- blut_core-0.1.0/blut_core/tests/test_parallel_strategy.py +64 -0
- blut_core-0.1.0/blut_core/tests/test_primitives.py +111 -0
- blut_core-0.1.0/blut_core/tests/test_read_metric.py +129 -0
- blut_core-0.1.0/blut_core/tests/test_run_ledger.py +73 -0
- blut_core-0.1.0/blut_core/trainer.py +631 -0
- blut_core-0.1.0/pyproject.toml +35 -0
blut_core-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
blut_core-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: blut-core
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Shared Python runtime for BLUT cookbooks: run context, metric log, status wire, run manifest, checkpoint contract, ingredient registry.
|
|
5
|
+
Project-URL: Repository, https://github.com/Quitetall/blut-cookbooks
|
|
6
|
+
Author: Brian Lam
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: blut,cookbook,metrics,provenance,training
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Provides-Extra: parquet
|
|
14
|
+
Requires-Dist: pyarrow>=15; extra == 'parquet'
|
|
15
|
+
Provides-Extra: torch
|
|
16
|
+
Requires-Dist: torch>=2.5; extra == 'torch'
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# blut-core
|
|
20
|
+
|
|
21
|
+
The shared Python runtime for [BLUT](https://github.com/Quitetall/blut) cookbooks:
|
|
22
|
+
domain-agnostic building blocks any cookbook can reuse.
|
|
23
|
+
|
|
24
|
+
- `runctx` — run identity and filesystem anchors from the BLUT environment
|
|
25
|
+
- `MetricLog` — atomic per-epoch CSV/Parquet metric writer
|
|
26
|
+
- `read_metric` — verbatim metric/log reader (no model in the path)
|
|
27
|
+
- `status` — the StatusUpdate wire protocol
|
|
28
|
+
- `RunManifest` — run provenance, written even on crash
|
|
29
|
+
- `checkpoint` — corruption-safe save/load and the resume payload contract
|
|
30
|
+
- `sysgauge` — best-effort GPU/host snapshot for the metric stream
|
|
31
|
+
- `async_io` — bounded, backpressured delivery for persistence work
|
|
32
|
+
- the ingredient specs and builders the generic training recipes build on
|
|
33
|
+
|
|
34
|
+
`torch` is imported lazily, inside `checkpoint` and `sysgauge` only, so
|
|
35
|
+
`import blut_core` stays cheap. Install `blut-core[torch]` if you call those, and `blut-core[parquet]` for
|
|
36
|
+
Parquet metric logs.
|
|
37
|
+
|
|
38
|
+
Apache-2.0. Published from the `blut-cookbooks` repository.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# blut-core
|
|
2
|
+
|
|
3
|
+
The shared Python runtime for [BLUT](https://github.com/Quitetall/blut) cookbooks:
|
|
4
|
+
domain-agnostic building blocks any cookbook can reuse.
|
|
5
|
+
|
|
6
|
+
- `runctx` — run identity and filesystem anchors from the BLUT environment
|
|
7
|
+
- `MetricLog` — atomic per-epoch CSV/Parquet metric writer
|
|
8
|
+
- `read_metric` — verbatim metric/log reader (no model in the path)
|
|
9
|
+
- `status` — the StatusUpdate wire protocol
|
|
10
|
+
- `RunManifest` — run provenance, written even on crash
|
|
11
|
+
- `checkpoint` — corruption-safe save/load and the resume payload contract
|
|
12
|
+
- `sysgauge` — best-effort GPU/host snapshot for the metric stream
|
|
13
|
+
- `async_io` — bounded, backpressured delivery for persistence work
|
|
14
|
+
- the ingredient specs and builders the generic training recipes build on
|
|
15
|
+
|
|
16
|
+
`torch` is imported lazily, inside `checkpoint` and `sysgauge` only, so
|
|
17
|
+
`import blut_core` stays cheap. Install `blut-core[torch]` if you call those, and `blut-core[parquet]` for
|
|
18
|
+
Parquet metric logs.
|
|
19
|
+
|
|
20
|
+
Apache-2.0. Published from the `blut-cookbooks` repository.
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Shared Python runtime and ingredient registry for BLUT cookbooks.
|
|
2
|
+
|
|
3
|
+
The package contains domain-agnostic building blocks reusable by any cookbook:
|
|
4
|
+
|
|
5
|
+
- ``async_io`` — bounded, backpressured delivery for persistence work
|
|
6
|
+
- ``runctx`` — run identity + filesystem anchors from the BLUT env (P10)
|
|
7
|
+
- ``MetricLog`` — atomic per-epoch CSV/Parquet metric writer
|
|
8
|
+
- ``read_metric`` — verbatim metric/log reader (no LLM in the path; ADR 0038)
|
|
9
|
+
- ``status`` — emit/read the StatusUpdate wire protocol (P4)
|
|
10
|
+
- ``RunManifest`` — run provenance, written even on crash (P8)
|
|
11
|
+
- ``checkpoint`` — corruption-safe save/load + resume payload contract (P7)
|
|
12
|
+
- ``sysgauge`` — best-effort GPU/host snapshot for the metric stream (P10)
|
|
13
|
+
- ingredient specs and builders used by generic training recipes
|
|
14
|
+
|
|
15
|
+
``torch`` is lazy-imported only inside ``checkpoint``/``sysgauge`` functions, so
|
|
16
|
+
``import blut_core`` stays cheap and dependency-light. See ``blut/docs/metrics.md``
|
|
17
|
+
and decisions/0037, 0044.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from blut_core.registry import (
|
|
21
|
+
build_ingredient,
|
|
22
|
+
get_spec,
|
|
23
|
+
list_ingredients,
|
|
24
|
+
register_ingredient,
|
|
25
|
+
)
|
|
26
|
+
from blut_core.spec import KINDS, IngredientSpec
|
|
27
|
+
|
|
28
|
+
# Register generic ingredient specs on package import.
|
|
29
|
+
from blut_core.ingredients import _specs as _ingredient_specs # noqa: F401
|
|
30
|
+
|
|
31
|
+
from . import async_io, checkpoint, runctx, status, sysgauge
|
|
32
|
+
from .metric_log import MetricLog
|
|
33
|
+
from .run_manifest import RunManifest
|
|
34
|
+
|
|
35
|
+
# read_metric is a CLI module (`python -m blut_core.read_metric`); it is NOT
|
|
36
|
+
# eager-imported here (that triggers a runpy double-import warning under -m).
|
|
37
|
+
# `from blut_core import read_metric` still works (submodule import).
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"IngredientSpec",
|
|
41
|
+
"KINDS",
|
|
42
|
+
"MetricLog",
|
|
43
|
+
"RunManifest",
|
|
44
|
+
"async_io",
|
|
45
|
+
"build_ingredient",
|
|
46
|
+
"checkpoint",
|
|
47
|
+
"get_spec",
|
|
48
|
+
"list_ingredients",
|
|
49
|
+
"read_metric",
|
|
50
|
+
"register_ingredient",
|
|
51
|
+
"runctx",
|
|
52
|
+
"status",
|
|
53
|
+
"sysgauge",
|
|
54
|
+
]
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Bounded, backpressured asynchronous I/O for cookbook runtimes.
|
|
2
|
+
|
|
3
|
+
Bounded workers are daemons so an exceptional interpreter shutdown cannot hang
|
|
4
|
+
on an idle worker. Successful callers must still call :meth:`AsyncSink.close`;
|
|
5
|
+
that is the only boundary that drains accepted work and surfaces worker errors.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from queue import Queue
|
|
12
|
+
from threading import BoundedSemaphore, Condition, Thread, local
|
|
13
|
+
from typing import Callable, Generic, TypeVar, cast
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"AsyncSink",
|
|
18
|
+
"AsyncSinkWorkerError",
|
|
19
|
+
"Bounded",
|
|
20
|
+
"Inline",
|
|
21
|
+
"ItemTooLargeError",
|
|
22
|
+
"SinkClosedError",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
ItemT = TypeVar("ItemT")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _identity(item: ItemT) -> ItemT:
|
|
30
|
+
return item
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ItemTooLargeError(ValueError):
|
|
34
|
+
"""A submitted item exceeds the sink's declared retention limit."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, size_bytes: int, max_item_bytes: int) -> None:
|
|
37
|
+
self.size_bytes = size_bytes
|
|
38
|
+
self.max_item_bytes = max_item_bytes
|
|
39
|
+
super().__init__(f"item is {size_bytes} bytes; limit is {max_item_bytes}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class SinkClosedError(RuntimeError):
|
|
43
|
+
"""Work was submitted after sink shutdown began."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class AsyncSinkWorkerError(RuntimeError):
|
|
47
|
+
"""A sink worker failed while delivering an accepted item."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, worker_error_type: str, message: str) -> None:
|
|
50
|
+
self.worker_error_type = worker_error_type
|
|
51
|
+
super().__init__(message)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class _WorkerFailure:
|
|
56
|
+
worker_error_type: str
|
|
57
|
+
message: str
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def capture(cls, error: BaseException) -> _WorkerFailure:
|
|
61
|
+
error_type = type(error)
|
|
62
|
+
worker_error_type = f"{error_type.__module__}.{error_type.__qualname__}"
|
|
63
|
+
try:
|
|
64
|
+
message = str(error)
|
|
65
|
+
except BaseException:
|
|
66
|
+
message = "worker failure with an unprintable message"
|
|
67
|
+
return cls(worker_error_type=worker_error_type, message=message)
|
|
68
|
+
|
|
69
|
+
def to_exception(self) -> AsyncSinkWorkerError:
|
|
70
|
+
return AsyncSinkWorkerError(self.worker_error_type, self.message)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class Inline:
|
|
75
|
+
"""Run the installed handler synchronously on the submitting thread."""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class Bounded:
|
|
80
|
+
"""Run work on one worker with bounded retained residency."""
|
|
81
|
+
|
|
82
|
+
capacity: int
|
|
83
|
+
max_item_bytes: int
|
|
84
|
+
|
|
85
|
+
def __post_init__(self) -> None:
|
|
86
|
+
if isinstance(self.capacity, bool) or not isinstance(self.capacity, int):
|
|
87
|
+
raise TypeError("capacity must be an integer")
|
|
88
|
+
if isinstance(self.max_item_bytes, bool) or not isinstance(
|
|
89
|
+
self.max_item_bytes, int
|
|
90
|
+
):
|
|
91
|
+
raise TypeError("max_item_bytes must be an integer")
|
|
92
|
+
if self.capacity <= 0:
|
|
93
|
+
raise ValueError("capacity must be greater than zero")
|
|
94
|
+
if self.max_item_bytes <= 0:
|
|
95
|
+
raise ValueError("max_item_bytes must be greater than zero")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
_STOP = object()
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class AsyncSink(Generic[ItemT]):
|
|
102
|
+
"""Deliver items to one handler under an explicit, close-required mode."""
|
|
103
|
+
|
|
104
|
+
def __init__(
|
|
105
|
+
self,
|
|
106
|
+
handler: Callable[[ItemT], None],
|
|
107
|
+
mode: Inline | Bounded,
|
|
108
|
+
*,
|
|
109
|
+
item_size: Callable[[ItemT], int] | None = None,
|
|
110
|
+
retain: Callable[[ItemT], ItemT] = _identity,
|
|
111
|
+
retained_size: Callable[[ItemT], int] | None = None,
|
|
112
|
+
thread_name: str = "blut-async-io",
|
|
113
|
+
) -> None:
|
|
114
|
+
self._handler = handler
|
|
115
|
+
self._mode = mode
|
|
116
|
+
self._item_size = item_size
|
|
117
|
+
self._retain = retain
|
|
118
|
+
self._retained_size = retained_size
|
|
119
|
+
self._closed = False
|
|
120
|
+
self._failure: _WorkerFailure | None = None
|
|
121
|
+
self._state = Condition()
|
|
122
|
+
self._active_submits = 0
|
|
123
|
+
self._stop_enqueued = False
|
|
124
|
+
self._callback_state = local()
|
|
125
|
+
self._queue: Queue[ItemT | object] | None = None
|
|
126
|
+
self._slots: BoundedSemaphore | None = None
|
|
127
|
+
self._worker: Thread | None = None
|
|
128
|
+
if isinstance(mode, Bounded):
|
|
129
|
+
self._queue = Queue(maxsize=mode.capacity)
|
|
130
|
+
self._slots = BoundedSemaphore(mode.capacity)
|
|
131
|
+
self._worker = Thread(target=self._run, name=thread_name, daemon=True)
|
|
132
|
+
self._worker.start()
|
|
133
|
+
|
|
134
|
+
def submit(self, item: ItemT, *, size_bytes: int | None = None) -> None:
|
|
135
|
+
"""Deliver one item according to the configured mode."""
|
|
136
|
+
|
|
137
|
+
if getattr(self._callback_state, "active", False):
|
|
138
|
+
raise RuntimeError("submit cannot be called from a sink callback")
|
|
139
|
+
|
|
140
|
+
with self._state:
|
|
141
|
+
self._raise_if_failed_locked()
|
|
142
|
+
if self._closed:
|
|
143
|
+
raise SinkClosedError("sink is closed")
|
|
144
|
+
self._active_submits += 1
|
|
145
|
+
|
|
146
|
+
acquired_slot = False
|
|
147
|
+
try:
|
|
148
|
+
if isinstance(self._mode, Inline):
|
|
149
|
+
self._invoke_handler(self._invoke_callback(self._retain, item))
|
|
150
|
+
return
|
|
151
|
+
|
|
152
|
+
if size_bytes is None and self._item_size is not None:
|
|
153
|
+
size_bytes = self._invoke_callback(self._item_size, item)
|
|
154
|
+
if size_bytes is None and self._retained_size is None:
|
|
155
|
+
raise TypeError(
|
|
156
|
+
"bounded submit requires size_bytes, item_size, or retained_size"
|
|
157
|
+
)
|
|
158
|
+
if size_bytes is not None:
|
|
159
|
+
if isinstance(size_bytes, bool) or not isinstance(size_bytes, int):
|
|
160
|
+
raise TypeError("item size must be an integer byte count")
|
|
161
|
+
if size_bytes < 0:
|
|
162
|
+
raise ValueError("item size must not be negative")
|
|
163
|
+
if size_bytes > self._mode.max_item_bytes:
|
|
164
|
+
raise ItemTooLargeError(size_bytes, self._mode.max_item_bytes)
|
|
165
|
+
|
|
166
|
+
slots = cast(BoundedSemaphore, self._slots)
|
|
167
|
+
queue = cast(Queue[ItemT | object], self._queue)
|
|
168
|
+
slots.acquire()
|
|
169
|
+
acquired_slot = True
|
|
170
|
+
with self._state:
|
|
171
|
+
self._raise_if_failed_locked()
|
|
172
|
+
if self._closed:
|
|
173
|
+
raise SinkClosedError("sink is closed")
|
|
174
|
+
retained = self._invoke_callback(self._retain, item)
|
|
175
|
+
if self._retained_size is not None:
|
|
176
|
+
retained_bytes = self._invoke_callback(self._retained_size, retained)
|
|
177
|
+
if isinstance(retained_bytes, bool) or not isinstance(retained_bytes, int):
|
|
178
|
+
raise TypeError("retained item size must be an integer byte count")
|
|
179
|
+
if retained_bytes < 0:
|
|
180
|
+
raise ValueError("retained item size must not be negative")
|
|
181
|
+
if retained_bytes > self._mode.max_item_bytes:
|
|
182
|
+
raise ItemTooLargeError(retained_bytes, self._mode.max_item_bytes)
|
|
183
|
+
queue.put(retained)
|
|
184
|
+
acquired_slot = False
|
|
185
|
+
finally:
|
|
186
|
+
if acquired_slot:
|
|
187
|
+
cast(BoundedSemaphore, self._slots).release()
|
|
188
|
+
with self._state:
|
|
189
|
+
self._active_submits -= 1
|
|
190
|
+
self._state.notify_all()
|
|
191
|
+
|
|
192
|
+
def close(self) -> None:
|
|
193
|
+
"""Drain accepted work and stop the sink."""
|
|
194
|
+
|
|
195
|
+
if getattr(self._callback_state, "active", False):
|
|
196
|
+
raise RuntimeError("close cannot be called from a sink callback")
|
|
197
|
+
|
|
198
|
+
with self._state:
|
|
199
|
+
self._closed = True
|
|
200
|
+
while self._active_submits:
|
|
201
|
+
self._state.wait()
|
|
202
|
+
if self._worker is not None and not self._stop_enqueued:
|
|
203
|
+
cast(Queue[ItemT | object], self._queue).put(_STOP)
|
|
204
|
+
self._stop_enqueued = True
|
|
205
|
+
|
|
206
|
+
if self._worker is not None:
|
|
207
|
+
self._worker.join()
|
|
208
|
+
self._raise_if_failed()
|
|
209
|
+
|
|
210
|
+
def _run(self) -> None:
|
|
211
|
+
queue = cast(Queue[ItemT | object], self._queue)
|
|
212
|
+
slots = cast(BoundedSemaphore, self._slots)
|
|
213
|
+
while True:
|
|
214
|
+
item = queue.get()
|
|
215
|
+
if item is _STOP:
|
|
216
|
+
return
|
|
217
|
+
try:
|
|
218
|
+
self._invoke_handler(cast(ItemT, item))
|
|
219
|
+
except BaseException as error:
|
|
220
|
+
with self._state:
|
|
221
|
+
if self._failure is None:
|
|
222
|
+
self._failure = _WorkerFailure.capture(error)
|
|
223
|
+
finally:
|
|
224
|
+
del item
|
|
225
|
+
slots.release()
|
|
226
|
+
|
|
227
|
+
def _invoke_handler(self, item: ItemT) -> None:
|
|
228
|
+
self._invoke_callback(self._handler, item)
|
|
229
|
+
|
|
230
|
+
def _invoke_callback(self, callback, item):
|
|
231
|
+
previous = getattr(self._callback_state, "active", False)
|
|
232
|
+
self._callback_state.active = True
|
|
233
|
+
try:
|
|
234
|
+
return callback(item)
|
|
235
|
+
finally:
|
|
236
|
+
self._callback_state.active = previous
|
|
237
|
+
|
|
238
|
+
def _raise_if_failed_locked(self) -> None:
|
|
239
|
+
if self._failure is not None:
|
|
240
|
+
raise self._failure.to_exception()
|
|
241
|
+
|
|
242
|
+
def _raise_if_failed(self) -> None:
|
|
243
|
+
with self._state:
|
|
244
|
+
failure = self._failure
|
|
245
|
+
if failure is not None:
|
|
246
|
+
raise failure.to_exception()
|