cedarkit-query 0.2.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 (46) hide show
  1. cedarkit_query-0.2.1/LICENSE +202 -0
  2. cedarkit_query-0.2.1/MANIFEST.in +5 -0
  3. cedarkit_query-0.2.1/PKG-INFO +41 -0
  4. cedarkit_query-0.2.1/README.md +29 -0
  5. cedarkit_query-0.2.1/docs/normalization-v1.md +88 -0
  6. cedarkit_query-0.2.1/docs/protocol-v1.md +28 -0
  7. cedarkit_query-0.2.1/docs/using-v1.md +5 -0
  8. cedarkit_query-0.2.1/examples/catalog.json +13 -0
  9. cedarkit_query-0.2.1/examples/request.json +18 -0
  10. cedarkit_query-0.2.1/pyproject.toml +26 -0
  11. cedarkit_query-0.2.1/scripts/build_schemas.py +54 -0
  12. cedarkit_query-0.2.1/scripts/check_dist.py +140 -0
  13. cedarkit_query-0.2.1/setup.cfg +4 -0
  14. cedarkit_query-0.2.1/src/cedarkit_query/__init__.py +61 -0
  15. cedarkit_query-0.2.1/src/cedarkit_query/_json.py +124 -0
  16. cedarkit_query-0.2.1/src/cedarkit_query/errors.py +152 -0
  17. cedarkit_query-0.2.1/src/cedarkit_query/model.py +365 -0
  18. cedarkit_query-0.2.1/src/cedarkit_query/normalize.py +967 -0
  19. cedarkit_query-0.2.1/src/cedarkit_query/parameters.py +102 -0
  20. cedarkit_query-0.2.1/src/cedarkit_query/resources.py +268 -0
  21. cedarkit_query-0.2.1/src/cedarkit_query/schemas/catalog-v1.schema.json +369 -0
  22. cedarkit_query-0.2.1/src/cedarkit_query/schemas/common-v1.schema.json +3067 -0
  23. cedarkit_query-0.2.1/src/cedarkit_query/schemas/context-v1.schema.json +6 -0
  24. cedarkit_query-0.2.1/src/cedarkit_query/schemas/error-v1.schema.json +87 -0
  25. cedarkit_query-0.2.1/src/cedarkit_query/schemas/explanation-v1.schema.json +168 -0
  26. cedarkit_query-0.2.1/src/cedarkit_query/schemas/mappings-v1.schema.json +526 -0
  27. cedarkit_query-0.2.1/src/cedarkit_query/schemas/parameters-v1.schema.json +84 -0
  28. cedarkit_query-0.2.1/src/cedarkit_query/schemas/query-v1.schema.json +6 -0
  29. cedarkit_query-0.2.1/src/cedarkit_query/schemas/report-v1.schema.json +69 -0
  30. cedarkit_query-0.2.1/src/cedarkit_query/schemas/request-v1.schema.json +45 -0
  31. cedarkit_query-0.2.1/src/cedarkit_query/validation.py +202 -0
  32. cedarkit_query-0.2.1/src/cedarkit_query.egg-info/PKG-INFO +41 -0
  33. cedarkit_query-0.2.1/src/cedarkit_query.egg-info/SOURCES.txt +44 -0
  34. cedarkit_query-0.2.1/src/cedarkit_query.egg-info/dependency_links.txt +1 -0
  35. cedarkit_query-0.2.1/src/cedarkit_query.egg-info/requires.txt +2 -0
  36. cedarkit_query-0.2.1/src/cedarkit_query.egg-info/top_level.txt +1 -0
  37. cedarkit_query-0.2.1/tests/conftest.py +71 -0
  38. cedarkit_query-0.2.1/tests/test_normalize.py +384 -0
  39. cedarkit_query-0.2.1/tests/test_parameters.py +148 -0
  40. cedarkit_query-0.2.1/tests/test_protocol.py +454 -0
  41. cedarkit_query-0.2.1/tests/test_resources.py +151 -0
  42. cedarkit_query-0.2.1/tests/test_scopes.py +28 -0
  43. cedarkit_query-0.2.1/tests/test_vectors.py +44 -0
  44. cedarkit_query-0.2.1/tests/vectors/v1/invalid.json +77 -0
  45. cedarkit_query-0.2.1/tests/vectors/v1/normalization.json +84 -0
  46. cedarkit_query-0.2.1/tests/vectors/v1/valid.json +112 -0
