arrayprobe 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. arrayprobe/__init__.py +219 -0
  2. arrayprobe/__main__.py +19 -0
  3. arrayprobe/_v314_lazy.py +48 -0
  4. arrayprobe/ai_ready.py +212 -0
  5. arrayprobe/attributed_export.py +1333 -0
  6. arrayprobe/authordefaults.py +267 -0
  7. arrayprobe/cli.py +3510 -0
  8. arrayprobe/combine.py +12 -0
  9. arrayprobe/compare.py +950 -0
  10. arrayprobe/config.py +1239 -0
  11. arrayprobe/constants.py +12 -0
  12. arrayprobe/count_closure.py +204 -0
  13. arrayprobe/diagnostic_views.py +769 -0
  14. arrayprobe/diode_report.py +265 -0
  15. arrayprobe/driver/__init__.py +5 -0
  16. arrayprobe/driver/_load_record.py +331 -0
  17. arrayprobe/driver/preflight_inputs.py +250 -0
  18. arrayprobe/driver/reprocess.py +553 -0
  19. arrayprobe/driver/run_flight.py +8166 -0
  20. arrayprobe/driver/tas_from_probe_housekeeping.py +124 -0
  21. arrayprobe/dropsize.py +519 -0
  22. arrayprobe/friendly.py +206 -0
  23. arrayprobe/geometry/__init__.py +77 -0
  24. arrayprobe/geometry/min_rectangle.py +92 -0
  25. arrayprobe/intarr.py +12 -0
  26. arrayprobe/intarr_analysis.py +16 -0
  27. arrayprobe/intarr_plots.py +12 -0
  28. arrayprobe/inventory.py +129 -0
  29. arrayprobe/jit_kernels.py +344 -0
  30. arrayprobe/lwc.py +44 -0
  31. arrayprobe/masks.py +349 -0
  32. arrayprobe/matio.py +410 -0
  33. arrayprobe/matlab_compat.py +13 -0
  34. arrayprobe/ncio.py +26 -0
  35. arrayprobe/particle.py +55 -0
  36. arrayprobe/particle_perimeter.py +12 -0
  37. arrayprobe/products.py +78 -0
  38. arrayprobe/profiles.py +179 -0
  39. arrayprobe/provenance.py +21 -0
  40. arrayprobe/py.typed +11 -0
  41. arrayprobe/readers/__init__.py +9 -0
  42. arrayprobe/readers/dmt.py +603 -0
  43. arrayprobe/readers/mask_csv.py +12 -0
  44. arrayprobe/readers/pms.py +12 -0
  45. arrayprobe/readers/sea.py +433 -0
  46. arrayprobe/readers/tasinfo.py +12 -0
  47. arrayprobe/regimes.py +507 -0
  48. arrayprobe/render.py +728 -0
  49. arrayprobe/reproduce_report.py +149 -0
  50. arrayprobe/review_agreement.py +135 -0
  51. arrayprobe/review_sampling.py +327 -0
  52. arrayprobe/run_page.py +624 -0
  53. arrayprobe/sample_area.py +12 -0
  54. arrayprobe/selector.py +206 -0
  55. arrayprobe/sizing.py +151 -0
  56. arrayprobe/time_convert.py +12 -0
  57. arrayprobe/timing_closure.py +141 -0
  58. arrayprobe/tools/__init__.py +27 -0
  59. arrayprobe/tools/make_demo_flight.py +1089 -0
  60. arrayprobe/tools/make_tas_file.py +760 -0
  61. arrayprobe/tools/probe_comparison.py +569 -0
  62. arrayprobe/tools/synthetic_truth.py +698 -0
  63. arrayprobe/tools/tas_sources.py +705 -0
  64. arrayprobe/triage_context.py +488 -0
  65. arrayprobe/triage_server.py +5215 -0
  66. arrayprobe/tune/__init__.py +15 -0
  67. arrayprobe/tune/diodes.py +400 -0
  68. arrayprobe/tune/distributions.py +300 -0
  69. arrayprobe/tune/sample.py +243 -0
  70. arrayprobe/tune/score.py +230 -0
  71. arrayprobe/tune/settings.py +354 -0
  72. arrayprobe/validate_by_condition.py +208 -0
  73. arrayprobe/validation_report.py +166 -0
  74. arrayprobe-0.1.0.dist-info/METADATA +260 -0
  75. arrayprobe-0.1.0.dist-info/RECORD +189 -0
  76. arrayprobe-0.1.0.dist-info/WHEEL +5 -0
  77. arrayprobe-0.1.0.dist-info/entry_points.txt +2 -0
  78. arrayprobe-0.1.0.dist-info/licenses/LICENSE +31 -0
  79. arrayprobe-0.1.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +47 -0
  80. arrayprobe-0.1.0.dist-info/licenses/NOTICE.md +369 -0
  81. arrayprobe-0.1.0.dist-info/top_level.txt +4 -0
  82. arrayprobe_soda2/__init__.py +131 -0
  83. arrayprobe_soda2/angles.py +143 -0
  84. arrayprobe_soda2/aspect_ratio.py +541 -0
  85. arrayprobe_soda2/backfill.py +100 -0
  86. arrayprobe_soda2/binary_dof.py +181 -0
  87. arrayprobe_soda2/buildindex.py +113 -0
  88. arrayprobe_soda2/decompress_dmt.py +285 -0
  89. arrayprobe_soda2/enhancement_hooks.py +275 -0
  90. arrayprobe_soda2/export_ascii.py +732 -0
  91. arrayprobe_soda2/export_ncdf.py +683 -0
  92. arrayprobe_soda2/export_ncdf_raf.py +396 -0
  93. arrayprobe_soda2/fillholes.py +161 -0
  94. arrayprobe_soda2/find_radius.py +105 -0
  95. arrayprobe_soda2/findsize.py +407 -0
  96. arrayprobe_soda2/fit_poisson.py +170 -0
  97. arrayprobe_soda2/fix2dimage.py +63 -0
  98. arrayprobe_soda2/fixraking.py +162 -0
  99. arrayprobe_soda2/fixstuckbits.py +146 -0
  100. arrayprobe_soda2/hvps4_read_frame.py +121 -0
  101. arrayprobe_soda2/jit_kernels.py +152 -0
  102. arrayprobe_soda2/label_blobs.py +177 -0
  103. arrayprobe_soda2/min_circle_fast.py +320 -0
  104. arrayprobe_soda2/particlesort.py +703 -0
  105. arrayprobe_soda2/pbp_writer.py +558 -0
  106. arrayprobe_soda2/poisson_spot_correct.py +183 -0
  107. arrayprobe_soda2/princomp.py +107 -0
  108. arrayprobe_soda2/probespecs.py +361 -0
  109. arrayprobe_soda2/process_2d.py +1364 -0
  110. arrayprobe_soda2/process_2d_parallel.py +626 -0
  111. arrayprobe_soda2/process_hk.py +512 -0
  112. arrayprobe_soda2/processbuffer_2dc.py +155 -0
  113. arrayprobe_soda2/processbuffer_cip.py +213 -0
  114. arrayprobe_soda2/processbuffer_f2dc.py +139 -0
  115. arrayprobe_soda2/processbuffer_spec.py +441 -0
  116. arrayprobe_soda2/processbuffer_tail.py +350 -0
  117. arrayprobe_soda2/pth_readers.py +245 -0
  118. arrayprobe_soda2/py.typed +11 -0
  119. arrayprobe_soda2/read2dbuffer.py +371 -0
  120. arrayprobe_soda2/reject.py +246 -0
  121. arrayprobe_soda2/reprocess_pbp.py +156 -0
  122. arrayprobe_soda2/sample_area.py +264 -0
  123. arrayprobe_soda2/save_writer.py +480 -0
  124. arrayprobe_soda2/sea.py +324 -0
  125. arrayprobe_soda2/spec_absolutepointers.py +109 -0
  126. arrayprobe_soda2/spec_decompress.py +203 -0
  127. arrayprobe_soda2/spec_index.py +476 -0
  128. arrayprobe_soda2/spec_read_frame.py +286 -0
  129. arrayprobe_soda2/spec_read_hk.py +301 -0
  130. arrayprobe_soda2/spec_readint.py +127 -0
  131. arrayprobe_soda2/timeconv.py +77 -0
  132. arrayprobe_soda2/update_op.py +101 -0
  133. arrayprobe_uiops/__init__.py +45 -0
  134. arrayprobe_uiops/combine.py +192 -0
  135. arrayprobe_uiops/combine_fork.py +359 -0
  136. arrayprobe_uiops/constants.py +830 -0
  137. arrayprobe_uiops/decode_naming.py +113 -0
  138. arrayprobe_uiops/diode_mask.py +250 -0
  139. arrayprobe_uiops/engine_absence.py +41 -0
  140. arrayprobe_uiops/export_oap.py +325 -0
  141. arrayprobe_uiops/geometry_core.py +366 -0
  142. arrayprobe_uiops/habit.py +749 -0
  143. arrayprobe_uiops/habit_core.py +248 -0
  144. arrayprobe_uiops/hollow_size_rule.py +376 -0
  145. arrayprobe_uiops/imgproc.py +2081 -0
  146. arrayprobe_uiops/imgproc_core.py +275 -0
  147. arrayprobe_uiops/intarr.py +167 -0
  148. arrayprobe_uiops/intarr_analysis.py +569 -0
  149. arrayprobe_uiops/intarr_plots.py +119 -0
  150. arrayprobe_uiops/jit_kernels.py +430 -0
  151. arrayprobe_uiops/lwc.py +70 -0
  152. arrayprobe_uiops/matlab_compat.py +860 -0
  153. arrayprobe_uiops/measure.py +346 -0
  154. arrayprobe_uiops/min_circle.py +204 -0
  155. arrayprobe_uiops/min_ellipse.py +161 -0
  156. arrayprobe_uiops/min_rectangle.py +200 -0
  157. arrayprobe_uiops/ncar_2dc_timing.py +100 -0
  158. arrayprobe_uiops/ncio.py +810 -0
  159. arrayprobe_uiops/oap_read.py +228 -0
  160. arrayprobe_uiops/particle.py +51 -0
  161. arrayprobe_uiops/particle_perimeter.py +94 -0
  162. arrayprobe_uiops/particle_physics.py +199 -0
  163. arrayprobe_uiops/pecan_params.py +134 -0
  164. arrayprobe_uiops/probe_cases.py +298 -0
  165. arrayprobe_uiops/product_sanity.py +337 -0
  166. arrayprobe_uiops/profile.py +71 -0
  167. arrayprobe_uiops/profiles.py +756 -0
  168. arrayprobe_uiops/provenance.py +804 -0
  169. arrayprobe_uiops/py.typed +11 -0
  170. arrayprobe_uiops/qc.py +169 -0
  171. arrayprobe_uiops/readers/__init__.py +8 -0
  172. arrayprobe_uiops/readers/mask_csv.py +74 -0
  173. arrayprobe_uiops/readers/pms.py +239 -0
  174. arrayprobe_uiops/readers/tasinfo.py +57 -0
  175. arrayprobe_uiops/rect_ellipse.py +129 -0
  176. arrayprobe_uiops/register_image_assisted.py +25 -0
  177. arrayprobe_uiops/reject.py +501 -0
  178. arrayprobe_uiops/reject_core.py +220 -0
  179. arrayprobe_uiops/sample_area.py +93 -0
  180. arrayprobe_uiops/sizedist.py +1923 -0
  181. arrayprobe_uiops/sizedist_core.py +814 -0
  182. arrayprobe_uiops/sizedist_tables.py +642 -0
  183. arrayprobe_uiops/spec.py +1094 -0
  184. arrayprobe_uiops/spec_core.py +703 -0
  185. arrayprobe_uiops/stray_pixel.py +103 -0
  186. arrayprobe_uiops/tas.py +191 -0
  187. arrayprobe_uiops/time_convert.py +41 -0
  188. uiops/__init__.py +402 -0
  189. uiops/py.typed +11 -0
