relarena-core 0.0.1__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 (38) hide show
  1. relarena_core-0.0.1/LICENSE +200 -0
  2. relarena_core-0.0.1/NOTICE +16 -0
  3. relarena_core-0.0.1/PKG-INFO +33 -0
  4. relarena_core-0.0.1/README.md +11 -0
  5. relarena_core-0.0.1/pyproject.toml +34 -0
  6. relarena_core-0.0.1/pyproject.toml.orig +26 -0
  7. relarena_core-0.0.1/src/relarena_core/__init__.py +41 -0
  8. relarena_core-0.0.1/src/relarena_core/cache.py +224 -0
  9. relarena_core-0.0.1/src/relarena_core/dataset.py +302 -0
  10. relarena_core-0.0.1/src/relarena_core/discovery.py +45 -0
  11. relarena_core-0.0.1/src/relarena_core/featurization/__init__.py +5 -0
  12. relarena_core-0.0.1/src/relarena_core/featurization/cache.py +47 -0
  13. relarena_core-0.0.1/src/relarena_core/featurization/columns.py +54 -0
  14. relarena_core-0.0.1/src/relarena_core/featurization/dfs.py +676 -0
  15. relarena_core-0.0.1/src/relarena_core/featurization/warm_cache.py +46 -0
  16. relarena_core-0.0.1/src/relarena_core/fingerprints.py +103 -0
  17. relarena_core-0.0.1/src/relarena_core/identity.py +100 -0
  18. relarena_core-0.0.1/src/relarena_core/metrics.py +161 -0
  19. relarena_core-0.0.1/src/relarena_core/model.py +106 -0
  20. relarena_core-0.0.1/src/relarena_core/predict_contract.py +41 -0
  21. relarena_core-0.0.1/src/relarena_core/py.typed +0 -0
  22. relarena_core-0.0.1/src/relarena_core/registry.py +170 -0
  23. relarena_core-0.0.1/src/relarena_core/results.py +81 -0
  24. relarena_core-0.0.1/src/relarena_core/search_space.py +149 -0
  25. relarena_core-0.0.1/src/relarena_core/selection.py +25 -0
  26. relarena_core-0.0.1/src/relarena_core/system.py +63 -0
  27. relarena_core-0.0.1/src/relarena_core/tasks.py +22 -0
  28. relarena_core-0.0.1/src/relarena_core/tfm.py +197 -0
  29. relarena_core-0.0.1/src/relarena_core/tuner.py +185 -0
  30. relarena_core-0.0.1/src/relarena_core/userdb/__init__.py +12 -0
  31. relarena_core-0.0.1/src/relarena_core/userdb/_schema.py +29 -0
  32. relarena_core-0.0.1/src/relarena_core/userdb/database.schema.json +37 -0
  33. relarena_core-0.0.1/src/relarena_core/userdb/ingest.py +239 -0
  34. relarena_core-0.0.1/src/relarena_core/userdb/predict.py +115 -0
  35. relarena_core-0.0.1/src/relarena_core/userdb/query.py +373 -0
  36. relarena_core-0.0.1/src/relarena_core/userdb/spec.py +77 -0
  37. relarena_core-0.0.1/src/relarena_core/userdb/task.py +96 -0
  38. relarena_core-0.0.1/src/relarena_core/userdb/task.schema.json +67 -0
