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
@@ -0,0 +1,435 @@
1
+ """Log/residual parser — raw OpenFOAM solver output -> structured Events.
2
+
3
+ This is the Watcher's parsing layer (Master Tech Architecture §8.1): a regex +
4
+ state-machine parser that turns solver stdout into typed Events. It is streaming:
5
+ feed it chunks as they arrive from the sandbox, and it yields Events as complete
6
+ information becomes available, buffering partial trailing lines.
7
+
8
+ It NEVER emits free-form prose — only structured fields, with byte offsets back
9
+ into the raw log for provenance. Anomaly detection over residual *history*
10
+ (slope, plateau, wall stall) lives in ``anomaly.py``; this module handles the
11
+ per-line facts and per-line NaN/Inf divergence.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ import re
18
+ from dataclasses import dataclass, field
19
+
20
+ from courant.events import (
21
+ ContinuityErrors,
22
+ CrashPayload,
23
+ DivergencePayload,
24
+ Event,
25
+ EventKind,
26
+ ResidualPayload,
27
+ Severity,
28
+ WarnPayload,
29
+ )
30
+
31
+ # --- Regexes (compiled once) ------------------------------------------------
32
+
33
+ _RE_TIME = re.compile(r"^Time = (\S+)")
34
+ #: The **bulk** Courant number, and only that one.
35
+ #:
36
+ #: `(?<![A-Za-z] )` is the whole fix. Multiphase and compressible solvers print
37
+ #: more than one Courant number per step, and this pattern matched every one of
38
+ #: them by substring — so on `interFoam` the line
39
+ #:
40
+ #: Interface Courant Number mean: 0.0421794 max: 0.762621
41
+ #:
42
+ #: matched, landed in the same step as the bulk reading that preceded it, and
43
+ #: **overwrote it**. Measured on a real `damBreak` run: the parser reported a
44
+ #: peak Courant of 1.11447, which is the interface peak exactly; the true bulk
45
+ #: peak was 1.24333. Every CFL check, the stability verdict, and the timestep
46
+ #: the fix proposer computes were all reading the wrong number on every VOF
47
+ #: case — and reading one that stays *low* while the bulk number is the one that
48
+ #: breaks a solve, so it fails silently and in the dangerous direction.
49
+ #:
50
+ #: The interface number is a real control (`maxAlphaCo`) and deserves its own
51
+ #: reading eventually. Conflating the two is what could not stand.
52
+ _RE_COURANT = re.compile(
53
+ r"(?<![A-Za-z] )Courant Number mean:\s*(\S+)\s+max:\s*(\S+)")
54
+ _RE_DELTAT = re.compile(r"^deltaT = (\S+)")
55
+ #: `[\w.]+`, not `\w+`. OpenFOAM field names contain dots — `alpha.water`,
56
+ #: `alpha.air`, `U.air`, `T.solid` — and `\w` excludes `.`, so
57
+ #:
58
+ #: smoothSolver: Solving for alpha.water, Initial residual = 0.0095, ...
59
+ #:
60
+ #: never matched. On a real `interFoam/damBreak` run the parser produced 121
61
+ #: residual steps carrying `p_rgh` and `pcorr` and nothing else: the phase
62
+ #: fraction — the field that *is* the free surface, and the whole point of a VOF
63
+ #: solve — was invisible. `worst_final_residual` then reported 5.3e-04 from the
64
+ #: pressure alone and called the run converged while `alpha.water` sat above
65
+ #: 1e-02 throughout.
66
+ #:
67
+ #: Every multiphase and multi-region solver OpenFOAM ships names fields this way.
68
+ _RE_RESIDUAL = re.compile(
69
+ r"Solving for ([\w.]+),\s*Initial residual = (\S+),\s*Final residual = (\S+),"
70
+ r"\s*No Iterations (\d+)"
71
+ )
72
+ _RE_CONTINUITY = re.compile(
73
+ r"time step continuity errors :\s*sum local = (\S+),\s*global = (\S+),"
74
+ r"\s*cumulative = (\S+)"
75
+ )
76
+ _RE_BOUNDING = re.compile(r"^bounding (\w+),\s*min:\s*(\S+)\s*max:\s*(\S+)(?:\s*average:\s*(\S+))?")
77
+ _RE_EXECTIME = re.compile(r"ExecutionTime = (\S+) s\s+ClockTime = (\S+) s")
78
+ _RE_FOAM_FATAL = re.compile(r"FOAM FATAL (?:IO )?ERROR")
79
+
80
+ #: OpenFOAM's own banner, printed by **every** run whose build traps FPEs — the
81
+ #: default:
82
+ #:
83
+ #: trapFpe: Floating point exception trapping enabled (FOAM_SIGFPE).
84
+ #:
85
+ #: It announces that trapping is *on*, not that anything went wrong. Matching it
86
+ #: as a crash gave a 100% false-positive rate on real solves: a healthy cavity
87
+ #: case emitted CRASH at line 18, before the time loop started. Checked first
88
+ #: and always, because the words it contains are the words a crash uses.
89
+ _RE_FPE_BANNER = re.compile(r"trapFpe:|trapping enabled|FOAM_SIGFPE")
90
+
91
+ #: What an actual fatal signal looks like in the log. Measured against a real
92
+ #: SIGFPE from a diverged icoFoam run (exit 136), not inferred:
93
+ #:
94
+ #: [stack trace]
95
+ #: #1 Foam::sigFpe::sigHandler(int) in …/libOpenFOAM.so
96
+ #:
97
+ #: `Foam::sig*::sigHandler` is the handler actually firing. `[stack trace]` is
98
+ #: the block header OpenFOAM prints for any fatal signal, so it also covers
99
+ #: SIGSEGV and SIGABRT. The bare phrase "Floating point exception" is the
100
+ #: *shell's* message and lands in the log only when stderr is merged into it —
101
+ #: kept for that case, and only when the banner has been ruled out.
102
+ _RE_FATAL_SIGNAL = re.compile(
103
+ r"Foam::sig(?:Fpe|Segv|Int|Quit)::sigHandler"
104
+ r"|Floating point exception"
105
+ r"|Segmentation fault"
106
+ )
107
+
108
+ #: The block header OpenFOAM prints before any fatal-signal backtrace. Handled
109
+ #: separately from the patterns above because it says *that* a signal fired
110
+ #: without saying which — the naming frame follows it.
111
+ _RE_STACK_TRACE_HEADER = re.compile(r"\[stack trace\]")
112
+
113
+ #: Which signal, when the log says. Ordered: the handler name is definitive, the
114
+ #: shell message is a fallback.
115
+ _RE_SIGNAL_NAME = [
116
+ (re.compile(r"sigFpe::sigHandler|Floating point exception"), "SIGFPE"),
117
+ (re.compile(r"sigSegv::sigHandler|Segmentation fault"), "SIGSEGV"),
118
+ ]
119
+
120
+
121
+ def _signal_name(line: str) -> str:
122
+ """Name the signal from the log line, defaulting to a truthful unknown."""
123
+ for pattern, name in _RE_SIGNAL_NAME:
124
+ if pattern.search(line):
125
+ return name
126
+ # `[stack trace]` alone says a fatal signal fired without saying which. The
127
+ # honest answer is that we do not know, not a guess at the most common one:
128
+ # the diagnosis reads this field.
129
+ return "FATAL"
130
+
131
+
132
+ def _to_float(token: str) -> float | None:
133
+ """Parse an OpenFOAM numeric token, tolerating nan/inf/(nan)/-nan etc."""
134
+ t = token.strip().strip("()")
135
+ try:
136
+ return float(t)
137
+ except ValueError:
138
+ low = t.lower()
139
+ if "nan" in low:
140
+ return math.nan
141
+ if "inf" in low:
142
+ return math.inf if not low.startswith("-") else -math.inf
143
+ return None
144
+
145
+
146
+ def _is_bad(x: float | None) -> bool:
147
+ return x is not None and (math.isnan(x) or math.isinf(x))
148
+
149
+
150
+ @dataclass
151
+ class _StepBuilder:
152
+ """Accumulates one solver time-step until its boundary is reached."""
153
+
154
+ time: float | None = None
155
+ iteration: int | None = None
156
+ initial_residuals: dict[str, float] = field(default_factory=dict)
157
+ final_residuals: dict[str, float] = field(default_factory=dict)
158
+ solver_iterations: dict[str, int] = field(default_factory=dict)
159
+ courant_mean: float | None = None
160
+ courant_max: float | None = None
161
+ continuity: ContinuityErrors | None = None
162
+ delta_t: float | None = None
163
+ exec_time: float | None = None
164
+ clock_time: float | None = None
165
+ _has_data: bool = False
166
+
167
+ def to_payload(self) -> ResidualPayload:
168
+ return ResidualPayload(
169
+ time=self.time,
170
+ iteration=self.iteration,
171
+ initial_residuals=dict(self.initial_residuals),
172
+ final_residuals=dict(self.final_residuals),
173
+ solver_iterations=dict(self.solver_iterations),
174
+ courant_mean=self.courant_mean,
175
+ courant_max=self.courant_max,
176
+ continuity=self.continuity,
177
+ delta_t=self.delta_t,
178
+ exec_time=self.exec_time,
179
+ clock_time=self.clock_time,
180
+ )
181
+
182
+
183
+ class LogParser:
184
+ """Streaming parser. One instance per run.
185
+
186
+ Usage::
187
+
188
+ parser = LogParser(run_id="r1")
189
+ for event in parser.feed(chunk):
190
+ ...
191
+ for event in parser.close(return_code=rc):
192
+ ...
193
+ """
194
+
195
+ def __init__(self, run_id: str, start_seq: int = 0):
196
+ self.run_id = run_id
197
+ self._seq = start_seq
198
+ self._offset = 0 # byte offset of next unconsumed char
199
+ self._buf = "" # partial trailing line
200
+ self._step = _StepBuilder()
201
+ self._iter_index = 0 # global step counter
202
+ self._foam_fatal_seen = False
203
+ self._crash_emitted = False # dedupe inline crash vs close() crash
204
+ self._stack_trace_at: int | None = None # a deferred [stack trace]
205
+
206
+ # -- public API ---------------------------------------------------------
207
+
208
+ def feed(self, text: str) -> list[Event]:
209
+ """Feed a chunk of raw log text; returns Events ready to emit."""
210
+ buf = self._buf + text
211
+ events: list[Event] = []
212
+ # One moving index, and the remainder is kept once at the end.
213
+ # Re-slicing the buffer after every line copied the whole rest of it
214
+ # 110,061 times on a 10 MB log: 40 of the 44 seconds `courant verify`
215
+ # took on the largest certified run (TRD PERF-1).
216
+ pos = 0
217
+ while True:
218
+ nl = buf.find("\n", pos)
219
+ if nl == -1:
220
+ break
221
+ line = buf[pos:nl]
222
+ line_offset = self._offset
223
+ # advance offset by the consumed bytes (line + newline)
224
+ self._offset += len(line.encode("utf-8")) + 1
225
+ pos = nl + 1
226
+ events.extend(self._consume_line(line, line_offset))
227
+ self._buf = buf[pos:]
228
+ return events
229
+
230
+ def close(self, return_code: int | None = None) -> list[Event]:
231
+ """Flush the final in-progress step and, if the run failed, emit CRASH."""
232
+ events: list[Event] = []
233
+ # flush trailing partial line as a full line (best effort)
234
+ if self._buf:
235
+ events.extend(self._consume_line(self._buf, self._offset))
236
+ self._offset += len(self._buf.encode("utf-8"))
237
+ self._buf = ""
238
+ if self._step._has_data:
239
+ events.append(self._emit(EventKind.RESIDUAL, self._step.to_payload()))
240
+ self._step = _StepBuilder()
241
+ # A stack trace whose frames never named a signal is still a crash.
242
+ # Reported as FATAL rather than guessed at: the diagnosis reads this.
243
+ if self._stack_trace_at is not None and not self._crash_emitted:
244
+ self._crash_emitted = True
245
+ events.append(
246
+ self._emit(
247
+ EventKind.CRASH,
248
+ CrashPayload(signal="FATAL", tag="fatal_signal"),
249
+ severity=Severity.ERROR,
250
+ log_offset=self._stack_trace_at,
251
+ )
252
+ )
253
+ self._stack_trace_at = None
254
+
255
+ if return_code not in (None, 0) and not self._crash_emitted:
256
+ events.append(
257
+ self._emit(
258
+ EventKind.CRASH,
259
+ CrashPayload(return_code=return_code, tag="nonzero_exit"),
260
+ severity=Severity.ERROR,
261
+ )
262
+ )
263
+ return events
264
+
265
+ def parse_text(self, text: str, return_code: int | None = 0) -> list[Event]:
266
+ """Convenience: parse a complete log string in one call."""
267
+ events = self.feed(text)
268
+ events.extend(self.close(return_code=return_code))
269
+ return events
270
+
271
+ # -- internals ----------------------------------------------------------
272
+
273
+ def _emit(self, kind: EventKind, payload, severity: Severity = Severity.INFO,
274
+ log_offset: int | None = None) -> Event:
275
+ ev = Event(
276
+ run_id=self.run_id,
277
+ seq=self._seq,
278
+ kind=kind,
279
+ severity=severity,
280
+ payload=payload,
281
+ ts_sim=self._step.time,
282
+ log_offset=log_offset,
283
+ )
284
+ self._seq += 1
285
+ return ev
286
+
287
+ def _consume_line(self, line: str, offset: int) -> list[Event]:
288
+ events: list[Event] = []
289
+
290
+ # New time-step boundary: flush the previous step first.
291
+ m = _RE_TIME.match(line)
292
+ if m:
293
+ if self._step._has_data:
294
+ events.append(self._emit(EventKind.RESIDUAL, self._step.to_payload()))
295
+ self._step = _StepBuilder()
296
+ self._iter_index += 1
297
+ val = _to_float(m.group(1))
298
+ self._step.time = val
299
+ # steady solvers print integer 'Time' = iteration index
300
+ if val is not None and float(val).is_integer():
301
+ self._step.iteration = int(val)
302
+ else:
303
+ self._step.iteration = self._iter_index
304
+ self._step._has_data = True
305
+ return events
306
+
307
+ m = _RE_DELTAT.match(line)
308
+ if m:
309
+ self._step.delta_t = _to_float(m.group(1))
310
+ self._step._has_data = True
311
+ return events
312
+
313
+ m = _RE_COURANT.search(line)
314
+ if m:
315
+ self._step.courant_mean = _to_float(m.group(1))
316
+ self._step.courant_max = _to_float(m.group(2))
317
+ self._step._has_data = True
318
+ return events
319
+
320
+ m = _RE_RESIDUAL.search(line)
321
+ if m:
322
+ fieldname, init_s, final_s, iters_s = m.groups()
323
+ init = _to_float(init_s)
324
+ fin = _to_float(final_s)
325
+ if init is not None:
326
+ self._step.initial_residuals[fieldname] = init
327
+ if fin is not None:
328
+ self._step.final_residuals[fieldname] = fin
329
+ self._step.solver_iterations[fieldname] = int(iters_s)
330
+ self._step._has_data = True
331
+ # per-line divergence: a NaN/Inf residual is an immediate red flag
332
+ if _is_bad(init) or _is_bad(fin):
333
+ events.append(
334
+ self._emit(
335
+ EventKind.DIVERGENCE,
336
+ DivergencePayload(
337
+ field=fieldname,
338
+ residual=init if _is_bad(init) else fin,
339
+ is_nan=(_is_bad(init) and math.isnan(init))
340
+ or (_is_bad(fin) and math.isnan(fin)),
341
+ is_inf=(_is_bad(init) and math.isinf(init))
342
+ or (_is_bad(fin) and math.isinf(fin)),
343
+ ),
344
+ severity=Severity.ERROR,
345
+ log_offset=offset,
346
+ )
347
+ )
348
+ return events
349
+
350
+ m = _RE_CONTINUITY.search(line)
351
+ if m:
352
+ self._step.continuity = ContinuityErrors(
353
+ sum_local=_to_float(m.group(1)),
354
+ **{"global": _to_float(m.group(2))},
355
+ cumulative=_to_float(m.group(3)),
356
+ )
357
+ self._step._has_data = True
358
+ return events
359
+
360
+ m = _RE_BOUNDING.match(line)
361
+ if m:
362
+ events.append(
363
+ self._emit(
364
+ EventKind.WARN,
365
+ WarnPayload(category="bounding", field=m.group(1), count=1,
366
+ minimum=_to_float(m.group(2)), maximum=_to_float(m.group(3)),
367
+ average=_to_float(m.group(4)) if m.group(4) else None),
368
+ severity=Severity.WARN,
369
+ log_offset=offset,
370
+ )
371
+ )
372
+ return events
373
+
374
+ m = _RE_EXECTIME.search(line)
375
+ if m:
376
+ self._step.exec_time = _to_float(m.group(1))
377
+ self._step.clock_time = _to_float(m.group(2))
378
+ self._step._has_data = True
379
+ return events
380
+
381
+ if _RE_FOAM_FATAL.search(line):
382
+ self._foam_fatal_seen = True
383
+ self._crash_emitted = True
384
+ events.append(
385
+ self._emit(
386
+ EventKind.CRASH,
387
+ CrashPayload(foam_fatal=True, tag="foam_fatal"),
388
+ severity=Severity.ERROR,
389
+ log_offset=offset,
390
+ )
391
+ )
392
+ return events
393
+
394
+ # The banner wins. It contains the same words a real crash does, and it
395
+ # is present on every healthy run, so it has to be excluded before the
396
+ # crash patterns are consulted rather than after.
397
+ if _RE_FPE_BANNER.search(line):
398
+ return events
399
+
400
+ if _RE_STACK_TRACE_HEADER.search(line):
401
+ # The header says a fatal signal fired; the frame naming *which* one
402
+ # is a line or two below it. Remember the offset and wait — emitting
403
+ # here would permanently record "FATAL" for a crash the log
404
+ # identifies precisely, and events are immutable once emitted.
405
+ if not self._crash_emitted and self._stack_trace_at is None:
406
+ self._stack_trace_at = offset
407
+ return events
408
+
409
+ if _RE_FATAL_SIGNAL.search(line):
410
+ # A stack trace is many lines; one CRASH per run is the fact.
411
+ if self._crash_emitted:
412
+ return events
413
+ self._crash_emitted = True
414
+ events.append(
415
+ self._emit(
416
+ EventKind.CRASH,
417
+ CrashPayload(signal=_signal_name(line), tag="fatal_signal"),
418
+ severity=Severity.ERROR,
419
+ # The header, not this frame: it is where the failure starts
420
+ # in the log, and it is the line a reader wants shown.
421
+ log_offset=self._stack_trace_at
422
+ if self._stack_trace_at is not None else offset,
423
+ )
424
+ )
425
+ self._stack_trace_at = None
426
+ return events
427
+
428
+ return events
429
+
430
+
431
+ def parse_log_file(path: str, run_id: str, return_code: int | None = 0) -> list[Event]:
432
+ """Parse a complete log file from disk into Events."""
433
+ with open(path, "r", errors="replace") as fh:
434
+ text = fh.read()
435
+ return LogParser(run_id=run_id).parse_text(text, return_code=return_code)
@@ -0,0 +1,49 @@
1
+ """The Watcher façade — attaches to a run and turns a raw line stream into the
2
+ complete Event stream (parser facts + history-based anomalies).
3
+
4
+ This is the single object the Run Sandbox feeds. It owns a LogParser (line -> facts)
5
+ and an AnomalyDetector (history -> anomalies), and merges their output in order.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from courant.events import Event, EventKind
11
+ from courant.watcher.anomaly import AnomalyConfig, AnomalyDetector
12
+ from courant.watcher.parser import LogParser
13
+
14
+
15
+ class Watcher:
16
+ """Owns parsing + anomaly detection for one run.
17
+
18
+ Feed it raw log chunks via :meth:`feed`; poll :meth:`tick` from a wall timer;
19
+ call :meth:`finalize` when the solver exits. Each returns Events in order.
20
+ """
21
+
22
+ def __init__(self, run_id: str, anomaly_config: AnomalyConfig | None = None):
23
+ self.run_id = run_id
24
+ self._parser = LogParser(run_id)
25
+ self._anomaly = AnomalyDetector(run_id, anomaly_config)
26
+ self.events: list[Event] = []
27
+
28
+ def feed(self, text: str) -> list[Event]:
29
+ produced: list[Event] = []
30
+ for ev in self._parser.feed(text):
31
+ produced.append(ev)
32
+ if ev.kind is EventKind.RESIDUAL:
33
+ produced.extend(self._anomaly.observe(ev))
34
+ self.events.extend(produced)
35
+ return produced
36
+
37
+ def tick(self, now: float) -> list[Event]:
38
+ produced = self._anomaly.check_wall_stall(now)
39
+ self.events.extend(produced)
40
+ return produced
41
+
42
+ def finalize(self, return_code: int | None) -> list[Event]:
43
+ produced: list[Event] = []
44
+ for ev in self._parser.close(return_code=return_code):
45
+ produced.append(ev)
46
+ if ev.kind is EventKind.RESIDUAL:
47
+ produced.extend(self._anomaly.observe(ev))
48
+ self.events.extend(produced)
49
+ return produced
@@ -0,0 +1,146 @@
1
+ Metadata-Version: 2.4
2
+ Name: courant-dev
3
+ Version: 0.5.0
4
+ Summary: Courant: physics acceptance testing for machine-produced simulation. A read-only, deterministic gate that accepts, rejects or abstains on an OpenFOAM run, with the reasons it read.
5
+ Author: Shivanshu Dwivedi
6
+ Maintainer-email: Courant <hello@courant.dev>
7
+ License-Expression: Apache-2.0
8
+ Project-URL: Homepage, https://courant.dev
9
+ Project-URL: Repository, https://github.com/courantdev/courant
10
+ Project-URL: Releases, https://github.com/courantdev/courant/releases
11
+ Project-URL: Issues, https://github.com/courantdev/courant/issues
12
+ Keywords: openfoam,cfd,simulation,verification,ai-agents,mcp,ci
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: MacOS
18
+ Classifier: Operating System :: POSIX :: Linux
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Topic :: Scientific/Engineering
24
+ Classifier: Topic :: Scientific/Engineering :: Physics
25
+ Classifier: Topic :: Software Development :: Quality Assurance
26
+ Classifier: Topic :: Software Development :: Testing
27
+ Requires-Python: >=3.11
28
+ Description-Content-Type: text/markdown
29
+ License-File: LICENSE
30
+ License-File: NOTICE
31
+ Requires-Dist: pydantic>=2.6
32
+ Requires-Dist: typer>=0.12
33
+ Requires-Dist: rich>=13.7
34
+ Requires-Dist: numpy>=1.26
35
+ Requires-Dist: foamlib>=1.6
36
+ Requires-Dist: httpx>=0.27
37
+ Provides-Extra: sandbox
38
+ Requires-Dist: docker>=7.0; extra == "sandbox"
39
+ Provides-Extra: diagnosis
40
+ Requires-Dist: anthropic>=0.40; extra == "diagnosis"
41
+ Provides-Extra: build
42
+ Requires-Dist: pyinstaller>=6.6; extra == "build"
43
+ Provides-Extra: dev
44
+ Requires-Dist: pytest>=8.0; extra == "dev"
45
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
46
+ Requires-Dist: ruff>=0.4; extra == "dev"
47
+ Requires-Dist: pyyaml>=6.0; extra == "dev"
48
+ Requires-Dist: jsonschema>=4.20; extra == "dev"
49
+ Provides-Extra: mcp
50
+ Requires-Dist: mcp<3,>=2.2; extra == "mcp"
51
+ Dynamic: license-file
52
+
53
+ # Courant
54
+
55
+ **Physics acceptance testing for machine-produced simulation.** Courant is a read-only,
56
+ deterministic gate between a simulation (an AI agent's or an engineer's) and the person who
57
+ signs it. Without a task specification it decides whether an OpenFOAM run is *valid*; with the
58
+ task the run was asked to solve, it decides whether the run is *the problem that was asked*.
59
+
60
+ Every verdict is `accept`, `reject` or `insufficient`, and every reason cites the file it read,
61
+ the method, the threshold and the value. Deterministic code decides every verdict; no language
62
+ model is in the verdict's path. Courant never edits a case, never runs a solver, and its checks
63
+ never use the network.
64
+
65
+ Licensed under the [Apache License 2.0](https://github.com/courantdev/courant/blob/main/LICENSE).
66
+
67
+ ## Install
68
+
69
+ <!-- docs-skip: installs from the package index, which CI does not reach -->
70
+ ```bash
71
+ pip install 'courant-dev[mcp]' # Python 3.11 or later; the command is `courant`
72
+ ```
73
+
74
+ The distribution is named `courant-dev` (PyPI's `courant` is an unrelated project); the import
75
+ package and the commands are `courant` and `courant-mcp`.
76
+
77
+ A single-file binary for Linux and macOS, which needs no Python, is attached to every
78
+ [release](https://github.com/courantdev/courant/releases), with `SHA256SUMS` and its Ed25519
79
+ signature:
80
+
81
+ <!-- docs-skip: downloads the installer from GitHub, which CI does not reach -->
82
+ ```bash
83
+ curl -fsSL https://github.com/courantdev/courant/releases/latest/download/install.sh | sh
84
+ ```
85
+
86
+ The installer checks the binary's SHA-256 against the release's `SHA256SUMS`, and the signature
87
+ of `SHA256SUMS` against the release key it carries when python3 with the `cryptography` package
88
+ or OpenSSL 3 is on the machine. With neither, it says that only the checksum was checked and how
89
+ to check the signature by hand; `COURANT_REQUIRE_SIGNATURE=1` makes it refuse instead.
90
+ `courant update` installs nothing unless the signature verifies against the key built into the
91
+ binary.
92
+
93
+ ## Try it offline
94
+
95
+ These run on the real OpenFOAM runs that ship inside the package, with no network:
96
+
97
+ ```bash
98
+ courant demo # four real runs and an HTML report
99
+ courant verify --about # the error rates published for this version
100
+ ```
101
+
102
+ ## What it does
103
+
104
+ | Command | What it does |
105
+ |---|---|
106
+ | `courant verify <case or log>` | `accept`, `reject` or `insufficient` (exit 0, 2 or 3; `courant.verdict/2`), with the basis it was judged on and what was not checked. `--spec` with `--spec-sha256` checks every value a task specification names against the case. `--html`, `--report md`, `--json`, `--pack` and `--check-pack` (an evidence pack anyone can re-derive), `--batch` with `--junit`, `--record`, `--about` |
107
+ | `courant spec init / hash / check / lock / confirm / extract` | Draft a task specification from a reference case, lock it by hash, and check a case against it before or after its run |
108
+ | `courant gate` | The CI check, and the [GitHub Action](https://github.com/courantdev/courant/tree/main/.github/actions/courant-gate): verify the runs a repository names, one summary row per run, one evidence pack per run |
109
+ | `courant preflight <case>` | A broken setup, caught before the solver spends anything |
110
+ | `courant convergence <case>` | Where the monitored answer stopped changing, and the iterations, wall clock and core-hours after it |
111
+ | `courant watch <case>` | A read-only live advisory while the solver runs, with `--exit-on-fail` for job scripts |
112
+ | `courant audit <dir>` | What a folder of runs cost, and how much of it bought nothing |
113
+ | `courant test run --judge …` | The Courant Test: score any judge, including an AI model, on real OpenFOAM runs |
114
+ | `courant mcp` | The same tools for any AI agent over MCP, read-only and confined to the directories named; `score_agent_output` tells an agent, before it reports, whether its run is a silent error |
115
+ | `courant doctor`, `courant update`, `courant version` | Diagnostics and a support bundle you send yourself; a signed update of the binary |
116
+
117
+ The checks never use the network. A command contacts something only when that is its purpose
118
+ and you ran it, and it names the host first: `courant update` (github.com), `courant doctor
119
+ --models`, and a language model you name
120
+ ([NETWORK.md](https://github.com/courantdev/courant/blob/main/docs/NETWORK.md)). Start with
121
+ [GETTING-STARTED.md](https://github.com/courantdev/courant/blob/main/docs/GETTING-STARTED.md).
122
+
123
+ ## What is measured
124
+
125
+ On OpenFOAM v2406, with every figure carrying its denominator (`courant verify --about` prints
126
+ the rates that ship with each version):
127
+
128
+ - **Detection:** 31 of 31 real runs judged correctly. 0 of 23 wrong results accepted and 0 of 8
129
+ good results rejected.
130
+ - **The wrong problem:** on 20 real runs with the right physics and a wrong input (inlet
131
+ doubled, viscosity tripled, gravity rotated, geometry scaled, end time cut), the verdict
132
+ without a specification rejected 8 of 20; against the task specification, 20 of 20.
133
+ - **Before the run:** preflight caught 8 of 23 broken setups, and flagged 0 of 8 good ones.
134
+ - **Fixed budgets:** where the answer settled, 1,023 of 1,999 iterations (51.2%, pitzDaily)
135
+ and 547 of 999 (54.8%, T3A) came after it.
136
+ - **Reproducible:** evidence packs re-derive byte for byte, 31 of 31.
137
+
138
+ "Certified" here means measured against a real solver, with the error rate published. It is not
139
+ a regulator's approval. Courant has no account, no telemetry and no service of its own.
140
+
141
+ ## Contributing and security
142
+
143
+ See [CONTRIBUTING.md](https://github.com/courantdev/courant/blob/main/CONTRIBUTING.md) and
144
+ [SECURITY.md](https://github.com/courantdev/courant/blob/main/SECURITY.md).
145
+
146
+ Copyright 2026 Shivanshu Dwivedi (Courant, https://courant.dev)