cedarkit-query 0.2.1__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,102 @@
1
+ """Business parameter binding against an explicit in-memory definition set."""
2
+
3
+ from ._json import canonical
4
+ from .errors import QueryError
5
+ from .model import Query
6
+ from .normalize import constrain_query, normalize_query
7
+
8
+
9
+ def _resolve(name, parameters):
10
+ if name in parameters:
11
+ return name
12
+ matches = sorted(
13
+ pid
14
+ for pid, definition in parameters.items()
15
+ if name == definition["name"] or name in definition.get("aliases", ())
16
+ )
17
+ if len(matches) != 1:
18
+ raise QueryError(
19
+ "invalid_query",
20
+ "/parameter",
21
+ "ambiguous parameter" if matches else "unknown parameter",
22
+ {
23
+ "reason": "ambiguous_parameter" if matches else "unknown_parameter",
24
+ "candidates": matches,
25
+ },
26
+ )
27
+ return matches[0]
28
+
29
+
30
+ def _ancestors(pid, parameters):
31
+ while (pid := parameters[pid].get("parent")) is not None:
32
+ yield pid
33
+
34
+
35
+ def _query_conditions(fixed):
36
+ return {key: value for key, value in fixed.items() if key != "statistics"}
37
+
38
+
39
+ def _equivalent_variant(query, pid, parameters, statistics):
40
+ equivalent = set()
41
+ for candidate, definition in parameters.items():
42
+ if pid not in _ancestors(candidate, parameters):
43
+ continue
44
+ fixed = definition.get("fixed_conditions", {})
45
+ if fixed.get("statistics") != statistics:
46
+ continue
47
+ try:
48
+ refined = constrain_query(query, _query_conditions(fixed))
49
+ except QueryError as exc:
50
+ if exc.code in {"constraint_conflict", "invalid_query"}:
51
+ continue
52
+ raise
53
+ if refined == query:
54
+ equivalent.add(candidate)
55
+ ancestors = {
56
+ parent for candidate in equivalent for parent in _ancestors(candidate, parameters)
57
+ }
58
+ deepest = sorted(equivalent - ancestors)
59
+ if len(deepest) > 1:
60
+ raise QueryError(
61
+ "invalid_query",
62
+ "/parameter",
63
+ "equivalent parameter variants are ambiguous",
64
+ {"reason": "ambiguous_parameter", "candidates": deepest},
65
+ )
66
+ return deepest[0] if deepest else pid
67
+
68
+
69
+ def prepare_queries(queries, parameters):
70
+ """Resolve names and fixed conditions before selection algebra or identity.
71
+
72
+ Parameters is the caller's validated index by stable ID. Its records carry
73
+ names, optional aliases and parent IDs, and effective fixed conditions
74
+ with inheritance already applied. No definitions or data are loaded here.
75
+ """
76
+ prepared = {}
77
+ for value in queries:
78
+ raw = Query(value).to_dict()
79
+ if "parameter" not in raw:
80
+ query = normalize_query(raw)
81
+ prepared[canonical(query)] = query
82
+ continue
83
+ names = raw["parameter"]
84
+ for name in names if isinstance(names, list) else [names]:
85
+ pid = _resolve(name, parameters)
86
+ fixed = parameters[pid].get("fixed_conditions", {})
87
+ statistics = fixed.get("statistics")
88
+ if statistics and statistics.get("over") == "ensemble" and (
89
+ "member" in raw or "member_role" in raw
90
+ ):
91
+ field = "member" if "member" in raw else "member_role"
92
+ raise QueryError(
93
+ "constraint_conflict",
94
+ "/" + field,
95
+ "individual member selection conflicts with an ensemble statistic",
96
+ {"reason": "fixed_condition_conflict"},
97
+ )
98
+ bound = constrain_query({**raw, "parameter": pid}, _query_conditions(fixed))
99
+ resolved = _equivalent_variant(bound, pid, parameters, statistics)
100
+ result = Query({**bound.to_dict(), "parameter": resolved})
101
+ prepared[canonical(result)] = result
102
+ return tuple(prepared[key] for key in sorted(prepared))
@@ -0,0 +1,268 @@
1
+ """Pure validation for definitions, mappings and catalog resource combinations."""
2
+
3
+ from ._json import canonical, plain
4
+ from .errors import QueryError
5
+ from .normalize import _normal_selector, _normalize, constrain_query, intersect_scopes
6
+
7
+
8
+ def _error(path, message):
9
+ raise QueryError("invalid_config", path, message)
10
+
11
+
12
+ def _index(rows, key, path):
13
+ result = {}
14
+ for index, row in enumerate(rows):
15
+ name = row[key]
16
+ if name in result:
17
+ _error(f"{path}/{index}/{key}", "duplicate identifier")
18
+ result[name] = row
19
+ return result
20
+
21
+
22
+ def _fixed(fixed, path, *, level_type=None):
23
+ query = {key: value for key, value in fixed.items() if key != "statistics"}
24
+ if level_type is not None:
25
+ query.setdefault("level_type", level_type)
26
+ result = _normalize(query, path, allow_unbound=True)
27
+ if "statistics" in fixed:
28
+ result["statistics"] = fixed["statistics"]
29
+ return result
30
+
31
+
32
+ def _effective(data):
33
+ definitions = _index(data["parameters"], "parameter_id", "/parameters")
34
+ effective = {}
35
+ visiting = set()
36
+
37
+ def resolve(pid, path):
38
+ if pid in visiting:
39
+ _error(path, "parameter dependency cycle")
40
+ if pid not in definitions:
41
+ _error(path, f"unknown parameter {pid}")
42
+ if pid in effective:
43
+ return effective[pid]
44
+ visiting.add(pid)
45
+ row = definitions[pid]
46
+ path = f"/parameters/{pid}"
47
+ parent = resolve(row["parent"], path + "/parent") if "parent" in row else {}
48
+ inherited = parent.get("fixed_conditions", {})
49
+ fixed = _fixed(
50
+ row.get("fixed_conditions", {}),
51
+ path + "/fixed_conditions",
52
+ level_type=inherited.get("level_type"),
53
+ )
54
+ if "statistics" in fixed and "statistics" in inherited:
55
+ parent_stats = inherited["statistics"]
56
+ child_stats = fixed["statistics"]
57
+ for key in parent_stats.keys() & child_stats.keys():
58
+ if parent_stats[key] != child_stats[key]:
59
+ _error(
60
+ path + "/fixed_conditions/statistics/" + key,
61
+ "conflicting inherited statistic",
62
+ )
63
+ fixed["statistics"] = {**parent_stats, **child_stats}
64
+ inherited = {
65
+ key: value for key, value in inherited.items() if key != "statistics"
66
+ }
67
+ for key in fixed.keys() & inherited.keys():
68
+ if fixed[key] != inherited[key]:
69
+ _error(
70
+ path + "/fixed_conditions/" + key, "conflicting inherited condition"
71
+ )
72
+ fixed = _fixed({**inherited, **fixed}, path + "/fixed_conditions")
73
+ if "level" in fixed and "layer" in fixed:
74
+ _error(path + "/fixed_conditions", "level and layer are mutually exclusive")
75
+ statistics = fixed.get("statistics", {})
76
+ if "of" in statistics:
77
+ resolve(
78
+ statistics["of"]["parameter_id"],
79
+ path + "/fixed_conditions/statistics/of",
80
+ )
81
+ result = {
82
+ **{
83
+ key: parent[key]
84
+ for key in ("unit", "description", "description_cn")
85
+ if key in parent
86
+ },
87
+ **row,
88
+ "fixed_conditions": fixed,
89
+ }
90
+ if "unit" not in result:
91
+ _error(path + "/unit", "effective unit is required")
92
+ effective[pid] = result
93
+ visiting.remove(pid)
94
+ return result
95
+
96
+ for pid, row in definitions.items():
97
+ aliases = row.get("aliases", ())
98
+ if row["name"] in aliases or any(
99
+ name in definitions and name != pid for name in (row["name"], *aliases)
100
+ ):
101
+ _error(
102
+ f"/parameters/{pid}/aliases",
103
+ "name or alias conflicts with a parameter identity",
104
+ )
105
+ resolve(pid, "/parameters")
106
+ return effective
107
+
108
+
109
+ def validate_resource(data, kind):
110
+ try:
111
+ if kind == "parameters":
112
+ _effective(data)
113
+ return
114
+ _index(data["mappings"], "id", "/mappings")
115
+ tables = _index(data["tables"], "id", "/tables")
116
+ for index, row in enumerate(data["mappings"]):
117
+ path = f"/mappings/{index}"
118
+ if row["backend"] != data["backend"]:
119
+ _error(path + "/backend", "mapping and resource backends differ")
120
+ if {"parameter", "native"} & row["when"].keys():
121
+ _error(path + "/when", "when accepts business conditions only")
122
+ _normalize(row["when"], path + "/when", allow_unbound=True)
123
+ for key, value in row["native"]["match"].items():
124
+ _normal_selector(
125
+ value,
126
+ "number" if isinstance(value, dict) else "literal",
127
+ f"{path}/native/match/{key}",
128
+ )
129
+ for duty, rule in row["native"].get("translate", {}).items():
130
+ table = rule.get("config", {}).get("table")
131
+ if table is not None and table not in tables:
132
+ _error(
133
+ f"{path}/native/translate/{duty}/config/table",
134
+ "missing shared table",
135
+ )
136
+ except QueryError as exc:
137
+ if exc.code == "invalid_config":
138
+ raise
139
+ raise QueryError(
140
+ "invalid_config", exc.path, exc.message, dict(exc.context)
141
+ ) from exc
142
+
143
+
144
+ def validate_resource_set(parameters, mappings, catalog, dataset_id):
145
+ """Validate the selected dataset's resource references and return effective definitions."""
146
+ from .model import Catalog, Mappings
147
+
148
+ effective = effective_parameters(parameters)
149
+ datasets = {row["id"]: row for row in Catalog(catalog).to_dict()["datasets"]}
150
+ if dataset_id not in datasets:
151
+ _error("/datasets", "dataset is absent from catalog")
152
+ products = {
153
+ (row["id"], row["version"]): row
154
+ for row in datasets[dataset_id].get("products", ())
155
+ }
156
+ if not products:
157
+ _error("/datasets/products", "dataset has no product binding")
158
+
159
+ for product in products.values():
160
+ for key in ("scope", "provides", "expected_domain"):
161
+ queries = [product[key]] if key == "scope" else product.get(key, ())
162
+ for query in queries:
163
+ names = query.get("parameter", ())
164
+ if isinstance(names, str):
165
+ names = (names,)
166
+ if any(name not in effective for name in names):
167
+ _error(f"/datasets/products/{key}", "unknown catalog parameter ID")
168
+
169
+ resources = _index(
170
+ [Mappings(value).to_dict() for value in mappings], "backend", "/mappings"
171
+ )
172
+ applicable = {identity: [] for identity in products}
173
+ for resource in resources.values():
174
+ for row in resource["mappings"]:
175
+ pid = row["parameter_id"]
176
+ path = f"/mappings/{row['id']}"
177
+ if pid not in effective:
178
+ _error(path + "/parameter_id", "unknown mapped parameter ID")
179
+ applies = row["applies_to"]
180
+ if not _applies(applies, "dataset", dataset_id):
181
+ continue
182
+ targets = [
183
+ (product, version)
184
+ for product, version in products
185
+ if _applies(applies, "product", product)
186
+ and _applies(applies, "product_version", version)
187
+ ]
188
+ if not targets:
189
+ _error(
190
+ path + "/applies_to",
191
+ "mapping refers to an unavailable product or version",
192
+ )
193
+ fixed = {
194
+ k: v
195
+ for k, v in effective[pid]["fixed_conditions"].items()
196
+ if k != "statistics"
197
+ }
198
+ try:
199
+ bound = constrain_query(row["when"], fixed).to_dict()
200
+ except QueryError as exc:
201
+ raise QueryError(
202
+ "invalid_config",
203
+ path + "/when",
204
+ "mapping conflicts with parameter conditions",
205
+ ) from exc
206
+ backend = resource["backend"]
207
+ native = canonical(row["native"]["match"])
208
+ time_scope = {"time": applies["time"]} if "time" in applies else {}
209
+ for target in targets:
210
+ for (
211
+ other_backend,
212
+ other_pid,
213
+ other_native,
214
+ other_bound,
215
+ other_time,
216
+ ) in applicable[target]:
217
+ if (
218
+ (other_backend, other_pid, other_native)
219
+ == (backend, pid, native)
220
+ and intersect_scopes(bound, other_bound) is not None
221
+ and intersect_scopes(time_scope, other_time) is not None
222
+ ):
223
+ _error(
224
+ path + "/native/match",
225
+ "overlapping mapping for the same parameter and native keys",
226
+ )
227
+ applicable[target].append((backend, pid, native, bound, time_scope))
228
+ for identity, product in products.items():
229
+ backends = {
230
+ "cmadaas" if source["kind"] == "cmadaas" else "grib2"
231
+ for source in product["sources"]
232
+ }
233
+ for key in ("provides", "expected_domain"):
234
+ for index, query in enumerate(product.get(key, ())):
235
+ names = query.get("parameter", ())
236
+ if isinstance(names, str):
237
+ names = (names,)
238
+ conditions = {
239
+ key: value for key, value in query.items() if key != "parameter"
240
+ }
241
+ for pid in names:
242
+ covered = {
243
+ backend
244
+ for backend, mapped, _, bound, time_scope in applicable[
245
+ identity
246
+ ]
247
+ if pid == mapped
248
+ and intersect_scopes(conditions, bound) is not None
249
+ and intersect_scopes(conditions, time_scope) is not None
250
+ }
251
+ if not backends <= covered:
252
+ _error(
253
+ f"/datasets/products/{key}/{index}",
254
+ "parameter has no applicable mapping",
255
+ )
256
+ return plain(effective)
257
+
258
+
259
+ def _applies(applies, key, value):
260
+ selector = applies.get(key, value)
261
+ return value in selector if isinstance(selector, list) else value == selector
262
+
263
+
264
+ def effective_parameters(parameters):
265
+ """Expand validated parameter definitions for binding."""
266
+ from .model import Parameters
267
+
268
+ return _effective(Parameters(parameters).to_dict())