@@ -0,0 +1,200 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 PriorLabs GmbH
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
@@ -0,0 +1,16 @@
1
+ RelArena Core
2
+ Copyright 2026 PriorLabs GmbH
3
+
4
+ Licensed under the Apache License, Version 2.0. See the LICENSE file.
5
+
6
+ The shared Deep Feature Synthesis and tabular-foundation-model fitting recipe
7
+ is a method adaptation of RDBLearn, licensed under Apache-2.0:
8
+ Copyright (c) HKU Shanghai X-Lab
9
+ https://github.com/HKUSHXLab/rdblearn
10
+
11
+ The non-stratified train downsampling in src/relarena_core/tfm.py is the closest
12
+ adaptation. The implementation is original code; no RDBLearn source files are
13
+ copied into this distribution.
14
+
15
+ Datasets and model weights are not distributed with this package. Dependencies,
16
+ downloaded datasets and inference backends retain their own upstream terms.
@@ -0,0 +1,33 @@
1
+ Metadata-Version: 2.4
2
+ Name: relarena-core
3
+ Version: 0.0.1
4
+ Summary: Shared contracts, temporal validation and predictive queries for relational models.
5
+ Author: Prior Labs
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ License-File: NOTICE
9
+ Requires-Dist: relbench==2.1.2
10
+ Requires-Dist: numpy>=1.24
11
+ Requires-Dist: pandas>=2.3.3,<3.0
12
+ Requires-Dist: scikit-learn>=1.3
13
+ Requires-Dist: configspace>=1.0
14
+ Requires-Dist: pyyaml>=6.0
15
+ Requires-Dist: jsonschema>=4.0
16
+ Requires-Dist: duckdb>=1.2.2
17
+ Requires-Dist: fastdfs>=1.1 ; extra == 'dfs'
18
+ Requires-Dist: setuptools<82 ; extra == 'dfs'
19
+ Requires-Python: >=3.11, <3.13
20
+ Provides-Extra: dfs
21
+ Description-Content-Type: text/markdown
22
+
23
+ # RelArena Core
24
+
25
+ Shared model contracts, temporal validation, caching and predictive queries for
26
+ relational models. This distribution is developed in the RelArena monorepo.
27
+
28
+ ```bash
29
+ pip install relarena-core
30
+ ```
31
+
32
+ DFS preprocessing is available through `relarena-core[dfs]`. Model packages
33
+ provide their own inference backends.
@@ -0,0 +1,11 @@
1
+ # RelArena Core
2
+
3
+ Shared model contracts, temporal validation, caching and predictive queries for
4
+ relational models. This distribution is developed in the RelArena monorepo.
5
+
6
+ ```bash
7
+ pip install relarena-core
8
+ ```
9
+
10
+ DFS preprocessing is available through `relarena-core[dfs]`. Model packages
11
+ provide their own inference backends.
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.11.15"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "relarena-core"
7
+ version = "0.0.1"
8
+ description = "Shared contracts, temporal validation and predictive queries for relational models."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = [
12
+ "LICENSE",
13
+ "NOTICE",
14
+ ]
15
+ requires-python = ">=3.11,<3.13"
16
+ dependencies = [
17
+ "relbench==2.1.2",
18
+ "numpy>=1.24",
19
+ "pandas>=2.3.3,<3.0",
20
+ "scikit-learn>=1.3",
21
+ "configspace>=1.0",
22
+ "pyyaml>=6.0",
23
+ "jsonschema>=4.0",
24
+ "duckdb>=1.2.2",
25
+ ]
26
+
27
+ [[project.authors]]
28
+ name = "Prior Labs"
29
+
30
+ [project.optional-dependencies]
31
+ dfs = [
32
+ "fastdfs>=1.1",
33
+ "setuptools<82",
34
+ ]
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.11.15"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "relarena-core"
7
+ version = "0.0.1"
8
+ description = "Shared contracts, temporal validation and predictive queries for relational models."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE", "NOTICE"]
12
+ authors = [{ name = "Prior Labs" }]
13
+ requires-python = ">=3.11,<3.13"
14
+ dependencies = [
15
+ "relbench==2.1.2",
16
+ "numpy>=1.24",
17
+ "pandas>=2.3.3,<3.0",
18
+ "scikit-learn>=1.3",
19
+ "configspace>=1.0",
20
+ "pyyaml>=6.0",
21
+ "jsonschema>=4.0",
22
+ "duckdb>=1.2.2",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ dfs = ["fastdfs>=1.1", "setuptools<82"]
@@ -0,0 +1,41 @@
1
+ """Shared contracts and runtime for relational prediction."""
2
+
3
+ from relarena_core.cache import CacheConfig, CacheMiss, cache_key, cached_artifact
4
+ from relarena_core.dataset import InnerSplit, OuterSplit, Split, TaskSource
5
+ from relarena_core.discovery import discover_models
6
+ from relarena_core.identity import RunIdentity
7
+ from relarena_core.model import RelArenaModel
8
+ from relarena_core.registry import (
9
+ MethodRegistry,
10
+ ModelRegistry,
11
+ register_model,
12
+ register_system,
13
+ registry,
14
+ )
15
+ from relarena_core.results import SystemResult, TrialResult
16
+ from relarena_core.system import RelArenaSystem
17
+ from relarena_core.tuner import tune
18
+
19
+ __version__ = "0.0.1"
20
+ __all__ = [
21
+ "CacheConfig",
22
+ "CacheMiss",
23
+ "cache_key",
24
+ "cached_artifact",
25
+ "TaskSource",
26
+ "Split",
27
+ "InnerSplit",
28
+ "OuterSplit",
29
+ "discover_models",
30
+ "RunIdentity",
31
+ "RelArenaModel",
32
+ "RelArenaSystem",
33
+ "MethodRegistry",
34
+ "ModelRegistry",
35
+ "register_model",
36
+ "register_system",
37
+ "registry",
38
+ "TrialResult",
39
+ "SystemResult",
40
+ "tune",
41
+ ]
@@ -0,0 +1,224 @@
1
+ """Optional, experimental helpers for caller-owned local cache artifacts.
2
+
3
+ This module provides only cache configuration and safe filesystem mechanics. It
4
+ does not know what an artifact represents, how its key is constructed, or how it
5
+ is serialized. Each preprocessing module owns those decisions and supplies
6
+ `load`, `build`, and optional `validate` callbacks to `cached_artifact`.
7
+
8
+ Using this API is not required: a model may implement caching independently or
9
+ avoid persistent caching altogether. Cache warming remains separate from a timed
10
+ RelArena experiment. Regardless of implementation, benchmark caches should have
11
+ public, reproducible, and leakage-safe generation code; see
12
+ `docs/adding-a-model.md` for the contributor policy and reference implementations.
13
+
14
+ A `CacheConfig` contains one resolved local cache root and a miss policy:
15
+
16
+ * `raise`: load an existing artifact; raise `CacheMiss` when absent.
17
+ * `fill`: load an existing artifact, or build and atomically publish it.
18
+ * `compute`: build privately without reading or writing the persistent store.
19
+
20
+ When no cache directory is configured, artifacts are also built in private
21
+ temporary scratch, regardless of the miss policy. Thus `raise` only guards
22
+ misses in a configured store.
23
+
24
+ Artifact keys are opaque, safe relative POSIX paths beneath the cache root.
25
+ Artifacts may be files or directories. On a fill miss, construction happens at
26
+ a unique staging path; the completed and validated artifact is then published
27
+ atomically. Concurrent builders cannot expose partial artifacts. Cache hits are
28
+ read-only and create no locks, metadata, or temporary files.
29
+
30
+ Callers are responsible for:
31
+
32
+ * constructing keys from the artifact's actual dependencies;
33
+ * versioning preprocessing algorithms;
34
+ * serialization, loading, building, and semantic validation;
35
+ * returning fully materialized values that do not depend on temporary paths.
36
+
37
+ Environment variables are resolved once by `resolve_cache_config` at an
38
+ entrypoint. Models and preprocessing code should receive the resulting immutable
39
+ `CacheConfig` explicitly rather than consulting the environment themselves.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import errno
45
+ import os
46
+ import re
47
+ import shutil
48
+ import tempfile
49
+ import uuid
50
+ import warnings
51
+ from collections.abc import Callable
52
+ from dataclasses import dataclass
53
+ from pathlib import Path, PurePosixPath
54
+ from typing import Literal, TypeVar
55
+
56
+ CACHE_DIR_ENV = "RELARENA_CACHE_DIR"
57
+ DISABLE_CACHE_ENV = "RELARENA_DISABLE_CACHE"
58
+ LEGACY_DISABLE_CACHE_ENV = "RELARENA_DISABLE_FEATURE_CACHE"
59
+
60
+ OnMiss = Literal["raise", "fill", "compute"]
61
+ Storage = Literal["file", "directory"]
62
+ T = TypeVar("T")
63
+
64
+
65
+ class CacheMiss(RuntimeError):
66
+ """A required artifact is absent from a configured cache."""
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class CacheConfig:
71
+ """Resolved cache directory and behavior for an absent artifact."""
72
+
73
+ directory: Path | None
74
+ on_miss: OnMiss
75
+
76
+ def __post_init__(self) -> None:
77
+ """Reject policies outside the intentionally small public set."""
78
+ if self.on_miss not in ("raise", "fill", "compute"):
79
+ raise ValueError(f"invalid cache miss policy: {self.on_miss!r}")
80
+
81
+
82
+ def parse_local_cache_dir(value: str | Path) -> Path:
83
+ """Expand a local cache path and reject URI-like locations."""
84
+ raw = str(value)
85
+ if not raw:
86
+ raise ValueError("cache directory cannot be empty")
87
+ scheme = re.match(r"^([A-Za-z][A-Za-z0-9+.-]*):(?:/{1,2})", raw)
88
+ if scheme is not None and len(scheme.group(1)) > 1:
89
+ raise ValueError(f"cache directory must be a local path, not {raw!r}")
90
+ return Path(raw).expanduser()
91
+
92
+
93
+ def resolve_cache_config(
94
+ cache_dir: str | Path | None, *, on_miss: OnMiss
95
+ ) -> CacheConfig:
96
+ """Resolve explicit path, environment fallback, and the disable switch once."""
97
+ value = cache_dir
98
+ if value is None:
99
+ value = os.environ.get(CACHE_DIR_ENV) or None
100
+ directory = None if value is None else parse_local_cache_dir(value)
101
+ if os.environ.get(LEGACY_DISABLE_CACHE_ENV):
102
+ warnings.warn(
103
+ f"{LEGACY_DISABLE_CACHE_ENV} is deprecated; use {DISABLE_CACHE_ENV}",
104
+ FutureWarning,
105
+ stacklevel=2,
106
+ )
107
+ directory = None
108
+ if os.environ.get(DISABLE_CACHE_ENV):
109
+ directory = None
110
+ return CacheConfig(directory=directory, on_miss=on_miss)
111
+
112
+
113
+ def cache_key(*segments: str) -> PurePosixPath:
114
+ """Join validated path segments into a canonical relative cache key."""
115
+ if not segments:
116
+ raise ValueError("cache key needs at least one segment")
117
+ for segment in segments:
118
+ if not segment or segment in (".", ".."):
119
+ raise ValueError(f"invalid cache-key segment: {segment!r}")
120
+ if "/" in segment or "\\" in segment:
121
+ raise ValueError(f"cache-key segment contains a separator: {segment!r}")
122
+ return PurePosixPath(*segments)
123
+
124
+
125
+ def _key_parts(key: str | PurePosixPath) -> tuple[str, ...]:
126
+ raw = str(key)
127
+ if not raw or raw.startswith("/") or "\\" in raw:
128
+ raise ValueError(f"cache key must be a safe relative POSIX path: {raw!r}")
129
+ parts = tuple(raw.split("/"))
130
+ if any(not part or part in (".", "..") for part in parts):
131
+ raise ValueError(f"cache key must be a safe relative POSIX path: {raw!r}")
132
+ return parts
133
+
134
+
135
+ def _destination(root: Path, parts: tuple[str, ...]) -> Path:
136
+ resolved_root = root.resolve()
137
+ destination = root.joinpath(*parts)
138
+ if not destination.resolve().is_relative_to(resolved_root):
139
+ raise ValueError("cache key escapes the configured cache directory")
140
+ return destination
141
+
142
+
143
+ def _qualifies(path: Path, storage: Storage) -> bool:
144
+ return path.is_file() if storage == "file" else path.is_dir()
145
+
146
+
147
+ def _require_shape(path: Path, storage: Storage) -> None:
148
+ if not _qualifies(path, storage):
149
+ raise RuntimeError(f"cache builder did not create {storage} artifact at {path}")
150
+
151
+
152
+ def _discard(path: Path) -> None:
153
+ if path.is_dir() and not path.is_symlink():
154
+ shutil.rmtree(path, ignore_errors=True)
155
+ else:
156
+ path.unlink(missing_ok=True)
157
+
158
+
159
+ def _build_in_scratch(
160
+ parts: tuple[str, ...],
161
+ storage: Storage,
162
+ build: Callable[[Path], T],
163
+ validate: Callable[[T], None] | None,
164
+ ) -> T:
165
+ with tempfile.TemporaryDirectory(prefix="relarena-cache-") as scratch:
166
+ path = Path(scratch).joinpath(*parts)
167
+ path.parent.mkdir(parents=True, exist_ok=True)
168
+ value = build(path)
169
+ _require_shape(path, storage)
170
+ if validate is not None:
171
+ validate(value)
172
+ return value
173
+
174
+
175
+ def cached_artifact(
176
+ cache: CacheConfig,
177
+ key: str | PurePosixPath,
178
+ *,
179
+ storage: Storage,
180
+ load: Callable[[Path], T],
181
+ build: Callable[[Path], T],
182
+ validate: Callable[[T], None] | None = None,
183
+ warm_hint: str | None = None,
184
+ ) -> T:
185
+ """Load, build, or reject one opaque file or directory artifact."""
186
+ if storage not in ("file", "directory"):
187
+ raise ValueError(f"invalid cache storage shape: {storage!r}")
188
+ parts = _key_parts(key)
189
+ if cache.directory is None or cache.on_miss == "compute":
190
+ return _build_in_scratch(parts, storage, build, validate)
191
+
192
+ destination = _destination(cache.directory, parts)
193
+ if _qualifies(destination, storage):
194
+ value = load(destination)
195
+ if validate is not None:
196
+ validate(value)
197
+ return value
198
+
199
+ if cache.on_miss == "raise":
200
+ hint = "" if warm_hint is None else f" {warm_hint}"
201
+ raise CacheMiss(
202
+ f"cache miss for {str(key)!r} in {cache.directory}.{hint}".rstrip()
203
+ )
204
+
205
+ destination.parent.mkdir(parents=True, exist_ok=True)
206
+ staging = destination.with_name(f".{destination.name}.tmp-{uuid.uuid4().hex}")
207
+ try:
208
+ value = build(staging)
209
+ _require_shape(staging, storage)
210
+ if validate is not None:
211
+ validate(value)
212
+ if storage == "file":
213
+ os.replace(staging, destination)
214
+ else:
215
+ try:
216
+ staging.rename(destination)
217
+ except OSError as exc:
218
+ if exc.errno not in (errno.EEXIST, errno.ENOTEMPTY) or not _qualifies(
219
+ destination, storage
220
+ ):
221
+ raise
222
+ return value
223
+ finally:
224
+ _discard(staging)