@@ -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 2020-2026, developers at CMA Earth System Modeling And Prediction Centre.
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.
@@ -0,0 +1,5 @@
1
+ recursive-include docs *.md
2
+ recursive-include scripts *.py
3
+ recursive-include tests *.py *.json
4
+ recursive-include src/cedarkit_query/schemas *.json
5
+ recursive-include examples *.json
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: cedarkit-query
3
+ Version: 0.2.1
4
+ Summary: Language-neutral CedarKit query value models and schemas
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.11
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: jsonschema>=4.20
10
+ Requires-Dist: PyYAML>=6
11
+ Dynamic: license-file
12
+
13
+ # cedarkit-query
14
+
15
+ Immutable Query, Request, Context, Catalog, report and error models for selecting native data. The package contains JSON Schemas and selection algebra. File discovery and GRIB decoding are handled by reki.
16
+
17
+ ```python
18
+ from cedarkit_query import Query, Request
19
+
20
+ query = Query(native={"grib": {
21
+ "discipline": 0,
22
+ "parameterCategory": 0,
23
+ "parameterNumber": 0,
24
+ "typeOfFirstFixedSurface": 103,
25
+ "scaleFactorOfFirstFixedSurface": 0,
26
+ "scaledValueOfFirstFixedSurface": 2,
27
+ }})
28
+ request = Request({
29
+ "api_version": "cedarkit.request/v1",
30
+ "source": {"kind": "file", "path": "original.grib2"},
31
+ "queries": [query.to_dict()],
32
+ })
33
+ ```
34
+
35
+ Use encoded scalar keys and their numeric codes to distinguish local tables, templates, fixed surfaces, intervals and ensemble members. Optional time and vertical selectors describe coordinates. Field values and their units are outside this declaration contract.
36
+
37
+ Version 0.2 removes the former business parameter and mapping models, the `parameter` selector, and product provision checks. Applications that used these contracts supply their native selectors or maintain their business vocabulary separately.
38
+
39
+ - [Request and Query contracts](docs/protocol-v1.md)
40
+ - [Selection algebra](docs/normalization-v1.md)
41
+ - [Native declarations in Python](docs/using-v1.md)
@@ -0,0 +1,29 @@
1
+ # cedarkit-query
2
+
3
+ Immutable Query, Request, Context, Catalog, report and error models for selecting native data. The package contains JSON Schemas and selection algebra. File discovery and GRIB decoding are handled by reki.
4
+
5
+ ```python
6
+ from cedarkit_query import Query, Request
7
+
8
+ query = Query(native={"grib": {
9
+ "discipline": 0,
10
+ "parameterCategory": 0,
11
+ "parameterNumber": 0,
12
+ "typeOfFirstFixedSurface": 103,
13
+ "scaleFactorOfFirstFixedSurface": 0,
14
+ "scaledValueOfFirstFixedSurface": 2,
15
+ }})
16
+ request = Request({
17
+ "api_version": "cedarkit.request/v1",
18
+ "source": {"kind": "file", "path": "original.grib2"},
19
+ "queries": [query.to_dict()],
20
+ })
21
+ ```
22
+
23
+ Use encoded scalar keys and their numeric codes to distinguish local tables, templates, fixed surfaces, intervals and ensemble members. Optional time and vertical selectors describe coordinates. Field values and their units are outside this declaration contract.
24
+
25
+ Version 0.2 removes the former business parameter and mapping models, the `parameter` selector, and product provision checks. Applications that used these contracts supply their native selectors or maintain their business vocabulary separately.
26
+
27
+ - [Request and Query contracts](docs/protocol-v1.md)
28
+ - [Selection algebra](docs/normalization-v1.md)
29
+ - [Native declarations in Python](docs/using-v1.md)
@@ -0,0 +1,88 @@
1
+ # Shared normalization and selection algebra
2
+
3
+ All operations here are pure. They do not inspect a file, fetch a resource,
4
+ connect to a service, resolve aliases from the process environment, or infer a
5
+ product version from a name. The sole selector value is Query.
6
+
7
+ `normalize_query` returns a canonical Query; constructing a Query alone stores
8
+ a validated declaration. Lists are semantic sets, deduplicated and ordered;
9
+ a singleton list is equivalent to a scalar. Pressure normalizes to hPa,
10
+ height/depth to m. Known spelling aliases are explicit, finite mappings.
11
+ Decimal calculations avoid arbitrary tolerances; values that cannot be
12
+ represented losslessly as JSON numbers fail. Named levels and model indices
13
+ have no physical unit. Indices are nonnegative integers; physical layer
14
+ ordering is checked for pressure/depth (bottom larger) and height (top larger),
15
+ without interpreting model indices as physical heights.
16
+
17
+ Time normalizes to UTC; duration normalizes to fixed seconds, preserving up
18
+ to nanosecond precision. Unrepresentable finer precision fails without
19
+ truncation. Calendar month/year durations are not approximated as days. Two
20
+ scalar temporal fields derive the third. Lists/ranges keep their constraints
21
+ and expand only legal `valid_time = time + step` tuples; they are not three
22
+ independent Cartesian axes. Every explicit finite temporal value must
23
+ participate in a legal tuple. This is separate from whether a product exists.
24
+
25
+ ```python
26
+ from cedarkit_query import normalize_query, query_identity
27
+
28
+ q = normalize_query({"level_type": "pressure", "level": 85000, "level_unit": "Pa"})
29
+ assert q.to_dict() == {"level_type": "pressure", "level": 850, "level_unit": "hPa"}
30
+ assert query_identity(q) == query_identity({"level_type": "pressure", "level": 850})
31
+ ```
32
+
33
+ `query_identity(query, context=...)` hashes canonical effective discrete
34
+ conditions and the explicitly supplied semantic context. Equivalent discrete
35
+ range/list forms, scalar derived times, equivalent units, and list order share
36
+ an identity. Supply the relevant source scope and definition versions when
37
+ they contribute to identity. Native constraints remain part of the identity.
38
+
39
+ For named selections, call `prepare_queries(queries, parameters)` before
40
+ computing an effective identity or combining branches. Pass the validated
41
+ parameter index by stable ID, with inherited fixed conditions already applied.
42
+ IDs match exactly. Names and aliases match case-sensitively within the supplied
43
+ definitions, and ambiguity reports candidate IDs. The helper adds fixed
44
+ conditions, normalizes explicit units, and resolves a parent selection to a
45
+ variant when its full fixed conditions already follow from the selection.
46
+ For example, a temperature Query that explicitly selects 200 cm above ground
47
+ can have the same effective identity as `cedarkit.t2m`. Translation into
48
+ product-specific native keys is a source execution step.
49
+
50
+ `expand_queries(queries, max_expansion=10000, member_roles=None, cemc=False)`
51
+ returns unique canonical Query combinations. Whole layer pairs stay intact.
52
+ Multiple Queries form a union, without cross-Query combinations. Omitted
53
+ fields and continuous ranges remain filters, not enumerated field domains.
54
+ Consequently the result count is an explicit discrete-selection count, never
55
+ an expected/actual business-field count. CEMC default member roles require an
56
+ explicit `cemc=True` context; a supplied member mapping overrides that default.
57
+ The algebra does not impose CEMC numbering on other data systems. Number/role
58
+ conditions combine without independent member-role Cartesian axes.
59
+
60
+ The expansion limit is a positive strict integer and can be greater than the
61
+ library default. It is checked on normalized, deduplicated effective
62
+ combinations; exceeding it raises expansion_limit_exceeded with limit,
63
+ count_lower_bound, and origins. There is no truncation or unlimited sentinel.
64
+ The bound does not limit files, requests, records, grid points, memory, or
65
+ network calls. The implementation does not claim a validated capacity or
66
+ provide backend pagination/retry policies.
67
+
68
+ `intersect_queries(left, right, max_expansion=...)` returns their conjunction,
69
+ or None for legal disjoint selections. `combine_queries(steps, scope=...,
70
+ max_expansion=...)` evaluates an AND of OR lists, returns compact branches with
71
+ origins, merges identical branches, and checks each step's effective bound.
72
+ An empty effective selection is an empty branch tuple, never an illegal Query
73
+ containing an empty list. Scope and each submitted Query are validated even
74
+ when a previous step is already empty. Temporal and numeric discrete-range
75
+ intersections preserve their lattices and original paired constraints.
76
+
77
+ `constrain_query(query, fixed_or_scope)` is intentionally different from a
78
+ normal intersection: every explicit scalar/list/every choice must be
79
+ compatible with the binding. A continuous filter may contain a fixed value.
80
+ For a height scope fixed at 2 m, a selector list containing 2 and 10 m
81
+ conflicts, while a continuous 0–10 m range can narrow to 2 m. The same
82
+ constraint semantics apply to native keys.
83
+
84
+ `intersect_scopes(left, right)` combines configuration bounds without enumerating
85
+ an entire product domain. It uses the shared intersection semantics, permits a
86
+ partial vertical bound to gain its type from the other bound, and returns None
87
+ for a known disjoint conjunction. It does not execute a selection or verify every temporal tuple. Effective Query
88
+ preparation and expansion retain their normal legality and max_expansion checks.
@@ -0,0 +1,28 @@
1
+ # Query protocol v1
2
+
3
+ `Query(mapping)` and `Query(**conditions)` create immutable declarations. Use `to_dict()` for a copy and `normalize_query` for normalized selectors. Omitted fields leave the corresponding records unrestricted within the effective source and product scope.
4
+
5
+ | Selector | Accepted form |
6
+ |---|---|
7
+ | `parameter` | A stable business parameter ID, registered name or alias, or a nonempty list of these strings |
8
+ | `native.grib` | ecCodes scalar key predicates, each with a value, a list or a numeric range |
9
+ | `time`, `valid_time` | ISO timestamp with an explicit offset, list or range |
10
+ | `step` | Nonnegative ISO duration, list or range |
11
+ | `level_type`, `level`, `level_unit` | Optional projected vertical coordinate and its input unit |
12
+ | `layer` | Complete bottom and top pair or a list of pairs |
13
+ | `member`, `member_role` | Optional member number or role in a registered source |
14
+
15
+ Ranges are inclusive. An optional positive `every` restricts values to the stated stride. The executor can project coordinates when the native information supports them. Raw keys remain available for selection independently of those projections.
16
+
17
+ Python, JSON and YAML use the same Query schema. `parameter` and `native.grib`
18
+ can appear together and both constrain the same field. A parameter name is
19
+ resolved against explicit definitions by the source integration. The
20
+ declaration itself can be loaded without those definitions.
21
+
22
+ A Request requires `api_version: cedarkit.request/v1`, `source` and a nonempty `queries` list. A file source takes a literal path or an ordered path list, or a directory with a glob. A local source takes a dataset and a root. An optional Context supplies a catalog, scope, execution policy or member roles. File paths resolve relative to the Request or Context document. Loading a declaration performs no source discovery.
23
+
24
+ QueryReport records retrieval and cardinality. A complete expected identity domain requires an independent declaration. Observed fields alone do not establish such a domain. Errors carry a code, a path and context.
25
+
26
+ The `cmadaas.statistics_fields` mapping rule accepts an optional `config.operation="accumulation"` for a generic family and an optional `config.period`, using the same `since_initialization` or `trailing` period declaration as a parameter definition. An executor must reject a period that contradicts the parameter definition and must record the actual start and end of an accepted accumulation. Generic parameter parents can therefore retain their family identity while a reviewed product mapping supplies a fixed window. The optional `config.response_profile="derived_grid"` identifies explicitly reviewed processed-response behavior. Reki’s version 3 forecast contract requires a trailing accumulation; its explicitly registered version 4 forecast contract also supports reviewed instantaneous and since-initialization fields. The retained profile name does not imply that every accepted field is a computed difference. It preserves empty response headers, mapping unit provenance, rounded coordinates and neighboring boundary points. Other mappings retain their existing header checks.
27
+
28
+ A product-specific parameter may encode a vertical meaning that has no generic Query level type, such as a reviewed planetary boundary layer Richardson number. Its scoped joint vertical table can map an empty canonical condition to the exact native level-type and level pair. The executor must reject an additional vertical selector for that row, retain the native association in the report, and avoid inventing a surface, whole-atmosphere or numeric-height coordinate. Service aliases for the same reviewed identity may share a single published mapping so that equivalent historical rows do not introduce ambiguous translations.
@@ -0,0 +1,5 @@
1
+ # Use a native request
2
+
3
+ Load the request with `Request.load(path)` or build it from a mapping. Use `Query` to set native predicates and optional coordinate constraints. Use `reki.from_source(request.source, context=request.context)` and `source.sel(request.queries)` to execute the selection.
4
+
5
+ See [the native protocol](protocol-v1.md) and [the example request](../examples/request.json).
@@ -0,0 +1,13 @@
1
+ {
2
+ "api_version": "cedarkit.catalog/v1",
3
+ "id": "example.catalog",
4
+ "version": "1",
5
+ "datasets": [
6
+ {
7
+ "id": "example",
8
+ "local_layout": [
9
+ "{date_label}/original_{start_time_label}_{forecast_hour_label}.grib2"
10
+ ]
11
+ }
12
+ ]
13
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "api_version": "cedarkit.request/v1",
3
+ "source": {
4
+ "kind": "file",
5
+ "path": "original.grib2"
6
+ },
7
+ "queries": [
8
+ {
9
+ "native": {
10
+ "grib": {
11
+ "discipline": 0,
12
+ "parameterCategory": 0,
13
+ "parameterNumber": 0
14
+ }
15
+ }
16
+ }
17
+ ]
18
+ }
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "cedarkit-query"
7
+ version = "0.2.1"
8
+ description = "Language-neutral CedarKit query value models and schemas"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ dependencies = ["jsonschema>=4.20", "PyYAML>=6"]
14
+
15
+ [dependency-groups]
16
+ test = ["pytest>=8"]
17
+
18
+ [tool.setuptools.packages.find]
19
+ where = ["src"]
20
+ include = ["cedarkit_query*"]
21
+
22
+ [tool.setuptools.package-data]
23
+ cedarkit_query = ["schemas/*.json"]
24
+
25
+ [tool.pytest.ini_options]
26
+ testpaths = ["tests"]
@@ -0,0 +1,54 @@
1
+ """Check/canonicalize the authoritative packaged JSON Schemas (no old generator)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+
9
+ from jsonschema import Draft202012Validator
10
+
11
+ ROOT = Path(__file__).resolve().parents[1] / "src" / "cedarkit_query" / "schemas"
12
+
13
+
14
+ def main():
15
+ parser = argparse.ArgumentParser(description=__doc__)
16
+ parser.add_argument("--check", action="store_true", help="check without rewriting")
17
+ args = parser.parse_args()
18
+ documents = {}
19
+ files = sorted(ROOT.glob("*-v1.schema.json"))
20
+ for path in files:
21
+ schema = json.loads(path.read_text())
22
+ Draft202012Validator.check_schema(schema)
23
+ assert schema["$id"] not in documents, schema["$id"]
24
+ documents[schema["$id"]] = schema
25
+ assert len(documents) == 10, "expected exactly the ten current contract schemas"
26
+
27
+ def refs(node, document):
28
+ if isinstance(node, list):
29
+ for item in node:
30
+ refs(item, document)
31
+ elif isinstance(node, dict):
32
+ if "$ref" in node:
33
+ uri, _, fragment = node["$ref"].partition("#")
34
+ target = documents[uri or document]
35
+ if fragment:
36
+ assert fragment.startswith("/"), fragment
37
+ for key in fragment[1:].split("/"):
38
+ target = target[key.replace("~1", "/").replace("~0", "~")]
39
+ for value in node.values():
40
+ refs(value, document)
41
+
42
+ for path in files:
43
+ schema = json.loads(path.read_text())
44
+ refs(schema, schema["$id"])
45
+ text = json.dumps(schema, ensure_ascii=False, indent=2) + "\n"
46
+ if args.check:
47
+ assert path.read_text() == text, f"noncanonical JSON: {path}"
48
+ else:
49
+ path.write_text(text)
50
+ print("10 authoritative schemas: valid, canonical, and closed local references")
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()
@@ -0,0 +1,140 @@
1
+ """Check this package's sdist/wheel and isolated import; no cross-package harness."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import email
7
+ import os
8
+ from pathlib import Path
9
+ import subprocess
10
+ import tarfile
11
+ import tempfile
12
+ import zipfile
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+ KINDS = (
16
+ "common",
17
+ "query",
18
+ "context",
19
+ "request",
20
+ "report",
21
+ "explanation",
22
+ "error",
23
+ "catalog",
24
+ "parameters",
25
+ "mappings",
26
+ )
27
+ CHECK = """
28
+ import importlib.metadata
29
+ import json
30
+ from pathlib import Path
31
+ import sys
32
+ import cedarkit_query as cq
33
+ import yaml
34
+ assert Path(cq.__file__).resolve().is_relative_to(Path(sys.prefix).resolve())
35
+ assert importlib.metadata.version("cedarkit-query") == sys.argv[1]
36
+ for kind in ("common", "query", "context", "request", "report", "explanation", "error", "catalog", "parameters", "mappings"):
37
+ assert cq.get_schema(kind)["$id"] == f"urn:cedarkit:query:{kind}:v1"
38
+ request = cq.Request.from_dict({"api_version": "cedarkit.request/v1", "source": {"kind": "file", "path": "absent.grib2"}, "queries": [{}]})
39
+ assert request.completeness is None
40
+ assert cq.normalize_query({"level_type":"pressure", "level":85000, "level_unit":"Pa"}).level == 850
41
+ for conditions in (
42
+ {"parameter": "cedarkit.t2m"},
43
+ {"parameter": "cedarkit.t", "level_type": "pressure", "level": 850, "level_unit": "hPa"},
44
+ ):
45
+ data = {
46
+ "api_version": "cedarkit.request/v1",
47
+ "source": {"kind": "local", "dataset": "cma_gfs_gmf", "root": "/CMADAAS"},
48
+ "queries": [{**conditions, "time": "2026-11-02T12:00:00Z", "step": "PT6H"}],
49
+ }
50
+ request = cq.Request.from_dict(data)
51
+ for text in (json.dumps(data), yaml.safe_dump(data)):
52
+ loaded = cq.load_request(text)
53
+ assert loaded == request
54
+ assert cq.query_identity(loaded.queries[0]) == cq.query_identity(request.queries[0])
55
+ assert cq.Query(native={"grib": {"shortName": "2t"}}).native["grib"]["shortName"] == "2t"
56
+ assert not {"reki", "pandas", "xarray", "eccodes", "nuwe_cmadaas"} & set(sys.modules)
57
+ for old in ("RequestList", "Binding", "Response", "Transform", "parse_text_request"):
58
+ assert not hasattr(cq, old)
59
+ print(sys.version.split()[0], "isolated wheel import and 10 packaged schemas: OK")
60
+ """
61
+
62
+
63
+ def main():
64
+ parser = argparse.ArgumentParser(description=__doc__)
65
+ parser.add_argument("--dist", type=Path, default=ROOT / "dist")
66
+ parser.add_argument("--python", default="3.11")
67
+ parser.add_argument("--offline", action="store_true")
68
+ args = parser.parse_args()
69
+ wheels = list(args.dist.glob("*.whl"))
70
+ sdists = list(args.dist.glob("*.tar.gz"))
71
+ assert len(wheels) == len(sdists) == 1, (
72
+ "provide a directory with one exact candidate pair"
73
+ )
74
+ wheel, sdist = wheels[0].resolve(), sdists[0].resolve()
75
+ with tarfile.open(sdist) as archive:
76
+ names = archive.getnames()
77
+ assert sum("/schemas/" in n and n.endswith(".json") for n in names) == 10
78
+ assert (
79
+ sum("/tests/vectors/v1/" in n and n.endswith(".json") for n in names) == 3
80
+ )
81
+ assert sum("/examples/" in n and n.endswith(".json") for n in names) == 2
82
+ for name in (
83
+ "protocol-v1.md",
84
+ "normalization-v1.md",
85
+ ):
86
+ assert any(n.endswith("/docs/" + name) for n in names)
87
+ assert any(n.endswith("/scripts/build_schemas.py") for n in names)
88
+ assert not any(
89
+ n.endswith("/text.py") or n.endswith("/text.json") for n in names
90
+ )
91
+ with zipfile.ZipFile(wheel) as archive:
92
+ names = archive.namelist()
93
+ assert {
94
+ n.split("/")[-1] for n in names if "/schemas/" in n and n.endswith(".json")
95
+ } == {k + "-v1.schema.json" for k in KINDS}
96
+ metadata = email.message_from_bytes(
97
+ archive.read(next(n for n in names if n.endswith("/METADATA")))
98
+ )
99
+ assert metadata["Requires-Python"] == ">=3.11"
100
+ assert metadata.get_all("Requires-Dist") == ["jsonschema>=4.20", "PyYAML>=6"]
101
+ env = dict(os.environ)
102
+ env.pop("PYTHONPATH", None)
103
+ env.pop("PYTHONHOME", None)
104
+ offline = ["--offline"] if args.offline else []
105
+ with tempfile.TemporaryDirectory(prefix="cedarkit-query-wheel-") as temporary:
106
+ workspace = Path(temporary)
107
+ venv = workspace / ".venv"
108
+ interpreter = venv / "bin/python"
109
+ subprocess.run(
110
+ ["uv", "venv", *offline, "--python", args.python, str(venv)],
111
+ check=True,
112
+ env=env,
113
+ )
114
+ subprocess.run(
115
+ [
116
+ "uv",
117
+ "pip",
118
+ "install",
119
+ *offline,
120
+ "--python",
121
+ str(interpreter),
122
+ str(wheel),
123
+ ],
124
+ check=True,
125
+ env=env,
126
+ )
127
+ subprocess.run(
128
+ ["uv", "pip", "check", "--python", str(interpreter)], check=True, env=env
129
+ )
130
+ subprocess.run(
131
+ [str(interpreter), "-I", "-c", CHECK, metadata["Version"]],
132
+ cwd=workspace,
133
+ check=True,
134
+ env=env,
135
+ )
136
+ print("single-package sdist, wheel resources, lightweight import: OK")
137
+
138
+
139
+ if __name__ == "__main__":
140
+ main()