courant-dev 0.5.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 (152) hide show
  1. courant/__init__.py +26 -0
  2. courant/case/__init__.py +0 -0
  3. courant/case/_foam_reader.py +269 -0
  4. courant/case/config.py +134 -0
  5. courant/case/mesh.py +135 -0
  6. courant/case/reads.py +90 -0
  7. courant/case/schemes.py +99 -0
  8. courant/case/solvers.py +170 -0
  9. courant/cli/__init__.py +0 -0
  10. courant/cli/commands/__init__.py +6 -0
  11. courant/cli/commands/audit.py +40 -0
  12. courant/cli/commands/convergence.py +68 -0
  13. courant/cli/commands/ctest.py +76 -0
  14. courant/cli/commands/doctor.py +162 -0
  15. courant/cli/commands/gate.py +88 -0
  16. courant/cli/commands/live.py +73 -0
  17. courant/cli/commands/mcp.py +57 -0
  18. courant/cli/commands/preflight.py +36 -0
  19. courant/cli/commands/spec.py +231 -0
  20. courant/cli/commands/tour.py +122 -0
  21. courant/cli/commands/update.py +213 -0
  22. courant/cli/commands/verify.py +222 -0
  23. courant/cli/config.py +244 -0
  24. courant/cli/guard.py +69 -0
  25. courant/cli/main.py +130 -0
  26. courant/cli/tail.py +351 -0
  27. courant/config.py +155 -0
  28. courant/converge/__init__.py +57 -0
  29. courant/converge/assess.py +823 -0
  30. courant/converge/exact.py +112 -0
  31. courant/converge/render.py +182 -0
  32. courant/converge/scale.py +87 -0
  33. courant/converge/sentences.py +82 -0
  34. courant/converge/series.py +413 -0
  35. courant/converge/steady.py +261 -0
  36. courant/converge/tables.py +1019 -0
  37. courant/converge/transient.py +314 -0
  38. courant/ctest/__init__.py +6 -0
  39. courant/ctest/build.py +82 -0
  40. courant/ctest/data/judge-v0.labels.jsonl +31 -0
  41. courant/ctest/data/judge-v0.tasks.jsonl.gz +0 -0
  42. courant/ctest/judges/__init__.py +27 -0
  43. courant/ctest/judges/constant.py +18 -0
  44. courant/ctest/judges/courant.py +23 -0
  45. courant/ctest/judges/llm.py +166 -0
  46. courant/ctest/run.py +74 -0
  47. courant/ctest/schema.py +46 -0
  48. courant/ctest/score.py +91 -0
  49. courant/ctest/splits.py +20 -0
  50. courant/data/__init__.py +46 -0
  51. courant/data/certification.json +1 -0
  52. courant/data/certified_codes.json +18 -0
  53. courant/data/demo/icoFoam_cavity__cfl_blowup.case.json +68 -0
  54. courant/data/demo/icoFoam_cavity__cfl_blowup.log.gz +0 -0
  55. courant/data/demo/icoFoam_cavity__healthy.case.json +68 -0
  56. courant/data/demo/icoFoam_cavity__healthy.log.gz +0 -0
  57. courant/data/demo/icoFoam_cavity__transport_units.case.json +68 -0
  58. courant/data/demo/icoFoam_cavity__transport_units.log.gz +0 -0
  59. courant/data/demo/pitzDaily_fixed_budget.tar.gz +0 -0
  60. courant/data/schemas/audit.1.json +129 -0
  61. courant/data/schemas/cache.1.json +77 -0
  62. courant/data/schemas/convergence.1.json +112 -0
  63. courant/data/schemas/error-rates.1.json +53 -0
  64. courant/data/schemas/preflight.1.json +250 -0
  65. courant/data/schemas/record.1.json +155 -0
  66. courant/data/schemas/release-signature.1.json +39 -0
  67. courant/data/schemas/spec.1.json +258 -0
  68. courant/data/schemas/support.1.json +80 -0
  69. courant/data/schemas/verdict.1.json +716 -0
  70. courant/data/schemas/verdict.2.json +752 -0
  71. courant/diagnosis/__init__.py +0 -0
  72. courant/diagnosis/bundle.py +168 -0
  73. courant/diagnosis/checkers.py +919 -0
  74. courant/diagnosis/deterministic.py +110 -0
  75. courant/diagnosis/findings.py +107 -0
  76. courant/diagnosis/kb.py +188 -0
  77. courant/diagnosis/kb_data.py +253 -0
  78. courant/diagnosis/llm.py +299 -0
  79. courant/diagnosis/redact.py +425 -0
  80. courant/diagnosis/schema.py +83 -0
  81. courant/events/__init__.py +35 -0
  82. courant/events/core.py +194 -0
  83. courant/events/diverged.py +55 -0
  84. courant/gate/__init__.py +1 -0
  85. courant/gate/config.py +150 -0
  86. courant/gate/run.py +295 -0
  87. courant/live/__init__.py +16 -0
  88. courant/live/engine.py +155 -0
  89. courant/live/watch.py +164 -0
  90. courant/llm/__init__.py +59 -0
  91. courant/llm/allowlist.py +60 -0
  92. courant/llm/anthropic.py +137 -0
  93. courant/llm/budget.py +491 -0
  94. courant/llm/door.py +1071 -0
  95. courant/llm/errors.py +105 -0
  96. courant/llm/openrouter.py +118 -0
  97. courant/llm/policy.py +268 -0
  98. courant/llm/transport.py +48 -0
  99. courant/mcp/__init__.py +7 -0
  100. courant/mcp/server.py +113 -0
  101. courant/mcp/tools.py +177 -0
  102. courant/record/__init__.py +22 -0
  103. courant/record/filter.py +99 -0
  104. courant/record/record.py +149 -0
  105. courant/release.py +205 -0
  106. courant/signing.py +99 -0
  107. courant/spec/__init__.py +31 -0
  108. courant/spec/check.py +353 -0
  109. courant/spec/deck.py +455 -0
  110. courant/spec/extract.py +181 -0
  111. courant/spec/impossible.py +197 -0
  112. courant/spec/model.py +194 -0
  113. courant/taxonomy.py +219 -0
  114. courant/verification/__init__.py +30 -0
  115. courant/verification/_fluid_reader.py +228 -0
  116. courant/verification/bounding.py +84 -0
  117. courant/verification/checks.py +369 -0
  118. courant/verification/convergence.py +257 -0
  119. courant/verification/fields.py +38 -0
  120. courant/verification/grade.py +101 -0
  121. courant/verification/suite.py +30 -0
  122. courant/verify/__init__.py +37 -0
  123. courant/verify/about.py +100 -0
  124. courant/verify/audit.py +209 -0
  125. courant/verify/batch.py +141 -0
  126. courant/verify/cache.py +329 -0
  127. courant/verify/checks.py +37 -0
  128. courant/verify/html.py +330 -0
  129. courant/verify/ingest.py +115 -0
  130. courant/verify/junit.py +48 -0
  131. courant/verify/outcome.py +74 -0
  132. courant/verify/pack.py +106 -0
  133. courant/verify/pipeline.py +396 -0
  134. courant/verify/policy.py +167 -0
  135. courant/verify/preflight.py +166 -0
  136. courant/verify/render.py +174 -0
  137. courant/verify/schema.py +398 -0
  138. courant/verify/sentences.py +137 -0
  139. courant/verify/support.py +142 -0
  140. courant/verify/verdict2.py +235 -0
  141. courant/watcher/__init__.py +13 -0
  142. courant/watcher/anomaly.py +244 -0
  143. courant/watcher/exitcode.py +23 -0
  144. courant/watcher/parser.py +435 -0
  145. courant/watcher/watcher.py +49 -0
  146. courant_dev-0.5.0.dist-info/METADATA +146 -0
  147. courant_dev-0.5.0.dist-info/RECORD +152 -0
  148. courant_dev-0.5.0.dist-info/WHEEL +5 -0
  149. courant_dev-0.5.0.dist-info/entry_points.txt +3 -0
  150. courant_dev-0.5.0.dist-info/licenses/LICENSE +202 -0
  151. courant_dev-0.5.0.dist-info/licenses/NOTICE +4 -0
  152. courant_dev-0.5.0.dist-info/top_level.txt +1 -0