@@ -0,0 +1,804 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """One parser for every ``.call`` provenance sidecar this project writes -- and ``None`` when a
3
+ product has none.
4
+
5
+ **Why this module exists** (2026-09-18). A 1.25 GB CIP product was described as a v3.5
6
+ product for a full day when the v3.1.4 engine wrote it. The cause was not inattention; it was
7
+ shipped code. ``src/arrayprobe/cli.py:1027`` reads::
8
+
9
+ stamped = "3.5" if stamp.startswith("engine=3.5 ") else "3.1.4"
10
+
11
+ so an *absent* stamp (``OSError -> ""``), a JSON stamp, a truncated stamp and a genuine v3.1.4
12
+ stamp are all read as ``"3.1.4"``. Absence and a positive declaration are indistinguishable by
13
+ construction, and no amount of care at the keyboard can tell them apart afterwards.
14
+
15
+ **The contract, and the one rule that matters.** :attr:`Stamp.engine` is ``"3.1.4"``, ``"3.5"``,
16
+ ``"soda2"`` or ``None``. ``None`` means *the stamp does not record an engine* -- it is never
17
+ filled in from a date, a filename, a directory, a sibling file or a default. A caller that needs
18
+ a definite engine asks :func:`engine_of`, which raises rather than guesses. That is the whole
19
+ point: this module is allowed to say "I do not know", and every consumer is thereby forced to.
20
+
21
+ **Five formats, one parser.** All five are in the repository today (measured 2026-09-18):
22
+
23
+ ``driver``
24
+ ``scripts/run_flight.py``'s one-line text, ``engine=3.1.4 profile=oracles-production
25
+ reject=(...) shadow_diode=none``. Written by :func:`write_stamp` there and by :func:`write`
26
+ here, character for character the same shape -- ``tests/test_run_from_config.py``'s
27
+ ``ValidatedCallStampsAreByteIdentical`` pins that text and this module does not move it.
28
+ A v3.1.4 stamp written before 2026-09-15 has no ``engine=`` key at all, and is therefore
29
+ ``engine=None`` here. ``scripts/run_flight.py:_stamps_equivalent`` still reads such a stamp as
30
+ v3.1.4 *for the purpose of resume equality*, which is a different question with a different
31
+ safe answer (is this the same configuration I am about to run?); this module answers "what
32
+ wrote it", where the honest answer is that the file does not say.
33
+
34
+ ``v35-combine``
35
+ ``arrayprobe_uiops/combine.py``'s two-line text: the driver shape on line 1
36
+ (``engine=3.5 combine=borrowed-oracles-fork:combine_sizedist.m opt_in=...``) plus
37
+ ``inputs=<names>`` on line 2; through ``scripts/run_flight.py``, a third line
38
+ ``inputs_built_with=(<the inputs' stamp>)``.
39
+
40
+ ``soda2-pbp``
41
+ ``cli.py``'s ``.pbp.call`` JSON, whose ``"engine"`` key is the string ``"soda2"``.
42
+
43
+ ``legacy-json``
44
+ The four hand-rolled JSON dicts the ``_decoded/`` lane scripts write (``stage``/``profile``/
45
+ ``reject``; ``stage``/``tree``/``tas_source``; ...). **None of them carries an engine key**, so
46
+ every one of them is ``engine=None``. This is the format the CIP product carries, and reading
47
+ it as v3.1.4 is precisely the failure above.
48
+
49
+ ``unparseable``
50
+ A stamp that exists and is neither key=value text nor JSON -- a truncation, most likely.
51
+ It is deliberately not folded into ``unstamped``: saying "no stamp" about a file that has one
52
+ is the same class of untruth this module exists to stop.
53
+
54
+ **Stdlib only, and no arithmetic on data.** Nothing here reads a product's contents, so importing
55
+ it costs nothing and it can be imported from any engine, any tool and any lane script. It is a
56
+ ``TOOLING`` module in :data:`uiops.CATALOGUE`.
57
+
58
+ **It lives in the v3.5 engine** (moved from ``arrayprobe/provenance.py`` 2026-09-30):
59
+ code both engines share lives here, so deleting the v3.1.4 package breaks nothing that reads a
60
+ stamp. ``arrayprobe.provenance`` remains as an alias of this module for the v3.1.4 callers.
61
+
62
+ **A sidecar is keyed by name, so it does not survive a hardlink, copy or rename** -- the product
63
+ carries nothing inside it. :func:`report` prints ``nlink`` for exactly that reason. Whether the
64
+ products should carry two global attributes instead is an open design question
65
+ ; until it is settled, a stamp is
66
+ what there is.
67
+ """
68
+
69
+ from __future__ import annotations
70
+
71
+ import json
72
+ import os
73
+ import re
74
+ import subprocess
75
+ from collections.abc import Iterable
76
+ from dataclasses import dataclass, field
77
+ from pathlib import Path
78
+ from typing import Any
79
+
80
+ __all__ = [
81
+ "ATTR_CALL",
82
+ "ATTR_ENGINE",
83
+ "ATTR_PREFIX",
84
+ "ATTR_PROFILE",
85
+ "ATTR_STAGE",
86
+ "CALL_SUFFIX",
87
+ "ENGINES",
88
+ "EngineUnrecorded",
89
+ "FORMATS",
90
+ "PROFILE_UNSTATED",
91
+ "PROVENANCE_ATTRS",
92
+ "engine_attrs",
93
+ "ProvenanceDisagreement",
94
+ "STATES",
95
+ "Stamp",
96
+ "Unstamped",
97
+ "attrs_for",
98
+ "call_path",
99
+ "disagreements",
100
+ "engine_of",
101
+ "is_provenance_attr",
102
+ "parse",
103
+ "read",
104
+ "read_in_file_stamp",
105
+ "read_text",
106
+ "report",
107
+ "require",
108
+ "stamp_from_attrs",
109
+ "stamp_text",
110
+ "state",
111
+ "write",
112
+ ]
113
+
114
+ #: ``scripts/run_flight.py:call_path``'s naming: the stamp lives beside the product, never inside
115
+ #: it.
116
+ CALL_SUFFIX = ".call"
117
+
118
+ #: Every engine name a stamp may record. ``None`` -- not in this tuple -- is the fourth answer.
119
+ ENGINES: tuple[str, ...] = ("3.1.4", "3.5", "soda2")
120
+
121
+ #: Every value :attr:`Stamp.format` may take.
122
+ FORMATS: tuple[str, ...] = ("driver", "v35-combine", "soda2-pbp", "legacy-json", "unparseable")
123
+
124
+ #: Every value :func:`state` may return. ``unparseable`` extends the four-format set on purpose;
125
+ #: see the module docstring.
126
+ STATES: tuple[str, ...] = (
127
+ "stamped", "unstamped", "orphan-stamp", "in-flight", "legacy-json", "unparseable",
128
+ )
129
+
130
+ #: The prefix every provenance **global attribute** carries (2026-09-18).
131
+ #:
132
+ #: A sidecar is keyed by filename, so a rename, copy or hardlink drops it -- which is exactly how a
133
+ #: 1.25 GB v3.1.4 CIP product came to be indexed under a name carrying no stamp at all. An
134
+ #: attribute travels with the bytes.
135
+ #:
136
+ #: The prefix is lowercase-with-underscores on purpose. Every attribute UIOOPS itself writes is
137
+ #: Title Case, usually with a space (``'Creation Time'``, ``'SA Method'``, ``'Data Source'``,
138
+ #: ``'Dmax Definition'``), so nothing here can collide with the output contract, and
139
+ #: :func:`is_provenance_attr` can recognise ours **by shape** rather than by an enumerated list
140
+ #: that would silently stop covering a name added later.
141
+ ATTR_PREFIX = "arrayprobe_"
142
+
143
+ #: The engine that wrote the file: one of :data:`ENGINES`, never a default.
144
+ ATTR_ENGINE = ATTR_PREFIX + "engine"
145
+
146
+ #: The fidelity profile, when the stage takes one.
147
+ ATTR_PROFILE = ATTR_PREFIX + "profile"
148
+
149
+ #: The stage, when the writer names one.
150
+ ATTR_STAGE = ATTR_PREFIX + "stage"
151
+
152
+ #: The whole stamp text, character for character what the ``.call`` sidecar holds -- both are
153
+ #: built by :func:`stamp_text`, so they cannot drift by construction. This is the record; the three
154
+ #: keys above are the same information split out so ``ncdump -h`` is readable without a parser.
155
+ ATTR_CALL = ATTR_PREFIX + "call"
156
+
157
+ #: Every provenance attribute name this module writes.
158
+ #:
159
+ #: **This is deliberately NOT a second ``VOLATILE_ATTRS``**
160
+ #: (the pipeline benchmark's set). That set means *"differs between two otherwise-identical
161
+ #: runs"* -- ``'Creation Time'`` and nothing else, pinned by
162
+ #: ``tests/test_benchmark_fidelity_gate.py``. These attributes are the opposite: deterministic,
163
+ #: meaningful, and exactly what a digest should catch. The two comparisons want opposite answers:
164
+ #:
165
+ #: =========================================== ===========================================
166
+ #: our run vs our run (parallel/JIT identity) **compared** -- a differing engine must fail
167
+ #: our run vs an archived MATLAB product **excluded** -- the archive cannot carry it
168
+ #: =========================================== ===========================================
169
+ #:
170
+ #: So the *comparison* names the sets it excludes; the attribute does not declare itself volatile.
171
+ #: A byte-identity gate excludes ``VOLATILE_ATTRS`` alone and therefore already compares these; a
172
+ #: layer-1 comparison against an archived product excludes ``VOLATILE_ATTRS | PROVENANCE_ATTRS``.
173
+ #: Folding these into ``VOLATILE_ATTRS`` would blind the first comparison to a run made by the
174
+ #: wrong engine, which is the failure these attributes exist to stop.
175
+ PROVENANCE_ATTRS = frozenset({ATTR_ENGINE, ATTR_PROFILE, ATTR_STAGE, ATTR_CALL})
176
+
177
+ #: A stamp key: an identifier at the start of the line or after whitespace, followed by ``=``.
178
+ #: The whitespace requirement keeps ``reject=(rej_hollow=0,max_edge_img_ar=4)`` one value instead
179
+ #: of three keys -- its inner ``=`` signs are preceded by ``(`` or ``,``, never by a space
180
+ #: (``scripts/run_flight.py`` builds that fragment with ``",".join(...)``). Same algorithm as
181
+ #: ``arrayprobe.attributed_export.parse_stamp``, which predates this module and should delegate
182
+ #: here; it is not imported because it pulls in numpy and netCDF4 and this module is stdlib-only.
183
+ _STAMP_KEY = re.compile(r"(?:^|\s)([A-Za-z_][A-Za-z0-9_.]*)=")
184
+
185
+ #: What marks ``arrayprobe_uiops/combine.py``'s mirrored stamp as its own format rather than a
186
+ #: driver stamp that happens to say ``engine=3.5``.
187
+ _V35_COMBINE_MARK = "combine=borrowed-oracles-fork:"
188
+
189
+ #: Products a directory sweep considers. A lane directory also holds ``.csv``, ``.json`` and logs;
190
+ #: none of them is a stage output that carries a stamp.
191
+ _PRODUCT_SUFFIXES = (".nc", ".cdf")
192
+
193
+
194
+ class Unstamped(Exception):
195
+ """A product carries no ``.call`` sidecar, so nothing is recorded about what wrote it."""
196
+
197
+ def __init__(self, product: Path | str) -> None:
198
+ self.product = Path(product)
199
+ super().__init__(
200
+ f"{self.product.name} carries no {CALL_SUFFIX} sidecar, so what wrote it is not "
201
+ f"recorded. Run `arrayprobe provenance {self.product}` for the full picture. "
202
+ f"Nothing here infers an engine from a date, a filename or a neighbouring file."
203
+ )
204
+
205
+
206
+ class EngineUnrecorded(Exception):
207
+ """A product *has* a stamp, and that stamp does not name an engine.
208
+
209
+ Distinct from :class:`Unstamped` because the two call for different answers: an unstamped file
210
+ may simply predate stamping, while a stamp that exists and is silent on the engine is a format
211
+ that never had the field (every ``legacy-json`` lane stamp, and every driver stamp written
212
+ before 2026-09-15).
213
+ """
214
+
215
+ def __init__(self, product: Path | str, stamp: Stamp) -> None:
216
+ self.product = Path(product)
217
+ self.stamp = stamp
218
+ super().__init__(
219
+ f"{self.product.name}'s {CALL_SUFFIX} stamp is {stamp.format!r} and records no "
220
+ f"engine. It is not v3.1.4 by default -- that guess is the defect this refusal "
221
+ f"exists to prevent. Re-run the stage through a stamping path, or annotate "
222
+ f"it."
223
+ )
224
+
225
+
226
+ class ProvenanceDisagreement(Exception):
227
+ """The attribute inside a product and the ``.call`` sidecar beside it say different things.
228
+
229
+ **Never resolved silently.** The attribute is additive -- it does not outrank the sidecar and
230
+ the sidecar does not outrank it -- so a disagreement is a finding about the product, not a tie
231
+ to break. Picking a winner here would manufacture exactly the confident-but-wrong answer that
232
+ this module exists to stop; raising hands the question to whoever can actually settle it.
233
+
234
+ ``differences`` is the list :func:`disagreements` produced, one line per field that both
235
+ carriers state and state differently.
236
+ """
237
+
238
+ def __init__(self, product: Path | str, differences: list[str]) -> None:
239
+ self.product = Path(product)
240
+ self.differences = list(differences)
241
+ joined = "; ".join(self.differences)
242
+ super().__init__(
243
+ f"{self.product.name}: the provenance attribute inside the file and the "
244
+ f"{CALL_SUFFIX} sidecar beside it disagree -- {joined}. Neither wins by default: one "
245
+ f"of them describes a run that did not write these bytes. Re-run the stage, or decide "
246
+ f"which is true; `arrayprobe provenance {self.product}` shows both."
247
+ )
248
+
249
+
250
+ @dataclass(frozen=True)
251
+ class Stamp:
252
+ """One parsed ``.call`` sidecar.
253
+
254
+ ``engine`` is ``None`` whenever the stamp does not say. ``raw`` is the sidecar's text verbatim,
255
+ because the parsed keys are a convenience and the raw line is the record.
256
+ """
257
+
258
+ format: str
259
+ engine: str | None
260
+ profile: str | None
261
+ stage: str | None
262
+ raw: str
263
+ fields: dict[str, str] = field(default_factory=dict)
264
+
265
+ def __post_init__(self) -> None:
266
+ if self.format not in FORMATS:
267
+ raise ValueError(f"format {self.format!r} is not one of {FORMATS}")
268
+ if self.engine is not None and self.engine not in ENGINES:
269
+ raise ValueError(f"engine {self.engine!r} is not one of {ENGINES} (or None)")
270
+
271
+
272
+ def call_path(product: Path | str) -> Path:
273
+ """Where ``product``'s stamp lives: ``<product><CALL_SUFFIX>``, beside it, never inside it."""
274
+ p = Path(product)
275
+ return p.with_name(p.name + CALL_SUFFIX)
276
+
277
+
278
+ def read_text(product: Path | str) -> str | None:
279
+ """``product``'s stamp text, or ``None`` if it has none.
280
+
281
+ An unreadable sidecar is ``None`` too -- no stamp and a stamp we cannot open are the same
282
+ epistemic state, and neither is an engine.
283
+ """
284
+ sidecar = call_path(product)
285
+ try:
286
+ return sidecar.read_text(encoding="utf-8").strip()
287
+ except OSError:
288
+ return None
289
+
290
+
291
+ def _parse_keyvalue(text: str) -> dict[str, str] | None:
292
+ """``"engine=3.1.4 profile=x"`` -> its pairs, or ``None`` if the text is not that shape.
293
+
294
+ Values may contain spaces (``area_ratio_z=0.5 (default)``) and nested ``=`` signs
295
+ (``reject=(rej_hollow=0,...)``), so this is not a ``split()``: each key's value runs to the
296
+ start of the next key. A duplicated key returns ``None`` -- refusing to pick one, because
297
+ silently keeping one of two contradictory values is how a stamp stops meaning anything.
298
+ """
299
+ stripped = text.strip()
300
+ if not stripped:
301
+ return None
302
+ hits = list(_STAMP_KEY.finditer(stripped))
303
+ if not hits or hits[0].start() != 0:
304
+ return None
305
+ out: dict[str, str] = {}
306
+ for i, hit in enumerate(hits):
307
+ end = hits[i + 1].start() if i + 1 < len(hits) else len(stripped)
308
+ key = hit.group(1)
309
+ if key in out:
310
+ return None
311
+ out[key] = stripped[hit.end():end].strip()
312
+ return out
313
+
314
+
315
+ def _engine_from(value: Any) -> str | None:
316
+ """A recorded engine value -> a name in :data:`ENGINES`, or ``None``.
317
+
318
+ An engine this module does not know is ``None`` rather than passed through: a consumer
319
+ dispatching on an unrecognised string is the same failure as one dispatching on a guess.
320
+ """
321
+ if not isinstance(value, str):
322
+ return None
323
+ name = value.strip()
324
+ return name if name in ENGINES else None
325
+
326
+
327
+ def parse(text: str) -> Stamp:
328
+ """Parse stamp ``text`` in whichever of the five formats it is written in.
329
+
330
+ Detection is by content, not by filename: a ``.pbp.call`` renamed does not stop being SODA-2
331
+ JSON, and a lane script's JSON does not become a driver stamp by sitting next to a ``proc``.
332
+ """
333
+ raw = text.strip()
334
+ if not raw:
335
+ return Stamp("unparseable", None, None, None, raw, {})
336
+
337
+ if raw.startswith("{"):
338
+ try:
339
+ doc = json.loads(raw)
340
+ except json.JSONDecodeError:
341
+ return Stamp("unparseable", None, None, None, raw, {})
342
+ if not isinstance(doc, dict):
343
+ return Stamp("unparseable", None, None, None, raw, {})
344
+ fields = {str(k): ("" if v is None else str(v)) for k, v in doc.items()}
345
+ engine = _engine_from(doc.get("engine"))
346
+ profile = doc.get("profile")
347
+ stage = doc.get("stage")
348
+ fmt = "soda2-pbp" if engine == "soda2" else "legacy-json"
349
+ # A lane JSON has no engine key at all. That is not v3.1.4; it is silence.
350
+ return Stamp(
351
+ fmt,
352
+ engine,
353
+ str(profile) if isinstance(profile, str) else None,
354
+ str(stage) if isinstance(stage, str) else None,
355
+ raw,
356
+ fields,
357
+ )
358
+
359
+ first = raw.splitlines()[0] if raw.splitlines() else raw
360
+ pairs = _parse_keyvalue(first)
361
+ if pairs is None:
362
+ return Stamp("unparseable", None, None, None, raw, {})
363
+ fields = dict(pairs)
364
+ for line in raw.splitlines()[1:]:
365
+ extra = _parse_keyvalue(line)
366
+ if extra:
367
+ for k, v in extra.items():
368
+ fields.setdefault(k, v)
369
+ fmt = "v35-combine" if _V35_COMBINE_MARK in raw else "driver"
370
+ return Stamp(
371
+ fmt,
372
+ _engine_from(fields.get("engine")),
373
+ fields.get("profile"),
374
+ fields.get("stage"),
375
+ raw,
376
+ fields,
377
+ )
378
+
379
+
380
+ def read(product: Path | str) -> Stamp | None:
381
+ """``product``'s parsed stamp, or ``None`` when it has no sidecar."""
382
+ text = read_text(product)
383
+ return None if text is None else parse(text)
384
+
385
+
386
+ def require(product: Path | str) -> Stamp:
387
+ """``product``'s stamp, raising :class:`Unstamped` when there is none."""
388
+ stamp = read(product)
389
+ if stamp is None:
390
+ raise Unstamped(product)
391
+ return stamp
392
+
393
+
394
+ def engine_of(product: Path | str) -> str:
395
+ """The engine that wrote ``product``, from its own stamp.
396
+
397
+ Raises :class:`Unstamped` when there is no sidecar and :class:`EngineUnrecorded` when there is
398
+ one that does not name an engine. It never returns a default; there is no code path here that
399
+ produces an engine name the stamp did not contain.
400
+ """
401
+ stamp = require(product)
402
+ if stamp.engine is None:
403
+ raise EngineUnrecorded(product, stamp)
404
+ return stamp.engine
405
+
406
+
407
+ def stamp_text(
408
+ *,
409
+ engine: str,
410
+ # REQUIRED, not defaulted: `profile=None` is a legal and meaningful value here
411
+ # -- an S2 stamp names no profile because neither the SEA nor the DMT reader
412
+ # reads one -- but it must be STATED. A default cannot distinguish "absent by
413
+ # design" from "the caller forgot", which is the whole point of
414
+ # tests/test_profile_is_never_defaulted.py, and that check caught this module
415
+ # propagating the anti-pattern across four signatures on 2026-09-18.
416
+ profile: str | None,
417
+ stage: str | None = None,
418
+ extra: dict[str, str] | None = None,
419
+ ) -> str:
420
+ """The one-line driver-format stamp text, with no trailing newline.
421
+
422
+ **Both carriers are built from here** -- :func:`write` writes this plus ``"\\n"`` into the
423
+ sidecar, :func:`attrs_for` puts this into :data:`ATTR_CALL` -- so the attribute and the sidecar
424
+ are byte-identical by construction rather than by anyone remembering to keep them so. That is
425
+ what stops the attribute becoming a second source of truth: there is one text, stored twice.
426
+
427
+ Raises ``ValueError`` on an engine outside :data:`ENGINES`, or on a value containing a newline
428
+ or a space-separated ``word=`` (which would re-parse as a second key and quietly change what
429
+ the stamp says).
430
+ """
431
+ if engine not in ENGINES:
432
+ raise ValueError(f"engine {engine!r} is not one of {ENGINES}")
433
+ pairs: list[tuple[str, str]] = [("engine", engine)]
434
+ if profile is not None:
435
+ pairs.append(("profile", profile))
436
+ if stage is not None:
437
+ pairs.append(("stage", stage))
438
+ pairs.extend(sorted((extra or {}).items()))
439
+ for key, value in pairs:
440
+ text = str(value)
441
+ if "\n" in text or "\r" in text:
442
+ raise ValueError(f"stamp value for {key!r} contains a newline: {text!r}")
443
+ if _STAMP_KEY.search(" " + text):
444
+ raise ValueError(
445
+ f"stamp value for {key!r} contains a space-separated 'word=', which would re-parse "
446
+ f"as a second key: {text!r}"
447
+ )
448
+ return " ".join(f"{k}={v}" for k, v in pairs)
449
+
450
+
451
+ def is_provenance_attr(name: str) -> bool:
452
+ """Whether ``name`` is one of this project's provenance global attributes.
453
+
454
+ By prefix, not by membership of :data:`PROVENANCE_ATTRS`, so a comparison that excludes
455
+ "our provenance" keeps excluding all of it when a fourth key is added later. A check that
456
+ enumerates is a check that silently stops covering things.
457
+ """
458
+ return name.startswith(ATTR_PREFIX)
459
+
460
+
461
+ def attrs_for(
462
+ *,
463
+ engine: str,
464
+ # REQUIRED, not defaulted: `profile=None` is a legal and meaningful value here
465
+ # -- an S2 stamp names no profile because neither the SEA nor the DMT reader
466
+ # reads one -- but it must be STATED. A default cannot distinguish "absent by
467
+ # design" from "the caller forgot", which is the whole point of
468
+ # tests/test_profile_is_never_defaulted.py, and that check caught this module
469
+ # propagating the anti-pattern across four signatures on 2026-09-18.
470
+ profile: str | None,
471
+ stage: str | None = None,
472
+ extra: dict[str, str] | None = None,
473
+ ) -> dict[str, str]:
474
+ """The global attributes that record this configuration, ready for ``putAtt``.
475
+
476
+ Pure ``str`` in, pure ``dict[str, str]`` out -- no netCDF here, so this module stays
477
+ stdlib-only and a lane script can import it. :func:`arrayprobe_uiops.ncio.put_provenance` is
478
+ what
479
+ writes them.
480
+ """
481
+ text = stamp_text(engine=engine, profile=profile, stage=stage, extra=extra)
482
+ attrs = {ATTR_CALL: text, ATTR_ENGINE: engine}
483
+ if profile is not None:
484
+ attrs[ATTR_PROFILE] = str(profile)
485
+ if stage is not None:
486
+ attrs[ATTR_STAGE] = str(stage)
487
+ return attrs
488
+
489
+
490
+ #: The value :data:`ATTR_PROFILE` carries when a library caller of the v3.5 or SODA-2 engine
491
+ #: named no profile (author, 2026-09-24). It is deliberately not a profile name: those engines
492
+ #: take thresholds, not a profile, so a bare library call has none to record, and inventing one
493
+ #: from the thresholds would be inference. :func:`stamp_from_attrs` reads it as *silence* (no
494
+ #: profile recorded), so it never disagrees with a sidecar that names one.
495
+ PROFILE_UNSTATED = "unstated"
496
+
497
+
498
+ def engine_attrs(*, engine: str, profile: str | None) -> dict[str, str]:
499
+ """The two global attributes every v3.5 and SODA-2 product carries.
500
+
501
+ ``{ATTR_ENGINE: engine, ATTR_PROFILE: profile or PROFILE_UNSTATED}``, in that order. Written
502
+ unconditionally by those engines' writers -- a product that is copied, renamed or hardlinked
503
+ still says what wrote it. **Never written by the earlier translation**, whose products must stay
504
+ byte-faithful to MATLAB's; there the opt-in :func:`arrayprobe_uiops.ncio.put_provenance`
505
+ remains.
506
+ ``profile`` is required but may be ``None``: ``None`` writes :data:`PROFILE_UNSTATED`.
507
+ """
508
+ if engine not in ("3.5", "soda2"):
509
+ raise ValueError(f"engine_attrs is for the v3.5 and SODA-2 engines only, not {engine!r}")
510
+ text = PROFILE_UNSTATED if profile is None else str(profile)
511
+ if not text or any(c in text for c in " \r\n") or _STAMP_KEY.search(" " + text):
512
+ raise ValueError(f"profile {text!r} cannot be carried as a stamp value")
513
+ return {ATTR_ENGINE: engine, ATTR_PROFILE: text}
514
+
515
+
516
+ def stamp_from_attrs(attrs: dict[str, Any]) -> Stamp | None:
517
+ """The :class:`Stamp` a product's own global attributes record, or ``None`` if it has none.
518
+
519
+ Reads through :func:`parse`, the same parser the sidecar goes through -- there is deliberately
520
+ no second parser for the attribute form. :data:`ATTR_CALL` is the record when present; the
521
+ discrete keys are re-assembled into the same text when it is not (a hand-annotated file, or a
522
+ future writer that sets only the engine).
523
+
524
+ Raises :class:`ProvenanceDisagreement` when the file's own keys contradict its own
525
+ :data:`ATTR_CALL` -- which :func:`attrs_for` cannot produce, so it means the file was edited.
526
+ """
527
+ present = {str(k): v for k, v in attrs.items() if is_provenance_attr(str(k))}
528
+ if not present:
529
+ return None
530
+ call = present.get(ATTR_CALL)
531
+ if call is not None:
532
+ stamp = parse(str(call))
533
+ else:
534
+ discrete = [
535
+ (key, str(present[attr]))
536
+ for attr, key in ((ATTR_ENGINE, "engine"), (ATTR_PROFILE, "profile"),
537
+ (ATTR_STAGE, "stage"))
538
+ if attr in present
539
+ # PROFILE_UNSTATED is silence, not a profile named "unstated".
540
+ and not (attr == ATTR_PROFILE and str(present[attr]) == PROFILE_UNSTATED)
541
+ ]
542
+ # Assembled, not validated: an engine name this module does not know must reach
543
+ # ``parse`` and come back as ``engine=None``, not raise -- silence is the honest answer
544
+ # for a value we cannot vouch for, and ``stamp_text`` would refuse it outright.
545
+ stamp = parse(" ".join(f"{k}={v}" for k, v in discrete))
546
+ internal: list[str] = []
547
+ if call is not None:
548
+ for attr, key in ((ATTR_ENGINE, "engine"), (ATTR_PROFILE, "profile"),
549
+ (ATTR_STAGE, "stage")):
550
+ if attr not in present:
551
+ continue
552
+ if str(present[attr]) != (getattr(stamp, key) or ""):
553
+ internal.append(
554
+ f"{attr}={str(present[attr])!r} but {ATTR_CALL} says "
555
+ f"{getattr(stamp, key)!r}"
556
+ )
557
+ if internal:
558
+ raise ProvenanceDisagreement("<attributes>", internal)
559
+ return stamp
560
+
561
+
562
+ def disagreements(sidecar: Stamp | None, inside: Stamp | None) -> list[str]:
563
+ """Every field the two carriers **both state** and state differently.
564
+
565
+ **Silence is not disagreement.** A sidecar that records no engine (every ``legacy-json`` lane
566
+ stamp, and every driver stamp written before 2026-09-15) against an attribute that names one
567
+ is the attribute supplying what the sidecar lacks -- the point of carrying provenance in the
568
+ file, not a finding. Only a field both sides fill, with different values, is reported. Extra
569
+ keys on either side are
570
+ likewise not a difference: the sidecar may carry a ``reject=(...)`` fragment no attribute
571
+ holds, and saying so on every product would train the reader to ignore the check.
572
+ """
573
+ if sidecar is None or inside is None:
574
+ return []
575
+ out: list[str] = []
576
+ for key in ("engine", "profile", "stage"):
577
+ theirs, ours = getattr(sidecar, key), getattr(inside, key)
578
+ if theirs is not None and ours is not None and theirs != ours:
579
+ out.append(f"{key}: sidecar says {theirs!r}, attribute says {ours!r}")
580
+ for key, ours_value in sorted(inside.fields.items()):
581
+ if key in ("engine", "profile", "stage"):
582
+ continue
583
+ theirs_value = sidecar.fields.get(key)
584
+ if theirs_value is not None and theirs_value != ours_value:
585
+ out.append(f"{key}: sidecar says {theirs_value!r}, attribute says {ours_value!r}")
586
+ return out
587
+
588
+
589
+ def write(
590
+ product: Path | str,
591
+ *,
592
+ engine: str,
593
+ # REQUIRED, not defaulted: `profile=None` is a legal and meaningful value here
594
+ # -- an S2 stamp names no profile because neither the SEA nor the DMT reader
595
+ # reads one -- but it must be STATED. A default cannot distinguish "absent by
596
+ # design" from "the caller forgot", which is the whole point of
597
+ # tests/test_profile_is_never_defaulted.py, and that check caught this module
598
+ # propagating the anti-pattern across four signatures on 2026-09-18.
599
+ profile: str | None,
600
+ stage: str | None = None,
601
+ extra: dict[str, str] | None = None,
602
+ ) -> Path:
603
+ """Stamp ``product`` in the **driver text format**, partial-then-rename.
604
+
605
+ The text shape mirrors ``scripts/run_flight.py:write_stamp`` deliberately, so that a product
606
+ stamped by a single-stage CLI verb and one stamped by the driver are read by the same parser
607
+ and compare by the same string rules. Partial-then-``os.replace`` is not decoration: a kill
608
+ mid-write would otherwise leave a truncated stamp, which compares unequal and silently costs a
609
+ redo -- or, worse, compares equal to a prefix of some future label.
610
+
611
+ Returns the sidecar path. Raises ``ValueError`` on an engine outside :data:`ENGINES`, or on a
612
+ value containing a newline or a space-separated ``word=`` (which would re-parse as a second
613
+ key and quietly change what the stamp says).
614
+ """
615
+ label = stamp_text(engine=engine, profile=profile, stage=stage, extra=extra)
616
+ sidecar = call_path(product)
617
+ partial = sidecar.with_name(sidecar.name + ".partial")
618
+ partial.write_text(label + "\n", encoding="utf-8")
619
+ os.replace(partial, sidecar)
620
+ return sidecar
621
+
622
+
623
+ def _in_flight(product: Path) -> bool:
624
+ """Whether a run appears to be writing ``product`` right now.
625
+
626
+ Two conventions are in the tree: ``<product>.partial`` (the stamp writer's and the stage
627
+ writers' rename dance) and an ``_inflight/`` directory beside the product holding the stem.
628
+ """
629
+ if product.with_name(product.name + ".partial").exists():
630
+ return True
631
+ inflight = product.parent / "_inflight"
632
+ if inflight.is_dir():
633
+ stem = product.name.split(".")[0]
634
+ for entry in inflight.iterdir():
635
+ if entry.name.startswith(stem):
636
+ return True
637
+ return False
638
+
639
+
640
+ def state(product: Path | str) -> str:
641
+ """One of :data:`STATES`, for one product path.
642
+
643
+ ``orphan-stamp`` is a sidecar whose product is gone -- five of them sit in
644
+ ``_decoded/cip160906/`` alone. ``in-flight`` outranks the rest because a partial file's
645
+ missing stamp is expected, not a finding.
646
+ """
647
+ p = Path(product)
648
+ exists = p.exists()
649
+ stamp = read(p)
650
+ if _in_flight(p):
651
+ return "in-flight"
652
+ if not exists:
653
+ return "orphan-stamp" if stamp is not None else "unstamped"
654
+ if stamp is None:
655
+ return "unstamped"
656
+ if stamp.format == "legacy-json":
657
+ return "legacy-json"
658
+ if stamp.format == "unparseable":
659
+ return "unparseable"
660
+ return "stamped"
661
+
662
+
663
+ def _checkout_sha() -> str:
664
+ """This checkout's ``git rev-parse HEAD`` plus a dirty flag -- *not* the product's.
665
+
666
+ Deliberately never written into a stamp: adding
667
+ ``source=<sha>`` to the driver text would break byte-identity with every validated sidecar.
668
+ Reported here and labelled, which is honest and costs nothing.
669
+ """
670
+ try:
671
+ sha = subprocess.run(
672
+ ["git", "rev-parse", "HEAD"], capture_output=True, text=True, timeout=10,
673
+ )
674
+ if sha.returncode != 0:
675
+ return "unknown (not a git checkout)"
676
+ head = sha.stdout.strip()[:12]
677
+ status = subprocess.run(
678
+ ["git", "status", "--porcelain"], capture_output=True, text=True, timeout=10,
679
+ )
680
+ dirty = " dirty" if status.returncode == 0 and status.stdout.strip() else ""
681
+ return f"{head}{dirty}"
682
+ except (OSError, subprocess.SubprocessError):
683
+ return "unknown (git unavailable)"
684
+
685
+
686
+ def _expand(paths: Iterable[Path | str]) -> list[Path]:
687
+ """Every path a report should cover: a file as itself, a directory as its products.
688
+
689
+ A directory expands to every ``*.nc``/``*.cdf`` in it **plus** the product path implied by
690
+ every orphan ``.call``, so a sidecar whose product has been deleted is still reported. Silence
691
+ about a directory is what let 16 unstamped products accumulate unremarked.
692
+ """
693
+ out: list[Path] = []
694
+ for raw in paths:
695
+ p = Path(raw)
696
+ if p.is_dir():
697
+ found = {q for q in p.iterdir() if q.suffix in _PRODUCT_SUFFIXES and q.is_file()}
698
+ for sidecar in p.glob("*" + CALL_SUFFIX):
699
+ found.add(sidecar.with_name(sidecar.name[: -len(CALL_SUFFIX)]))
700
+ out.extend(sorted(found, key=lambda q: q.name))
701
+ else:
702
+ out.append(p)
703
+ return out
704
+
705
+
706
+ def _nlink(p: Path) -> str:
707
+ try:
708
+ return str(os.stat(p).st_nlink)
709
+ except OSError:
710
+ return "-"
711
+
712
+
713
+ def report(paths: Iterable[Path | str], *, require: bool = False) -> tuple[str, int]:
714
+ """The ``arrayprobe provenance`` table, and an exit code.
715
+
716
+ Returns ``(text, code)``. With ``require=True`` the code is ``1`` unless every reported
717
+ product is ``stamped`` **and names an engine**. The second half is not redundant: a driver
718
+ stamp written before 2026-09-15 has no ``engine=`` key, so it is legitimately ``stamped`` --
719
+ the sidecar is there and records the whole configuration -- while still not saying what wrote
720
+ the file. Passing it would let ``--require`` green-light exactly the products of
721
+ unrecorded engine this module exists to catch.
722
+ A directory answer is never silent: an empty directory says so, which is how the two-empty-
723
+ trees reading of "there is nothing here" is prevented.
724
+
725
+ ``nlink`` is printed because a sidecar is keyed by name: a product with ``nlink > 1`` has at
726
+ least one other name, and that other name has no stamp of its own.
727
+ """
728
+ targets = _expand(paths)
729
+ lines: list[str] = []
730
+ header = (f"{'product':<40} {'state':<13} {'engine':<11} {'format':<13} {'nlink':>5} "
731
+ f"{'profile':<20} in-file")
732
+ lines.append(header)
733
+ lines.append("-" * len(header))
734
+ counts: dict[str, int] = {}
735
+ not_stamped = 0
736
+ no_engine = 0
737
+ disagree = 0
738
+ for p in targets:
739
+ st = state(p)
740
+ counts[st] = counts.get(st, 0) + 1
741
+ stamp = read(p)
742
+ inside = _inside(p)
743
+ engine = (stamp.engine if stamp else None) or "unrecorded"
744
+ fmt = stamp.format if stamp else "-"
745
+ profile = (stamp.profile if stamp else None) or "-"
746
+ differences = disagreements(stamp, inside)
747
+ if differences:
748
+ in_file = "DISAGREES: " + "; ".join(differences)
749
+ disagree += 1
750
+ elif inside is not None:
751
+ in_file = f"engine={inside.engine or '-'} profile={inside.profile or '-'}"
752
+ else:
753
+ in_file = "-"
754
+ lines.append(
755
+ f"{p.name:<40} {st:<13} {engine:<11} {fmt:<13} {_nlink(p):>5} {profile:<20} {in_file}"
756
+ )
757
+ if st == "unstamped" and inside is not None and inside.engine:
758
+ pass # the in-file stamp alone accounts for it, as ncio.provenance_of accepts
759
+ elif st != "stamped":
760
+ not_stamped += 1
761
+ elif stamp is None or stamp.engine is None:
762
+ no_engine += 1
763
+ if not targets:
764
+ lines.append("(no products found -- an empty answer, stated rather than implied)")
765
+ lines.append("")
766
+ lines.append("counts: " + (", ".join(f"{k}={v}" for k, v in sorted(counts.items())) or "none"))
767
+ lines.append(f"checkout: {_checkout_sha()} (this checkout, not the product's -- no stamp "
768
+ f"records the source tree that wrote it)")
769
+ lines.append("note: a stamp is keyed by name; a copy, hardlink or rename loses it. The in-file "
770
+ "column reads the product's own arrayprobe_* attributes, which survive all three.")
771
+ failures = not_stamped + no_engine + disagree
772
+ if require and failures:
773
+ lines.append(
774
+ f"REQUIRE: {failures} of {len(targets)} product(s) unaccounted for "
775
+ f"({not_stamped} not `stamped`, {no_engine} stamped but naming no engine, "
776
+ f"{disagree} whose sidecar and in-file stamp disagree)."
777
+ )
778
+ code = 1 if (require and failures) else 0
779
+ return "\n".join(lines) + "\n", code
780
+
781
+
782
+ def read_in_file_stamp(filename: str | os.PathLike[str]) -> Stamp | None:
783
+ """The stamp ``filename`` carries **in its own bytes** (its global attributes), or ``None`` if
784
+ it carries none.
785
+
786
+ Survives a rename, a copy and a hardlink, which a ``.call`` sidecar keyed by filename does not.
787
+ ``netCDF4`` is imported here rather than at module load, so importing this module stays cheap.
788
+ """
789
+ from netCDF4 import Dataset
790
+
791
+ with Dataset(filename, "r") as ds:
792
+ attrs = {key: ds.getncattr(key) for key in ds.ncattrs() if is_provenance_attr(key)}
793
+ return stamp_from_attrs(attrs)
794
+
795
+
796
+ def _inside(product: Path) -> Stamp | None:
797
+ """The stamp a product carries in its own attributes, or ``None`` when it carries none or
798
+ cannot be opened as netCDF (an empty test fixture, a product still being written)."""
799
+ if not product.is_file() or product.stat().st_size == 0:
800
+ return None
801
+ try:
802
+ return read_in_file_stamp(product)
803
+ except (OSError, RuntimeError, ValueError):
804
+ return None