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.
- courant/__init__.py +26 -0
- courant/case/__init__.py +0 -0
- courant/case/_foam_reader.py +269 -0
- courant/case/config.py +134 -0
- courant/case/mesh.py +135 -0
- courant/case/reads.py +90 -0
- courant/case/schemes.py +99 -0
- courant/case/solvers.py +170 -0
- courant/cli/__init__.py +0 -0
- courant/cli/commands/__init__.py +6 -0
- courant/cli/commands/audit.py +40 -0
- courant/cli/commands/convergence.py +68 -0
- courant/cli/commands/ctest.py +76 -0
- courant/cli/commands/doctor.py +162 -0
- courant/cli/commands/gate.py +88 -0
- courant/cli/commands/live.py +73 -0
- courant/cli/commands/mcp.py +57 -0
- courant/cli/commands/preflight.py +36 -0
- courant/cli/commands/spec.py +231 -0
- courant/cli/commands/tour.py +122 -0
- courant/cli/commands/update.py +213 -0
- courant/cli/commands/verify.py +222 -0
- courant/cli/config.py +244 -0
- courant/cli/guard.py +69 -0
- courant/cli/main.py +130 -0
- courant/cli/tail.py +351 -0
- courant/config.py +155 -0
- courant/converge/__init__.py +57 -0
- courant/converge/assess.py +823 -0
- courant/converge/exact.py +112 -0
- courant/converge/render.py +182 -0
- courant/converge/scale.py +87 -0
- courant/converge/sentences.py +82 -0
- courant/converge/series.py +413 -0
- courant/converge/steady.py +261 -0
- courant/converge/tables.py +1019 -0
- courant/converge/transient.py +314 -0
- courant/ctest/__init__.py +6 -0
- courant/ctest/build.py +82 -0
- courant/ctest/data/judge-v0.labels.jsonl +31 -0
- courant/ctest/data/judge-v0.tasks.jsonl.gz +0 -0
- courant/ctest/judges/__init__.py +27 -0
- courant/ctest/judges/constant.py +18 -0
- courant/ctest/judges/courant.py +23 -0
- courant/ctest/judges/llm.py +166 -0
- courant/ctest/run.py +74 -0
- courant/ctest/schema.py +46 -0
- courant/ctest/score.py +91 -0
- courant/ctest/splits.py +20 -0
- courant/data/__init__.py +46 -0
- courant/data/certification.json +1 -0
- courant/data/certified_codes.json +18 -0
- courant/data/demo/icoFoam_cavity__cfl_blowup.case.json +68 -0
- courant/data/demo/icoFoam_cavity__cfl_blowup.log.gz +0 -0
- courant/data/demo/icoFoam_cavity__healthy.case.json +68 -0
- courant/data/demo/icoFoam_cavity__healthy.log.gz +0 -0
- courant/data/demo/icoFoam_cavity__transport_units.case.json +68 -0
- courant/data/demo/icoFoam_cavity__transport_units.log.gz +0 -0
- courant/data/demo/pitzDaily_fixed_budget.tar.gz +0 -0
- courant/data/schemas/audit.1.json +129 -0
- courant/data/schemas/cache.1.json +77 -0
- courant/data/schemas/convergence.1.json +112 -0
- courant/data/schemas/error-rates.1.json +53 -0
- courant/data/schemas/preflight.1.json +250 -0
- courant/data/schemas/record.1.json +155 -0
- courant/data/schemas/release-signature.1.json +39 -0
- courant/data/schemas/spec.1.json +258 -0
- courant/data/schemas/support.1.json +80 -0
- courant/data/schemas/verdict.1.json +716 -0
- courant/data/schemas/verdict.2.json +752 -0
- courant/diagnosis/__init__.py +0 -0
- courant/diagnosis/bundle.py +168 -0
- courant/diagnosis/checkers.py +919 -0
- courant/diagnosis/deterministic.py +110 -0
- courant/diagnosis/findings.py +107 -0
- courant/diagnosis/kb.py +188 -0
- courant/diagnosis/kb_data.py +253 -0
- courant/diagnosis/llm.py +299 -0
- courant/diagnosis/redact.py +425 -0
- courant/diagnosis/schema.py +83 -0
- courant/events/__init__.py +35 -0
- courant/events/core.py +194 -0
- courant/events/diverged.py +55 -0
- courant/gate/__init__.py +1 -0
- courant/gate/config.py +150 -0
- courant/gate/run.py +295 -0
- courant/live/__init__.py +16 -0
- courant/live/engine.py +155 -0
- courant/live/watch.py +164 -0
- courant/llm/__init__.py +59 -0
- courant/llm/allowlist.py +60 -0
- courant/llm/anthropic.py +137 -0
- courant/llm/budget.py +491 -0
- courant/llm/door.py +1071 -0
- courant/llm/errors.py +105 -0
- courant/llm/openrouter.py +118 -0
- courant/llm/policy.py +268 -0
- courant/llm/transport.py +48 -0
- courant/mcp/__init__.py +7 -0
- courant/mcp/server.py +113 -0
- courant/mcp/tools.py +177 -0
- courant/record/__init__.py +22 -0
- courant/record/filter.py +99 -0
- courant/record/record.py +149 -0
- courant/release.py +205 -0
- courant/signing.py +99 -0
- courant/spec/__init__.py +31 -0
- courant/spec/check.py +353 -0
- courant/spec/deck.py +455 -0
- courant/spec/extract.py +181 -0
- courant/spec/impossible.py +197 -0
- courant/spec/model.py +194 -0
- courant/taxonomy.py +219 -0
- courant/verification/__init__.py +30 -0
- courant/verification/_fluid_reader.py +228 -0
- courant/verification/bounding.py +84 -0
- courant/verification/checks.py +369 -0
- courant/verification/convergence.py +257 -0
- courant/verification/fields.py +38 -0
- courant/verification/grade.py +101 -0
- courant/verification/suite.py +30 -0
- courant/verify/__init__.py +37 -0
- courant/verify/about.py +100 -0
- courant/verify/audit.py +209 -0
- courant/verify/batch.py +141 -0
- courant/verify/cache.py +329 -0
- courant/verify/checks.py +37 -0
- courant/verify/html.py +330 -0
- courant/verify/ingest.py +115 -0
- courant/verify/junit.py +48 -0
- courant/verify/outcome.py +74 -0
- courant/verify/pack.py +106 -0
- courant/verify/pipeline.py +396 -0
- courant/verify/policy.py +167 -0
- courant/verify/preflight.py +166 -0
- courant/verify/render.py +174 -0
- courant/verify/schema.py +398 -0
- courant/verify/sentences.py +137 -0
- courant/verify/support.py +142 -0
- courant/verify/verdict2.py +235 -0
- courant/watcher/__init__.py +13 -0
- courant/watcher/anomaly.py +244 -0
- courant/watcher/exitcode.py +23 -0
- courant/watcher/parser.py +435 -0
- courant/watcher/watcher.py +49 -0
- courant_dev-0.5.0.dist-info/METADATA +146 -0
- courant_dev-0.5.0.dist-info/RECORD +152 -0
- courant_dev-0.5.0.dist-info/WHEEL +5 -0
- courant_dev-0.5.0.dist-info/entry_points.txt +3 -0
- courant_dev-0.5.0.dist-info/licenses/LICENSE +202 -0
- courant_dev-0.5.0.dist-info/licenses/NOTICE +4 -0
- courant_dev-0.5.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""`courant.verdict/2`: accept, reject or insufficient, with its basis stated (TRD GATE-1..GATE-3,
|
|
2
|
+
ARC-16, §32; PRD 2.0 P2-GATE-1).
|
|
3
|
+
|
|
4
|
+
Version 2 is a re-statement of version 1, not a second judgement. The pipeline decides once
|
|
5
|
+
(`courant.verify.policy`, in version 1's words), and `to_v2` maps that decision through one
|
|
6
|
+
table, `FROM_V1`: TRUSTWORTHY to `accept`, NOT_TRUSTWORTHY to `reject`, NOT_ASSESSABLE to
|
|
7
|
+
`insufficient`. The rule that decided (`VER-5.x`), the grade, the reasons, the causes, the stats and
|
|
8
|
+
the convergence and conformance blocks are carried unchanged. `VerdictV2.to_v1()` rebuilds the
|
|
9
|
+
version 1 verdict byte for byte, so `--schema 1` (ARC-16) and the Courant Test's locked labels
|
|
10
|
+
(GATE-3) are the same decision in the old words.
|
|
11
|
+
|
|
12
|
+
What version 2 adds:
|
|
13
|
+
|
|
14
|
+
- `basis` (GATE-2): what the verdict was judged against. `validity` with no specification;
|
|
15
|
+
`validity+conformance` with a specification whose SHA-256 was locked before the run and
|
|
16
|
+
matches; `validity+unlocked-spec` with a specification given without a lock, or one that does
|
|
17
|
+
not match its lock (VER-5.8 then makes the verdict `insufficient`); `validity+extracted-spec`
|
|
18
|
+
with an extracted specification nobody confirmed (SPEC-7, `courant spec extract`). The basis
|
|
19
|
+
states what the policy was already told: the pipeline passes the same `extracted` flag to
|
|
20
|
+
`policy.apply_conformance`, where VER-5.12 turns a mismatch into `insufficient`, so the label
|
|
21
|
+
never stands in for the rule.
|
|
22
|
+
- `run.fork` and `run.solver_version` (ADP-1). Always present; `null` until the banner reader
|
|
23
|
+
fills them.
|
|
24
|
+
- With no specification, the not-checked list ends with `sentences.NO_SPEC` (GATE-2).
|
|
25
|
+
|
|
26
|
+
Readers accept both majors (`load_verdict`). Every surface writes version 2 by default and
|
|
27
|
+
version 1 behind `--schema 1` for one minor release.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import itertools
|
|
33
|
+
import json
|
|
34
|
+
from collections.abc import Mapping
|
|
35
|
+
from typing import Literal
|
|
36
|
+
|
|
37
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
38
|
+
|
|
39
|
+
from courant.verify import sentences
|
|
40
|
+
from courant.verify.schema import (
|
|
41
|
+
SCHEMA as SCHEMA_V1,
|
|
42
|
+
)
|
|
43
|
+
from courant.verify.schema import (
|
|
44
|
+
ConformanceBlock,
|
|
45
|
+
ConvergenceBlock,
|
|
46
|
+
InputFile,
|
|
47
|
+
ProbableCause,
|
|
48
|
+
Reason,
|
|
49
|
+
RunInfo,
|
|
50
|
+
Source,
|
|
51
|
+
Stats,
|
|
52
|
+
ToolInfo,
|
|
53
|
+
Verdict,
|
|
54
|
+
VerdictValue,
|
|
55
|
+
canonical_json,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
SCHEMA_V2 = "courant.verdict/2"
|
|
59
|
+
#: The schema majors a writer can emit (ARC-16): 2 by default, 1 for one minor release.
|
|
60
|
+
SCHEMAS = {1: SCHEMA_V1, 2: SCHEMA_V2}
|
|
61
|
+
|
|
62
|
+
Decision = Literal["accept", "reject", "insufficient"]
|
|
63
|
+
Basis = Literal["validity", "validity+conformance", "validity+unlocked-spec",
|
|
64
|
+
"validity+extracted-spec"]
|
|
65
|
+
|
|
66
|
+
#: GATE-1: the version 1 answer to the version 2 answer. A bijection; `TO_V1` is its inverse.
|
|
67
|
+
FROM_V1: dict[str, str] = {"TRUSTWORTHY": "accept", "NOT_TRUSTWORTHY": "reject",
|
|
68
|
+
"NOT_ASSESSABLE": "insufficient"}
|
|
69
|
+
TO_V1: dict[str, str] = {v2: v1 for v1, v2 in FROM_V1.items()}
|
|
70
|
+
|
|
71
|
+
#: The exit code of each answer (GATE-1): 0, 2 and 3; 4 is an unreadable input (GATE-10).
|
|
72
|
+
EXIT: dict[str, int] = {"accept": 0, "reject": 2, "insufficient": 3}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class RunInfoV2(BaseModel):
|
|
76
|
+
model_config = ConfigDict(frozen=True)
|
|
77
|
+
|
|
78
|
+
id: str
|
|
79
|
+
source: Source
|
|
80
|
+
solver: str | None
|
|
81
|
+
#: ADP-1: the solver fork (`esi` or `foundation`) and version read from the log banner.
|
|
82
|
+
fork: str | None = None
|
|
83
|
+
solver_version: str | None = None
|
|
84
|
+
inputs: tuple[InputFile, ...]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class VerdictV2(BaseModel):
|
|
88
|
+
"""The verdict, version 2 (§32). Field for field version 1, plus `basis`, `run.fork` and
|
|
89
|
+
`run.solver_version`, with `verdict` in version 2's words."""
|
|
90
|
+
|
|
91
|
+
model_config = ConfigDict(frozen=True, populate_by_name=True)
|
|
92
|
+
|
|
93
|
+
schema_: Literal["courant.verdict/2"] = Field(default=SCHEMA_V2, alias="schema")
|
|
94
|
+
tool: ToolInfo
|
|
95
|
+
run: RunInfoV2
|
|
96
|
+
verdict: Decision
|
|
97
|
+
basis: Basis
|
|
98
|
+
rule: str
|
|
99
|
+
grade: Literal["A", "B", "C", "D"] | None
|
|
100
|
+
reasons: tuple[Reason, ...]
|
|
101
|
+
probable_causes: tuple[ProbableCause, ...]
|
|
102
|
+
not_assessed: tuple[str, ...]
|
|
103
|
+
next_action: str | None
|
|
104
|
+
stats: Stats
|
|
105
|
+
convergence: ConvergenceBlock | None = None
|
|
106
|
+
conformance: ConformanceBlock | None = None
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def accepted(self) -> bool:
|
|
110
|
+
return self.verdict == "accept"
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def exit_code(self) -> int:
|
|
114
|
+
return EXIT[self.verdict]
|
|
115
|
+
|
|
116
|
+
def to_json(self) -> str:
|
|
117
|
+
"""Canonical JSON (VER-9). An absent convergence or conformance block is left out, as in
|
|
118
|
+
version 1."""
|
|
119
|
+
data = self.model_dump(mode="json", by_alias=True)
|
|
120
|
+
for key in ("convergence", "conformance"):
|
|
121
|
+
if data.get(key) is None:
|
|
122
|
+
data.pop(key, None)
|
|
123
|
+
return canonical_json(data)
|
|
124
|
+
|
|
125
|
+
def to_v1(self) -> Verdict:
|
|
126
|
+
"""The same decision as `courant.verdict/1`, byte for byte what version 1 wrote."""
|
|
127
|
+
not_assessed = self.not_assessed
|
|
128
|
+
if self.basis == "validity" and not_assessed and not_assessed[-1] == sentences.NO_SPEC:
|
|
129
|
+
not_assessed = not_assessed[:-1]
|
|
130
|
+
reasons = tuple(r for r in self.reasons if r.kind != "insufficient")
|
|
131
|
+
return Verdict(
|
|
132
|
+
tool=self.tool,
|
|
133
|
+
run=RunInfo(id=self.run.id, source=self.run.source, solver=self.run.solver,
|
|
134
|
+
inputs=self.run.inputs),
|
|
135
|
+
verdict=TO_V1[self.verdict], rule=self.rule, grade=self.grade,
|
|
136
|
+
reasons=reasons, probable_causes=self.probable_causes,
|
|
137
|
+
not_assessed=not_assessed, next_action=self.next_action, stats=self.stats,
|
|
138
|
+
convergence=self.convergence, conformance=self.conformance)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
AnyVerdict = Verdict | VerdictV2
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def basis_of(conformance: ConformanceBlock | None, *, extracted: bool = False) -> str:
|
|
145
|
+
"""GATE-2. What the verdict was judged against, from its conformance block alone (so a
|
|
146
|
+
version 1 verdict maps without its inputs). `extracted`: the specification records an
|
|
147
|
+
extraction and no confirmation (SPEC-7). It labels; it does not decide: the policy was given
|
|
148
|
+
the same flag (VER-5.12, `policy.apply_conformance`)."""
|
|
149
|
+
if conformance is None:
|
|
150
|
+
return "validity"
|
|
151
|
+
if extracted:
|
|
152
|
+
return "validity+extracted-spec"
|
|
153
|
+
if conformance.locked_sha256 and conformance.locked_sha256 == conformance.spec_sha256:
|
|
154
|
+
return "validity+conformance"
|
|
155
|
+
return "validity+unlocked-spec"
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def extracted_unconfirmed(spec: Mapping | None) -> bool:
|
|
159
|
+
"""Whether a specification (as JSON data) says it was extracted and nobody confirmed it
|
|
160
|
+
(SPEC-7: `provenance.extracted_by` without `provenance.confirmed_by`)."""
|
|
161
|
+
prov = (spec or {}).get("provenance") or {}
|
|
162
|
+
return bool(prov.get("extracted_by")) and not prov.get("confirmed_by")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def insufficient_reason(rule: str, conformance: ConformanceBlock | None = None) -> Reason:
|
|
166
|
+
"""GATE-4. The one reason an `insufficient` verdict carries: a code from the closed table
|
|
167
|
+
in `sentences.INSUFFICIENT`, its fixed sentence, and (where the evidence is in the verdict)
|
|
168
|
+
the hashes or the items it rests on. A rule outside the table raises."""
|
|
169
|
+
entry = sentences.insufficient_for(rule)
|
|
170
|
+
threshold = value = None
|
|
171
|
+
if conformance is not None and entry.name == "spec_hash_mismatch":
|
|
172
|
+
threshold, value = conformance.locked_sha256, conformance.spec_sha256
|
|
173
|
+
elif conformance is not None and entry.name == "spec_value_unreadable":
|
|
174
|
+
value = ", ".join(i.name for i in conformance.items if i.conforms is None) or None
|
|
175
|
+
return Reason(code=entry.code, kind="insufficient", severity="major", summary=entry.sentence,
|
|
176
|
+
input=entry.input, method=entry.method, threshold=threshold, value=value)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def to_v2(v1: Verdict, *, extracted: bool = False, fork: str | None = None,
|
|
180
|
+
solver_version: str | None = None) -> VerdictV2:
|
|
181
|
+
"""GATE-1. The version 1 verdict in version 2: the one mapping. An `insufficient` verdict
|
|
182
|
+
gains the closed-vocabulary reason of GATE-4 first; `to_v1()` takes it off again."""
|
|
183
|
+
basis = basis_of(v1.conformance, extracted=extracted)
|
|
184
|
+
not_assessed = v1.not_assessed
|
|
185
|
+
if basis == "validity":
|
|
186
|
+
not_assessed = (*not_assessed, sentences.NO_SPEC)
|
|
187
|
+
reasons = v1.reasons
|
|
188
|
+
if v1.verdict == "NOT_ASSESSABLE":
|
|
189
|
+
# After the conformance reasons, which VER-6 sorts first, and before everything else.
|
|
190
|
+
lead = sum(1 for _ in itertools.takewhile(lambda r: r.kind == "conformance", reasons))
|
|
191
|
+
reasons = (*reasons[:lead], insufficient_reason(v1.rule, v1.conformance), *reasons[lead:])
|
|
192
|
+
return VerdictV2(
|
|
193
|
+
tool=v1.tool,
|
|
194
|
+
run=RunInfoV2(id=v1.run.id, source=v1.run.source, solver=v1.run.solver, fork=fork,
|
|
195
|
+
solver_version=solver_version, inputs=v1.run.inputs),
|
|
196
|
+
verdict=FROM_V1[v1.verdict], basis=basis, rule=v1.rule, grade=v1.grade,
|
|
197
|
+
reasons=reasons, probable_causes=v1.probable_causes, not_assessed=not_assessed,
|
|
198
|
+
next_action=v1.next_action, stats=v1.stats, convergence=v1.convergence,
|
|
199
|
+
conformance=v1.conformance)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def as_v1(v: AnyVerdict) -> Verdict:
|
|
203
|
+
return v if isinstance(v, Verdict) else v.to_v1()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def as_v2(v: AnyVerdict) -> VerdictV2:
|
|
207
|
+
return v if isinstance(v, VerdictV2) else to_v2(v)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def in_schema(v: AnyVerdict, schema: int) -> AnyVerdict:
|
|
211
|
+
"""The verdict as the writer of `schema` (1 or 2) emits it (ARC-16)."""
|
|
212
|
+
if schema not in SCHEMAS:
|
|
213
|
+
raise ValueError(f"unknown verdict schema {schema}: use 1 or 2")
|
|
214
|
+
return as_v1(v) if schema == 1 else as_v2(v)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def load_verdict(data: str | bytes | Mapping) -> VerdictV2:
|
|
218
|
+
"""Read a verdict of either major (ARC-16). A version 1 verdict comes back as version 2
|
|
219
|
+
through `to_v2`; its `to_v1()` gives the original back."""
|
|
220
|
+
if isinstance(data, (str, bytes)):
|
|
221
|
+
data = json.loads(data)
|
|
222
|
+
schema = data.get("schema")
|
|
223
|
+
if schema == SCHEMA_V2:
|
|
224
|
+
return VerdictV2.model_validate(data)
|
|
225
|
+
if schema == SCHEMA_V1:
|
|
226
|
+
return to_v2(Verdict.model_validate(data))
|
|
227
|
+
raise ValueError(f"not a Courant verdict: schema {schema!r}")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
#: Version 1's model, under the name readers of both majors use.
|
|
231
|
+
VerdictV1 = Verdict
|
|
232
|
+
|
|
233
|
+
__all__ = ["EXIT", "FROM_V1", "SCHEMAS", "SCHEMA_V1", "SCHEMA_V2", "TO_V1", "AnyVerdict", "Basis",
|
|
234
|
+
"Decision", "RunInfoV2", "VerdictV1", "VerdictV2", "VerdictValue", "as_v1", "as_v2",
|
|
235
|
+
"basis_of", "extracted_unconfirmed", "in_schema", "load_verdict", "to_v2"]
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""The Watcher — raw solver output -> structured Events + anomaly detection."""
|
|
2
|
+
|
|
3
|
+
from courant.watcher.anomaly import AnomalyConfig, AnomalyDetector
|
|
4
|
+
from courant.watcher.parser import LogParser, parse_log_file
|
|
5
|
+
from courant.watcher.watcher import Watcher
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"LogParser",
|
|
9
|
+
"parse_log_file",
|
|
10
|
+
"AnomalyDetector",
|
|
11
|
+
"AnomalyConfig",
|
|
12
|
+
"Watcher",
|
|
13
|
+
]
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Anomaly detection over residual history — rules, not ML (Tech Architecture §8.1).
|
|
2
|
+
|
|
3
|
+
The parser turns lines into facts. This layer watches the *history* of those facts
|
|
4
|
+
and raises typed anomaly Events the orchestrator transitions on:
|
|
5
|
+
|
|
6
|
+
* soft DIVERGENCE — the representative residual is climbing over a window of
|
|
7
|
+
iterations (caught *before* it reaches NaN/Inf, which the parser catches).
|
|
8
|
+
* residual-plateau STALL — the residual has stopped improving while still above
|
|
9
|
+
a convergence target (a silent non-convergence).
|
|
10
|
+
* wall-clock STALL — no solver progress for too long (driven by the sandbox's
|
|
11
|
+
wall timer via ``check_wall_stall``).
|
|
12
|
+
|
|
13
|
+
Every threshold is explicit and configurable. Episodes are debounced so a single
|
|
14
|
+
sustained anomaly raises a single Event, not one per iteration.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import math
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
from courant.events import (
|
|
25
|
+
DivergencePayload,
|
|
26
|
+
Event,
|
|
27
|
+
EventKind,
|
|
28
|
+
ResidualPayload,
|
|
29
|
+
Severity,
|
|
30
|
+
StallPayload,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
#: Volume-fraction fields, whose residual tracks interface motion rather than
|
|
35
|
+
#: convergence. `alpha.water`, `alpha.air`, `alpha.mercury`, and the `alphas`
|
|
36
|
+
#: sum multiphaseInterFoam prints.
|
|
37
|
+
def _is_phase_fraction(field: str) -> bool:
|
|
38
|
+
lowered = field.lower()
|
|
39
|
+
return lowered.startswith("alpha.") or lowered == "alphas"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class AnomalyConfig:
|
|
44
|
+
# --- soft divergence ---
|
|
45
|
+
slope_window: int = 5 # steps used to fit the residual trend
|
|
46
|
+
divergence_slope: float = 0.15 # log10(residual) growth/step to flag (≈ +40%/step)
|
|
47
|
+
#: Residuals already below this are not diverging, whatever their slope.
|
|
48
|
+
#:
|
|
49
|
+
#: Without this floor a *converged* solve is reported as diverged. A real
|
|
50
|
+
#: cavity case finished with residuals fluctuating between 7.9e-07 and
|
|
51
|
+
#: 1.03e-06 — a 30% wiggle in a noise floor six orders of magnitude below
|
|
52
|
+
#: any tolerance — which fits a slope of 0.20/step and fired DIVERGENCE with
|
|
53
|
+
#: `is_nan=False, is_inf=False`. The run had printed "End", exited 0, and
|
|
54
|
+
#: reached a continuity error of 3e-17.
|
|
55
|
+
#:
|
|
56
|
+
#: The consequence was not cosmetic: `classify_status` turns a DIVERGENCE
|
|
57
|
+
#: event into `RunStatus.DIVERGED`, so the fix loop saw every successful
|
|
58
|
+
#: re-run as a failure and could never report a fix as working. The
|
|
59
|
+
#: plateau check below has always had this guard; divergence did not.
|
|
60
|
+
#:
|
|
61
|
+
#: Hard divergence (NaN/Inf) is detected in the parser and is unaffected —
|
|
62
|
+
#: that must fire at any magnitude.
|
|
63
|
+
divergence_floor: float = 1e-3
|
|
64
|
+
# --- residual plateau ---
|
|
65
|
+
plateau_window: int = 50 # steps of no improvement to flag a stall
|
|
66
|
+
plateau_rel_improve: float = 0.10 # <10% improvement over the window == flat
|
|
67
|
+
convergence_target: float = 1e-3 # only a stall if still above this residual
|
|
68
|
+
# --- wall-clock stall ---
|
|
69
|
+
wall_stall_seconds: float = 120.0
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class _History:
|
|
74
|
+
reps: list[float] = field(default_factory=list) # representative residual/step
|
|
75
|
+
fields: list[str] = field(default_factory=list) # worst field/step
|
|
76
|
+
iters: list[int] = field(default_factory=list) # x-axis for slope fit
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class AnomalyDetector:
|
|
80
|
+
"""Stateful consumer of RESIDUAL events. One instance per run.
|
|
81
|
+
|
|
82
|
+
Feed it events with :meth:`observe`; poll :meth:`check_wall_stall` from the
|
|
83
|
+
sandbox timer. Both return lists of anomaly Events ready to publish.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def __init__(self, run_id: str, config: AnomalyConfig | None = None,
|
|
87
|
+
start_seq: int = 10_000):
|
|
88
|
+
self.run_id = run_id
|
|
89
|
+
self.cfg = config or AnomalyConfig()
|
|
90
|
+
self._seq = start_seq # separate seq band from the parser
|
|
91
|
+
self._h = _History()
|
|
92
|
+
self._last_progress_wall: float | None = None
|
|
93
|
+
self._diverging = False # debounce flags
|
|
94
|
+
self._plateaued = False
|
|
95
|
+
self._wall_stalled = False
|
|
96
|
+
|
|
97
|
+
# -- public API ---------------------------------------------------------
|
|
98
|
+
|
|
99
|
+
def observe(self, event: Event) -> list[Event]:
|
|
100
|
+
if event.kind is not EventKind.RESIDUAL:
|
|
101
|
+
return []
|
|
102
|
+
payload: ResidualPayload = event.payload
|
|
103
|
+
rep, worst = self._representative(payload)
|
|
104
|
+
if rep is None:
|
|
105
|
+
return []
|
|
106
|
+
self._last_progress_wall = event.ts_wall
|
|
107
|
+
idx = payload.iteration if payload.iteration is not None else len(self._h.reps)
|
|
108
|
+
self._h.reps.append(rep)
|
|
109
|
+
self._h.fields.append(worst)
|
|
110
|
+
self._h.iters.append(idx)
|
|
111
|
+
|
|
112
|
+
out: list[Event] = []
|
|
113
|
+
out.extend(self._check_divergence(event))
|
|
114
|
+
out.extend(self._check_plateau(event))
|
|
115
|
+
return out
|
|
116
|
+
|
|
117
|
+
def check_wall_stall(self, now: float) -> list[Event]:
|
|
118
|
+
"""Poll from the sandbox wall timer. Emits at most one wall STALL/episode."""
|
|
119
|
+
if self._last_progress_wall is None:
|
|
120
|
+
return []
|
|
121
|
+
idle = now - self._last_progress_wall
|
|
122
|
+
if idle >= self.cfg.wall_stall_seconds and not self._wall_stalled:
|
|
123
|
+
self._wall_stalled = True
|
|
124
|
+
return [
|
|
125
|
+
self._emit(
|
|
126
|
+
EventKind.STALL,
|
|
127
|
+
StallPayload(reason="wall_clock", idle_seconds=idle),
|
|
128
|
+
Severity.WARN,
|
|
129
|
+
)
|
|
130
|
+
]
|
|
131
|
+
if idle < self.cfg.wall_stall_seconds:
|
|
132
|
+
self._wall_stalled = False
|
|
133
|
+
return []
|
|
134
|
+
|
|
135
|
+
# -- internals ----------------------------------------------------------
|
|
136
|
+
|
|
137
|
+
@staticmethod
|
|
138
|
+
def _representative(p: ResidualPayload) -> tuple[float | None, str | None]:
|
|
139
|
+
"""Worst (largest, positive, finite) initial residual and its field.
|
|
140
|
+
|
|
141
|
+
**Phase fractions are excluded**, and the reason is physical rather than
|
|
142
|
+
a tuning convenience. `alpha.water` is bounded in [0, 1] by construction
|
|
143
|
+
— MULES enforces it every step — so it cannot run away, and its residual
|
|
144
|
+
does not measure convergence at all: it measures how fast the interface
|
|
145
|
+
is *moving*. On `interFoam/damBreak` the interface accelerates down a
|
|
146
|
+
collapsing column of water, which is the entire point of the case, and
|
|
147
|
+
the residual rises accordingly.
|
|
148
|
+
|
|
149
|
+
Fitting a divergence slope to that reported DIVERGENCE on an unmodified
|
|
150
|
+
tutorial — with `is_nan=False`, `is_inf=False`, and a residual of
|
|
151
|
+
1.3e-03 — which `classify_status` then turns into `RunStatus.DIVERGED`.
|
|
152
|
+
A healthy multiphase case would have been declared a failed run.
|
|
153
|
+
|
|
154
|
+
It only became reachable once the parser learned to read dotted field
|
|
155
|
+
names at all; before that `alpha.water` was invisible and the question
|
|
156
|
+
never arose. Two bugs deep in the same log.
|
|
157
|
+
"""
|
|
158
|
+
best_val: float | None = None
|
|
159
|
+
best_field: str | None = None
|
|
160
|
+
for name, val in p.initial_residuals.items():
|
|
161
|
+
if val is None or val <= 0 or math.isnan(val) or math.isinf(val):
|
|
162
|
+
continue
|
|
163
|
+
if _is_phase_fraction(name):
|
|
164
|
+
continue
|
|
165
|
+
if best_val is None or val > best_val:
|
|
166
|
+
best_val, best_field = val, name
|
|
167
|
+
return best_val, best_field
|
|
168
|
+
|
|
169
|
+
def _check_divergence(self, event: Event) -> list[Event]:
|
|
170
|
+
w = self.cfg.slope_window
|
|
171
|
+
if len(self._h.reps) < w:
|
|
172
|
+
return []
|
|
173
|
+
ys = np.log10(np.asarray(self._h.reps[-w:]))
|
|
174
|
+
xs = np.asarray(self._h.iters[-w:], dtype=float)
|
|
175
|
+
# guard against a degenerate x-axis
|
|
176
|
+
if np.ptp(xs) == 0:
|
|
177
|
+
xs = np.arange(w, dtype=float)
|
|
178
|
+
slope = float(np.polyfit(xs, ys, 1)[0])
|
|
179
|
+
|
|
180
|
+
# A residual already inside the convergence tolerance is not diverging,
|
|
181
|
+
# however steeply it wiggles. See `divergence_floor`.
|
|
182
|
+
if self._h.reps[-1] <= self.cfg.divergence_floor:
|
|
183
|
+
self._diverging = False
|
|
184
|
+
return []
|
|
185
|
+
|
|
186
|
+
if slope >= self.cfg.divergence_slope:
|
|
187
|
+
if not self._diverging:
|
|
188
|
+
self._diverging = True
|
|
189
|
+
return [
|
|
190
|
+
self._emit(
|
|
191
|
+
EventKind.DIVERGENCE,
|
|
192
|
+
DivergencePayload(
|
|
193
|
+
field=self._h.fields[-1],
|
|
194
|
+
residual=self._h.reps[-1],
|
|
195
|
+
slope=slope,
|
|
196
|
+
),
|
|
197
|
+
Severity.ERROR,
|
|
198
|
+
)
|
|
199
|
+
]
|
|
200
|
+
else:
|
|
201
|
+
self._diverging = False
|
|
202
|
+
return []
|
|
203
|
+
|
|
204
|
+
def _check_plateau(self, event: Event) -> list[Event]:
|
|
205
|
+
w = self.cfg.plateau_window
|
|
206
|
+
if len(self._h.reps) < w:
|
|
207
|
+
return []
|
|
208
|
+
window = self._h.reps[-w:]
|
|
209
|
+
rep_now = window[-1]
|
|
210
|
+
# still converged? no stall.
|
|
211
|
+
if rep_now <= self.cfg.convergence_target:
|
|
212
|
+
self._plateaued = False
|
|
213
|
+
return []
|
|
214
|
+
best, worst = min(window), max(window)
|
|
215
|
+
# relative improvement across the window
|
|
216
|
+
improve = (worst - best) / worst if worst > 0 else 0.0
|
|
217
|
+
if improve < self.cfg.plateau_rel_improve:
|
|
218
|
+
if not self._plateaued:
|
|
219
|
+
self._plateaued = True
|
|
220
|
+
return [
|
|
221
|
+
self._emit(
|
|
222
|
+
EventKind.STALL,
|
|
223
|
+
StallPayload(
|
|
224
|
+
reason="residual_plateau",
|
|
225
|
+
plateau_iterations=w,
|
|
226
|
+
field=self._h.fields[-1],
|
|
227
|
+
),
|
|
228
|
+
Severity.WARN,
|
|
229
|
+
)
|
|
230
|
+
]
|
|
231
|
+
else:
|
|
232
|
+
self._plateaued = False
|
|
233
|
+
return []
|
|
234
|
+
|
|
235
|
+
def _emit(self, kind: EventKind, payload, severity: Severity) -> Event:
|
|
236
|
+
ev = Event(
|
|
237
|
+
run_id=self.run_id,
|
|
238
|
+
seq=self._seq,
|
|
239
|
+
kind=kind,
|
|
240
|
+
severity=severity,
|
|
241
|
+
payload=payload,
|
|
242
|
+
)
|
|
243
|
+
self._seq += 1
|
|
244
|
+
return ev
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Whether a run finished, read from its log (one definition, TRD VER-3).
|
|
2
|
+
|
|
3
|
+
OpenFOAM prints a bare `End` as the last line of a solver that ran to
|
|
4
|
+
completion. Everything else exited abnormally.
|
|
5
|
+
|
|
6
|
+
This was a private helper in the replay tier. The verifier needs the same
|
|
7
|
+
answer, and two copies of one fact is the bug class this codebase has fixed
|
|
8
|
+
seven times, so it lives here and both import it.
|
|
9
|
+
|
|
10
|
+
A converged steady run, a plateau that ran to its iteration limit, and a
|
|
11
|
+
transient run that reached its end time all print `End`. Calling a plateau a
|
|
12
|
+
crash made `crash.*` signatures reachable and pushed `BC.REVERSED_OUTFLOW`
|
|
13
|
+
into two diagnoses the real pipeline gets right.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
_END_MARKER = "\nEnd\n"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def infer_exit_code(log_text: str) -> int:
|
|
22
|
+
"""0 if the log shows a completed solver run, else 1."""
|
|
23
|
+
return 0 if log_text.rstrip().endswith("End") or _END_MARKER in log_text else 1
|