courant/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """Courant: physics acceptance testing for machine-produced simulation.
2
+
3
+ A read-only, deterministic gate between a simulation (an AI agent's or an engineer's) and the
4
+ person who signs it: `accept`, `reject` or `insufficient`, with the reasons it read. Without a
5
+ task specification it decides whether a run is valid; with one, whether it is the problem that
6
+ was asked. First integration: OpenFOAM.
7
+ """
8
+
9
+ __version__ = "0.5.0"
10
+
11
+ #: The public repository of the open-source gate (H-DISTRIBUTION, 11 Oct 2026): its source, its
12
+ #: releases (the signed binaries, the wheel and the installer) and its GitHub Action.
13
+ #:
14
+ #: This is the one home for that fact. `courant update` reads it here and
15
+ #: `packaging/install.sh` is asserted against it by
16
+ #: `tests/unit/test_release_channel.py` — because the two of them once named
17
+ #: different repositories, and the one nobody had run was the one that was
18
+ #: wrong for every customer.
19
+ RELEASE_REPO = "courantdev/courant"
20
+
21
+ #: The distribution's name on the package index: ``pip install courant-dev``. PyPI's ``courant``
22
+ #: is an unrelated project, so every install line names this, never plain ``courant``
23
+ #: (tests/unit/test_network.py). The import package and the commands stay ``courant``.
24
+ DISTRIBUTION = "courant-dev"
25
+
26
+ __all__ = ["__version__", "RELEASE_REPO", "DISTRIBUTION"]
File without changes
@@ -0,0 +1,269 @@
1
+ """Read a real OpenFOAM case directory into a CaseConfig (live path).
2
+
3
+ Uses foamlib to parse the dictionaries that matter for diagnosis. Best-effort and
4
+ defensive: a missing file or key is skipped, never fatal — real cases vary. This is
5
+ what makes the live DockerRunner path work end to end (config_view over real files).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+
12
+ from courant.case.config import CaseConfig, LinearSolverSpec
13
+ from courant.case.reads import reading
14
+
15
+
16
+ def _scalar(v):
17
+ """Extract a float from foamlib's varied return types (number, dimensioned, tuple)."""
18
+ if isinstance(v, bool):
19
+ return None
20
+ if isinstance(v, (int, float)):
21
+ return float(v)
22
+ if hasattr(v, "value"):
23
+ try:
24
+ return float(v.value) # foamlib Dimensioned
25
+ except Exception: # noqa: BLE001
26
+ return None
27
+ if isinstance(v, (tuple, list)) and v:
28
+ last = v[-1]
29
+ return float(last) if isinstance(last, (int, float)) else None
30
+ return None
31
+
32
+
33
+ def _tokens(v) -> str | None:
34
+ """Render a scheme value (tuple of tokens or string) as a string."""
35
+ if isinstance(v, (tuple, list)):
36
+ return " ".join(str(t) for t in v)
37
+ if v is None:
38
+ return None
39
+ return str(v)
40
+
41
+
42
+ def _get(f, *key):
43
+ try:
44
+ return f[key if len(key) > 1 else key[0]]
45
+ except Exception: # noqa: BLE001 — missing key, or an unreadable file
46
+ return None
47
+
48
+
49
+ def _readable(f, path: str, rel: str, unreadable: dict[str, str]) -> bool:
50
+ """Whether this file parses at all, recording the reason if not.
51
+
52
+ Every `_get` below swallows its exception, which is right for a missing key
53
+ and wrong for a file that cannot be parsed: the two are indistinguishable
54
+ afterwards, so an unreadable `controlDict` produced a `CaseConfig` with no
55
+ solver, no timestep and no write control — *silently*, exactly as though the
56
+ case had chosen to omit them.
57
+
58
+ That is reachable on real cases. `foamDictionary -set` rewrites a dictionary
59
+ with its `#include` directives expanded, and OpenFOAM's own
60
+ `pisoFoam/RAS/cavity` expands into `fields ( U { mean on; ... } );` — a list
61
+ containing an inline dictionary, which foamlib cannot parse. Any case an
62
+ engineer has edited with OpenFOAM's own tool can arrive in this state, and
63
+ every controlDict-derived checker and KB predicate then reads nothing and
64
+ says nothing about why.
65
+ """
66
+ try:
67
+ _parse(f, path)
68
+ except Exception as exc: # noqa: BLE001
69
+ unreadable[rel] = f"{type(exc).__name__}: {str(exc).splitlines()[0][:160]}"
70
+ return False
71
+ return True
72
+
73
+
74
+ def _parse(f, path: str) -> None:
75
+ """Parse a `FoamFile` once, noting `path` (the path the reader used, not foamlib's
76
+ resolution of it) when the bytes were read (VER-14).
77
+
78
+ foamlib reads lazily, and every `_get` swallows its exception, so this is the one place a
79
+ read can be seen to succeed. A file that cannot be opened (`OSError`) is not noted; a file
80
+ that was read and does not parse is noted, then the error propagates.
81
+ """
82
+ with reading(path):
83
+ try:
84
+ list(f.items())
85
+ except KeyError:
86
+ pass # parsed; simply has no entries we asked for
87
+
88
+
89
+ def _subdict_items(f, key):
90
+ """Yield (name, value) for a subdict; empty if absent."""
91
+ d = _get(f, key)
92
+ if d is None:
93
+ return []
94
+ try:
95
+ return list(d.items())
96
+ except Exception: # noqa: BLE001
97
+ return []
98
+
99
+
100
+ def read_case_config(case_dir: str) -> CaseConfig:
101
+ from foamlib import FoamFile
102
+
103
+ data: dict = {}
104
+ unreadable: dict[str, str] = {}
105
+
106
+ def open_file(rel):
107
+ p = os.path.join(case_dir, rel)
108
+ if not os.path.exists(p):
109
+ return None
110
+ f = FoamFile(p) # VER-14: `_readable` notes it once it is read
111
+ return f if _readable(f, p, rel, unreadable) else None
112
+
113
+ # --- controlDict ---
114
+ cd = open_file("system/controlDict")
115
+ if cd is not None:
116
+ data["solver"] = _get(cd, "application")
117
+ data["delta_t"] = _scalar(_get(cd, "deltaT"))
118
+ data["end_time"] = _scalar(_get(cd, "endTime"))
119
+ adj = _get(cd, "adjustTimeStep")
120
+ data["adjust_timestep"] = bool(adj) if adj is not None else None
121
+ data["max_co"] = _scalar(_get(cd, "maxCo"))
122
+ wc = _get(cd, "writeControl")
123
+ data["write_control"] = str(wc) if wc is not None else None
124
+ data["write_interval"] = _scalar(_get(cd, "writeInterval"))
125
+
126
+ # --- fvSchemes ---
127
+ fs = open_file("system/fvSchemes")
128
+ if fs is not None:
129
+ ddt = _get(fs, "ddtSchemes", "default")
130
+ data["ddt_scheme"] = _tokens(ddt)
131
+ div = {k: _tokens(v) for k, v in _subdict_items(fs, "divSchemes")}
132
+ if div:
133
+ data["div_schemes"] = {k: v for k, v in div.items() if v}
134
+
135
+ # --- fvSolution ---
136
+ fv = open_file("system/fvSolution")
137
+ if fv is not None:
138
+ relax: dict[str, float] = {}
139
+ scopes: dict[str, str] = {}
140
+ rf = _get(fv, "relaxationFactors")
141
+ if rf is not None:
142
+ # flatten nested fields/equations, or a flat mapping
143
+ try:
144
+ items = list(rf.items())
145
+ except Exception: # noqa: BLE001
146
+ items = []
147
+ for k, v in items:
148
+ if k in ("fields", "equations"):
149
+ try:
150
+ for kk, vv in v.items():
151
+ s = _scalar(vv)
152
+ if s is not None:
153
+ relax[kk] = s
154
+ scopes[kk] = k
155
+ except Exception: # noqa: BLE001
156
+ pass
157
+ else:
158
+ s = _scalar(v)
159
+ if s is not None:
160
+ relax[k] = s
161
+ scopes[k] = ""
162
+ if relax:
163
+ data["relaxation_factors"] = relax
164
+ data["relaxation_scopes"] = scopes
165
+ for loop in ("SIMPLE", "PIMPLE"):
166
+ nno = _scalar(_get(fv, loop, "nNonOrthogonalCorrectors"))
167
+ if nno is not None:
168
+ data["n_non_orthogonal_correctors"] = int(nno)
169
+ ncorr = _scalar(_get(fv, loop, "nCorrectors"))
170
+ if ncorr is not None:
171
+ data["n_correctors"] = int(ncorr)
172
+ nouter = _scalar(_get(fv, "PIMPLE", "nOuterCorrectors"))
173
+ if nouter is not None:
174
+ data["n_outer_correctors"] = int(nouter)
175
+ solvers: dict[str, LinearSolverSpec] = {}
176
+ for field, spec in _subdict_items(fv, "solvers"):
177
+ try:
178
+ solvers[field] = LinearSolverSpec(
179
+ field=field, solver=_tokens(spec.get("solver")),
180
+ tolerance=_scalar(spec.get("tolerance")),
181
+ rel_tol=_scalar(spec.get("relTol")))
182
+ except Exception: # noqa: BLE001
183
+ pass
184
+ if solvers:
185
+ data["linear_solvers"] = solvers
186
+
187
+ # --- turbulence ---
188
+ for rel in ("constant/momentumTransport", "constant/turbulenceProperties"):
189
+ tf = open_file(rel)
190
+ if tf is not None:
191
+ sim = _get(tf, "simulationType")
192
+ if sim is not None:
193
+ data["turbulence_type"] = str(sim)
194
+ # `RASModel` / `LESModel`, which is what OpenFOAM actually calls
195
+ # them. The key here was `model`, so `turbulence_model` has been
196
+ # `None` on every RAS case in the corpus — `pisoFoam/RAS/cavity` and
197
+ # `simpleFoam/pitzDaily` included — while `RASModel kEpsilon;` sat in
198
+ # the dictionary being read. Found independently by two solver
199
+ # families at once, and the asymmetry is telling: the fault injector
200
+ # already writes `RAS/RASModel` correctly, so the writer and the
201
+ # reader disagreed about the same key.
202
+ model = (_get(tf, "RAS", "RASModel") or _get(tf, "LES", "LESModel")
203
+ or _get(tf, "RAS", "model") or _get(tf, "LES", "model")
204
+ or _get(tf, "model"))
205
+ if model is not None:
206
+ data["turbulence_model"] = str(model)
207
+ break
208
+
209
+ # --- transport ---
210
+ tp = open_file("constant/transportProperties")
211
+ if tp is not None:
212
+ transport = {}
213
+ for name in ("nu", "rho", "Pr", "Prt"):
214
+ val = _scalar(_get(tp, name))
215
+ if val is not None:
216
+ transport[name] = val
217
+ if transport:
218
+ data["transport"] = transport
219
+
220
+ # --- boundary conditions (0/ field files) ---
221
+ boundary: dict[str, dict[str, str]] = {}
222
+ zero = os.path.join(case_dir, "0")
223
+ if os.path.isdir(zero):
224
+ for fname in os.listdir(zero):
225
+ fpath = os.path.join(zero, fname)
226
+ if not os.path.isfile(fpath):
227
+ continue
228
+ try:
229
+ ff = FoamFile(fpath)
230
+ _parse(ff, fpath) # VER-14: noted once read, parsed or not
231
+ for patch, spec in _subdict_items(ff, "boundaryField"):
232
+ t = _tokens(spec.get("type")) if hasattr(spec, "get") else None
233
+ if t:
234
+ boundary.setdefault(patch, {})[fname] = t
235
+ except Exception: # noqa: BLE001
236
+ continue
237
+ if boundary:
238
+ data["boundary"] = boundary
239
+
240
+ if unreadable:
241
+ data["unreadable"] = unreadable
242
+ # --- thermophysicalProperties: the compressible and buoyant families ---
243
+ #
244
+ # `transport` was read only from `constant/transportProperties`, which
245
+ # compressible and buoyant cases **do not have**. Their viscosity is `mu`,
246
+ # not `nu`, and it lives at `mixture/transport/mu` in a differently shaped
247
+ # file, with `Cp` under `mixture/thermodynamics`. Measured on real v2406
248
+ # tutorials: `CaseConfig.from_foam(...).transport == {}` for both
249
+ # `rhoPimpleFoam/RAS/cavity` and `buoyantPimpleFoam/hotRoom`.
250
+ #
251
+ # The consequence is a permanent blind spot rather than a false positive:
252
+ # `nu_out_of_range` and the `physics.nu` finding cannot fire on any solver
253
+ # in either family, so a units error in `mu` — the single most common
254
+ # real mistake there is, and the exact fault `PHYS.TRANSPORT_UNITS` names —
255
+ # was undetectable. Reported independently by both families.
256
+ thermo = open_file("constant/thermophysicalProperties")
257
+ if thermo is not None:
258
+ properties: dict[str, float] = dict(data.get("transport") or {})
259
+ for group, keys in (("transport", ("mu", "Pr")),
260
+ ("thermodynamics", ("Cp", "Hf")),
261
+ ("specie", ("molWeight",))):
262
+ for key in keys:
263
+ value = _scalar(_get(thermo, "mixture", group, key))
264
+ if value is not None:
265
+ properties.setdefault(key, value)
266
+ if properties:
267
+ data["transport"] = properties
268
+
269
+ return CaseConfig.from_dict({k: v for k, v in data.items() if v is not None})
courant/case/config.py ADDED
@@ -0,0 +1,134 @@
1
+ """CaseConfig — a structured, diagnosis-relevant view of an OpenFOAM case.
2
+
3
+ The full case is a tree of dictionaries (controlDict, fvSchemes, fvSolution, the
4
+ 0/ boundary fields, constant/ properties). Diagnosis only needs a curated subset:
5
+ timestep control, relaxation, schemes, linear-solver tolerances, turbulence model,
6
+ transport properties, and boundary-condition types. That subset is this model.
7
+
8
+ Two constructors:
9
+ * ``from_dict`` — build from a plain dict (benchmark ``case_facts.json``; replay).
10
+ * ``from_foam`` — parse a real case directory with foamlib (live path; lazy import).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from pydantic import BaseModel, ConfigDict, Field
16
+
17
+
18
+ class LinearSolverSpec(BaseModel):
19
+ model_config = ConfigDict(frozen=True)
20
+
21
+ field: str
22
+ solver: str | None = None # GAMG, PCG, smoothSolver, ...
23
+ tolerance: float | None = None
24
+ rel_tol: float | None = None
25
+
26
+
27
+ class CaseConfig(BaseModel):
28
+ model_config = ConfigDict(frozen=True)
29
+
30
+ solver: str | None = None
31
+
32
+ # controlDict
33
+ delta_t: float | None = None
34
+ end_time: float | None = None
35
+ adjust_timestep: bool | None = None
36
+ max_co: float | None = None
37
+ write_control: str | None = None
38
+ write_interval: float | None = None
39
+
40
+ # fvSchemes
41
+ ddt_scheme: str | None = None # steadyState, Euler, backward
42
+ div_schemes: dict[str, str] = Field(default_factory=dict) # term -> scheme
43
+
44
+ # fvSolution
45
+ relaxation_factors: dict[str, float] = Field(default_factory=dict) # field -> factor
46
+ #: Which sub-dictionary each relaxation key came from: ``"fields"``,
47
+ #: ``"equations"``, or ``""`` for a flat mapping.
48
+ #:
49
+ #: `relaxation_factors` deliberately flattens the two, because every checker
50
+ #: and KB predicate only cares *how high* a factor is. A **fix** has to write
51
+ #: the value back, and for that the scope is the difference between a valid
52
+ #: edit and a dry-run rejection — `simpleFoam/pitzDaily` has `equations` and
53
+ #: no `fields`, and guessing wrong cost the certification run a repair.
54
+ relaxation_scopes: dict[str, str] = Field(default_factory=dict)
55
+
56
+ #: Case files that exist but could not be parsed, file -> reason.
57
+ #:
58
+ #: Absence of a value and inability to read it are different facts and used
59
+ #: to be the same one. A `foamDictionary`-rewritten `controlDict` yielded a
60
+ #: config with no solver, no timestep and no write control, silently, and
61
+ #: every checker downstream behaved as though the engineer had omitted them.
62
+ unreadable: dict[str, str] = Field(default_factory=dict)
63
+ linear_solvers: dict[str, LinearSolverSpec] = Field(default_factory=dict)
64
+ n_non_orthogonal_correctors: int | None = None
65
+ n_correctors: int | None = None
66
+ #: PIMPLE's outer iterations. None reads as OpenFOAM's default of 1 (PISO mode); only
67
+ #: with more than one may a run legitimately sit above Courant 1 (VER-13).
68
+ n_outer_correctors: int | None = None
69
+
70
+ # turbulence
71
+ turbulence_type: str | None = None # laminar | RAS | LES
72
+ turbulence_model: str | None = None # kEpsilon, kOmegaSST, ...
73
+
74
+ # transport / thermophysical
75
+ transport: dict[str, float] = Field(default_factory=dict) # nu, etc.
76
+
77
+ # boundary conditions: patch -> field -> bc type
78
+ boundary: dict[str, dict[str, str]] = Field(default_factory=dict)
79
+
80
+ # multi-region (CHT)
81
+ regions: list[str] = Field(default_factory=list)
82
+
83
+ @classmethod
84
+ def from_dict(cls, data: dict) -> "CaseConfig":
85
+ d = dict(data)
86
+ if "linear_solvers" in d and d["linear_solvers"]:
87
+ d["linear_solvers"] = {
88
+ k: (v if isinstance(v, LinearSolverSpec)
89
+ else LinearSolverSpec(field=k, **v))
90
+ for k, v in d["linear_solvers"].items()
91
+ }
92
+ return cls.model_validate(d)
93
+
94
+ @classmethod
95
+ def from_foam(cls, case_dir: str) -> "CaseConfig": # pragma: no cover - needs foamlib+case
96
+ """Parse a real OpenFOAM case with foamlib (live path)."""
97
+ from courant.case._foam_reader import read_case_config
98
+
99
+ return read_case_config(case_dir)
100
+
101
+ # --- convenience predicates used by checkers ---
102
+ def is_steady(self) -> bool:
103
+ """Whether this case marches to a steady state.
104
+
105
+ Two sources, because either alone is wrong on real cases. `ddtSchemes
106
+ default steadyState` is the direct statement and takes precedence — a
107
+ case can say so explicitly, and a `simpleFoam` case with an explicit
108
+ transient scheme is not steady whatever its solver name suggests.
109
+
110
+ But `fvSchemes` is a file we may not have been able to read, and
111
+ `simpleFoam` is steady *by construction*: it has no time derivative to
112
+ discretise. Reading only the scheme meant such a case was treated as
113
+ transient, which silences every steady-only check — the relaxation
114
+ finding among them, on the one solver family where relaxation is the
115
+ thing that matters.
116
+ """
117
+ declared = (self.ddt_scheme or "").strip().lower()
118
+ if declared:
119
+ return declared == "steadystate"
120
+
121
+ from courant.case.solvers import is_steady as solver_is_steady
122
+
123
+ return solver_is_steady(self.solver)
124
+
125
+ def is_laminar(self) -> bool:
126
+ return (self.turbulence_type or "").strip().lower() == "laminar"
127
+
128
+ def boundary_types_for(self, field: str) -> dict[str, str]:
129
+ """patch -> bc type for a given field, across all patches."""
130
+ return {
131
+ patch: fields[field]
132
+ for patch, fields in self.boundary.items()
133
+ if field in fields
134
+ }
courant/case/mesh.py ADDED
@@ -0,0 +1,135 @@
1
+ """MeshQuality — structured checkMesh metrics for diagnosis (Tech Arch §5.1).
2
+
3
+ The mesh checker "wraps checkMesh; extracts skewness, non-orthogonality, aspect
4
+ ratio, negative volumes into structured Findings." This model is that structured
5
+ extraction. Constructors: ``from_dict`` (replay case-facts) and ``from_checkmesh``
6
+ (parse real checkMesh stdout, live path).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+
13
+ from pydantic import BaseModel, ConfigDict
14
+
15
+
16
+ class MeshQuality(BaseModel):
17
+ model_config = ConfigDict(frozen=True)
18
+
19
+ n_cells: int | None = None
20
+ max_non_orthogonality: float | None = None # degrees
21
+ average_non_orthogonality: float | None = None
22
+ max_skewness: float | None = None
23
+ max_aspect_ratio: float | None = None
24
+ n_negative_volume_cells: int = 0
25
+ mesh_ok: bool | None = None # checkMesh "Mesh OK." verdict
26
+
27
+ @classmethod
28
+ def from_dict(cls, data: dict) -> "MeshQuality":
29
+ return cls.model_validate(data)
30
+
31
+ @classmethod
32
+ def from_checkmesh(cls, text: str) -> "MeshQuality":
33
+ """Parse the metrics out of checkMesh stdout."""
34
+
35
+ # The first group that actually captured, not group(1).
36
+ #
37
+ # With an alternation, whichever branch matches at the *earliest*
38
+ # position wins — and for `aspect ratio…|Max aspect ratio…` against real
39
+ # output, that is the second branch, because "Max" starts before
40
+ # "aspect". So group(1) was None and `float(None)` raised TypeError on
41
+ # every real checkMesh log. `read_mesh_quality` catches and returns None,
42
+ # so the symptom was silent: mesh metrics simply never arrived, on the
43
+ # agent path as well as the live one, and all five MESH.* codes were
44
+ # undiagnosable even when a checkMesh log was sitting right there.
45
+ def _first(match: "re.Match | None") -> str | None:
46
+ if match is None:
47
+ return None
48
+ return next((g for g in match.groups() if g is not None), None)
49
+
50
+ def _f(pattern: str) -> float | None:
51
+ captured = _first(re.search(pattern, text))
52
+ return float(captured) if captured is not None else None
53
+
54
+ def _i(pattern: str) -> int | None:
55
+ captured = _first(re.search(pattern, text))
56
+ return int(captured) if captured is not None else None
57
+
58
+ non_ortho_max = _f(r"non-orthogonality Max:\s*([\d.eE+-]+)")
59
+ non_ortho_avg = _f(r"non-orthogonality Max:\s*[\d.eE+-]+\s*average:\s*([\d.eE+-]+)")
60
+ # `[=:]` — and this is the second time this line has been wrong.
61
+ #
62
+ # checkMesh prints the metric one way when the mesh is fine and another
63
+ # way when it is not:
64
+ #
65
+ # Max aspect ratio = 1 OK.
66
+ # ***High aspect ratio cells found, Max aspect ratio: 2000, ...
67
+ #
68
+ # The failing form uses a **colon**. With `=?` the value was readable
69
+ # only on a healthy mesh and unreadable on exactly the meshes worth
70
+ # reporting — so `MESH.ASPECT_RATIO` could never be diagnosed, and the
71
+ # scenario for it came back with an empty diagnosis while `checkMesh`
72
+ # was printing the number in as many words.
73
+ #
74
+ # A perfect inversion, and the same shape as the `CONV.MASS_IMBALANCE`
75
+ # log pattern that fired on healthy runs and missed broken ones. The
76
+ # lesson both times: the failing output is a *different string* from the
77
+ # passing one, and a pattern derived from a healthy run has never seen
78
+ # the case it exists for.
79
+ skew = _f(r"[Mm]ax skewness\s*[=:]?\s*([\d.eE+-]+)")
80
+ aspect = _f(r"Max aspect ratio\s*[=:]?\s*([\d.eE+-]+)|"
81
+ r"aspect ratio\s*[=:]?\s*([\d.eE+-]+)")
82
+ n_cells = _i(r"cells:\s*(\d+)")
83
+ neg = _i(r"(\d+)\s+cells with negative volume") or (
84
+ 0 if "negative volume" not in text.lower() else 1
85
+ )
86
+ mesh_ok = "Mesh OK." in text or "Mesh OK" in text
87
+
88
+ return cls(
89
+ n_cells=n_cells,
90
+ max_non_orthogonality=non_ortho_max,
91
+ average_non_orthogonality=non_ortho_avg,
92
+ max_skewness=skew,
93
+ max_aspect_ratio=aspect,
94
+ n_negative_volume_cells=neg or 0,
95
+ mesh_ok=mesh_ok,
96
+ )
97
+
98
+
99
+ #: Where a checkMesh log conventionally lands. `log.checkMesh` is what
100
+ #: OpenFOAM's own `runApplication` wrapper writes and what `DockerRunner` writes
101
+ #: for a pre-command; `checkMesh.log` is the other common hand-rolled spelling.
102
+ CHECKMESH_LOG_NAMES = ("log.checkMesh", "checkMesh.log")
103
+
104
+
105
+ def read_mesh_quality(case_dir: str) -> "MeshQuality | None":
106
+ """Mesh metrics from a checkMesh log already sitting in the case, or None.
107
+
108
+ Shared by the two paths that need it so there is one answer to "where does
109
+ the checkMesh log live". They differ in who *runs* checkMesh, not in where
110
+ they look for it:
111
+
112
+ * `courant watch` never runs it. That is the customer's cluster, their
113
+ queue and possibly their 50M-cell mesh, and a watcher that silently
114
+ starts a heavy job is a watcher nobody installs twice.
115
+ * `run_live_case` does, because the sandbox is ours and the run is already
116
+ happening inside it.
117
+
118
+ Never raises. A partial or truncated checkMesh log is common, and losing
119
+ mesh metrics must not cost the rest of the diagnosis.
120
+ """
121
+ from pathlib import Path
122
+
123
+ from courant.case.reads import note
124
+
125
+ for name in CHECKMESH_LOG_NAMES:
126
+ candidate = Path(case_dir) / name
127
+ if not candidate.is_file():
128
+ continue
129
+ try:
130
+ text = candidate.read_text(errors="replace")
131
+ note(candidate) # VER-14: read, so listed, whether or not it parses
132
+ return MeshQuality.from_checkmesh(text)
133
+ except Exception: # noqa: BLE001 — a partial log is not a failure
134
+ return None
135
+ return None
courant/case/reads.py ADDED
@@ -0,0 +1,90 @@
1
+ """Which case files the readers read (TRD VER-14).
2
+
3
+ A verdict's manifest is the set of files that decided it, and only a reader knows what it read.
4
+ So each reader notes its file at the line that reads it, and the verifier collects the notes
5
+ inside a `recording`. Nothing here guesses which files matter.
6
+
7
+ Outside a recording `note` does nothing, so a reader called from anywhere else (the watcher, the
8
+ fix loop) is unchanged. A note costs one `os.path.isfile`: no hashing and no other I/O. The
9
+ manifest hashes afterwards (`courant.verify.schema.manifest`).
10
+
11
+ A file is noted only once its read has succeeded (T-MANIFEST-2). A read that fails with an
12
+ `OSError` (the file cannot be opened, or vanished) read nothing, so the file is left out and the
13
+ reader's own fallback stands: an unreadable `0/U` is what it was before the manifest existed, a
14
+ missing field, and never a traceback. A read that got the bytes and could not parse them did read
15
+ the file, so it is noted. `reading(path)` is that rule, for readers whose failure is an exception.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ from collections.abc import Iterator
22
+ from contextlib import contextmanager
23
+ from contextvars import ContextVar
24
+
25
+
26
+ class Reads:
27
+ """The regular files read under one root, as root-relative POSIX paths.
28
+
29
+ Paths are compared lexically (`os.path.abspath`), never resolved, so a symlinked `0/` still
30
+ records as `0/U`: the path the reader used, which is the path a re-check will use.
31
+ """
32
+
33
+ def __init__(self, root: str | os.PathLike[str], parent: Reads | None = None) -> None:
34
+ self.root = os.path.abspath(os.fspath(root))
35
+ self._prefix = os.path.join(self.root, "")
36
+ self._paths: set[str] = set()
37
+ self._parent = parent
38
+
39
+ def add(self, path: str | os.PathLike[str]) -> None:
40
+ p = os.path.abspath(os.fspath(path))
41
+ if p.startswith(self._prefix) and os.path.isfile(p):
42
+ self._paths.add(p[len(self._prefix):].replace(os.sep, "/"))
43
+ if self._parent is not None:
44
+ self._parent.add(p)
45
+
46
+ def paths(self) -> list[str]:
47
+ return sorted(self._paths)
48
+
49
+
50
+ _current: ContextVar[Reads | None] = ContextVar("courant_case_reads", default=None)
51
+
52
+
53
+ @contextmanager
54
+ def recording(root: str | os.PathLike[str]) -> Iterator[Reads]:
55
+ """Collect every `note` made in the block for files under `root`. The recording that was
56
+ active before sees the same notes (a file read for `courant convergence` inside a verdict was
57
+ read for the verdict too), and it is restored on exit."""
58
+ reads = Reads(root, parent=_current.get())
59
+ token = _current.set(reads)
60
+ try:
61
+ yield reads
62
+ finally:
63
+ _current.reset(token)
64
+
65
+
66
+ def note(path: str | os.PathLike[str]) -> None:
67
+ """A reader read `path`. Recorded when a recording is active and `path` is a regular file
68
+ under its root; otherwise nothing happens."""
69
+ reads = _current.get()
70
+ if reads is not None:
71
+ reads.add(path)
72
+
73
+
74
+ @contextmanager
75
+ def reading(path: str | os.PathLike[str]) -> Iterator[None]:
76
+ """Note `path` once the block has read it (VER-14: listed only after a successful read).
77
+
78
+ The block ends normally: read, so noted. It raises `OSError`: nothing was read (the file
79
+ cannot be opened, or vanished), so it is not noted. It raises anything else: the bytes were
80
+ read and did not parse, so it is noted. The exception propagates either way, to the reader's
81
+ own fallback.
82
+ """
83
+ try:
84
+ yield
85
+ except OSError:
86
+ raise
87
+ except Exception:
88
+ note(path)
89
+ raise
90
+ note(path)