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
courant/events/core.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""The Event contract — the system's spine (Master Tech Architecture §3.2).
|
|
2
|
+
|
|
3
|
+
Every component speaks Events. An Event is immutable, typed, and carries enough
|
|
4
|
+
structured context to be replayed. Design rule: an Event NEVER contains free-form
|
|
5
|
+
prose the system later parses — structured fields only. The raw log stays in
|
|
6
|
+
object storage, referenced by ``log_offset`` so any diagnosis can be traced to
|
|
7
|
+
exact log bytes.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import time
|
|
13
|
+
from enum import Enum
|
|
14
|
+
from typing import Annotated, Literal, Union
|
|
15
|
+
|
|
16
|
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class EventKind(str, Enum):
|
|
20
|
+
"""The finite set of event kinds flowing through the system."""
|
|
21
|
+
|
|
22
|
+
RESIDUAL = "RESIDUAL" # per-timestep residuals / Courant / continuity
|
|
23
|
+
CHECKPOINT = "CHECKPOINT" # solver wrote a restartable time directory
|
|
24
|
+
WARN = "WARN" # bounding / clipping / non-fatal solver warning
|
|
25
|
+
STALL = "STALL" # no progress: wall-clock stall or frozen residuals
|
|
26
|
+
DIVERGENCE = "DIVERGENCE" # residuals exploding toward NaN/Inf
|
|
27
|
+
CRASH = "CRASH" # solver exited non-zero
|
|
28
|
+
INTERVENE = "INTERVENE" # orchestrator intervened (raised diagnose)
|
|
29
|
+
FIX = "FIX" # a fix diff was applied
|
|
30
|
+
VERIFY = "VERIFY" # a verification/trust-grade result
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Severity(str, Enum):
|
|
34
|
+
INFO = "info"
|
|
35
|
+
WARN = "warn"
|
|
36
|
+
ERROR = "error"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# ---------------------------------------------------------------------------
|
|
40
|
+
# Kind-specific payloads (structured fields only)
|
|
41
|
+
# ---------------------------------------------------------------------------
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ContinuityErrors(BaseModel):
|
|
45
|
+
"""OpenFOAM 'time step continuity errors' line."""
|
|
46
|
+
|
|
47
|
+
model_config = ConfigDict(frozen=True, populate_by_name=True)
|
|
48
|
+
|
|
49
|
+
sum_local: float | None = None
|
|
50
|
+
global_: float | None = Field(default=None, alias="global")
|
|
51
|
+
cumulative: float | None = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ResidualPayload(BaseModel):
|
|
55
|
+
"""One solver time-step / outer-iteration: residuals for every solved field,
|
|
56
|
+
plus Courant number, continuity errors, and timing."""
|
|
57
|
+
|
|
58
|
+
model_config = ConfigDict(frozen=True)
|
|
59
|
+
kind: Literal[EventKind.RESIDUAL] = EventKind.RESIDUAL
|
|
60
|
+
|
|
61
|
+
time: float | None = None # simulation time
|
|
62
|
+
iteration: int | None = None # global step index
|
|
63
|
+
initial_residuals: dict[str, float] = Field(default_factory=dict)
|
|
64
|
+
final_residuals: dict[str, float] = Field(default_factory=dict)
|
|
65
|
+
solver_iterations: dict[str, int] = Field(default_factory=dict)
|
|
66
|
+
courant_mean: float | None = None
|
|
67
|
+
courant_max: float | None = None
|
|
68
|
+
continuity: ContinuityErrors | None = None
|
|
69
|
+
delta_t: float | None = None
|
|
70
|
+
exec_time: float | None = None # cumulative CPU seconds
|
|
71
|
+
clock_time: float | None = None # cumulative wall seconds
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class CheckpointPayload(BaseModel):
|
|
75
|
+
model_config = ConfigDict(frozen=True)
|
|
76
|
+
kind: Literal[EventKind.CHECKPOINT] = EventKind.CHECKPOINT
|
|
77
|
+
|
|
78
|
+
time_dir: str # e.g. "0.5" — restartable dir
|
|
79
|
+
time: float | None = None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class WarnPayload(BaseModel):
|
|
83
|
+
model_config = ConfigDict(frozen=True)
|
|
84
|
+
kind: Literal[EventKind.WARN] = EventKind.WARN
|
|
85
|
+
|
|
86
|
+
category: str # e.g. "bounding", "clipping"
|
|
87
|
+
field: str | None = None # field being bounded, if any
|
|
88
|
+
count: int = 1 # occurrences aggregated
|
|
89
|
+
detail: str | None = None # short structured tag, not prose
|
|
90
|
+
#: For a bounding event: what OpenFOAM printed. A clip whose minimum is 0, or a few
|
|
91
|
+
#: parts in a million below it, is a floor touched rather than a field going negative.
|
|
92
|
+
minimum: float | None = None
|
|
93
|
+
maximum: float | None = None
|
|
94
|
+
average: float | None = None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class StallPayload(BaseModel):
|
|
98
|
+
model_config = ConfigDict(frozen=True)
|
|
99
|
+
kind: Literal[EventKind.STALL] = EventKind.STALL
|
|
100
|
+
|
|
101
|
+
reason: Literal["wall_clock", "residual_plateau", "no_output"]
|
|
102
|
+
idle_seconds: float | None = None # wall stall duration
|
|
103
|
+
plateau_iterations: int | None = None # residual flat for N iters
|
|
104
|
+
field: str | None = None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class DivergencePayload(BaseModel):
|
|
108
|
+
model_config = ConfigDict(frozen=True)
|
|
109
|
+
kind: Literal[EventKind.DIVERGENCE] = EventKind.DIVERGENCE
|
|
110
|
+
|
|
111
|
+
field: str | None = None # field that diverged
|
|
112
|
+
residual: float | None = None # value at detection
|
|
113
|
+
is_nan: bool = False
|
|
114
|
+
is_inf: bool = False
|
|
115
|
+
slope: float | None = None # residual growth slope (log10/iter)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class CrashPayload(BaseModel):
|
|
119
|
+
model_config = ConfigDict(frozen=True)
|
|
120
|
+
kind: Literal[EventKind.CRASH] = EventKind.CRASH
|
|
121
|
+
|
|
122
|
+
return_code: int | None = None
|
|
123
|
+
signal: str | None = None # e.g. "SIGFPE"
|
|
124
|
+
foam_fatal: bool = False # OpenFOAM 'FOAM FATAL ERROR'
|
|
125
|
+
tag: str | None = None # short error class, not prose
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class IntervenePayload(BaseModel):
|
|
129
|
+
model_config = ConfigDict(frozen=True)
|
|
130
|
+
kind: Literal[EventKind.INTERVENE] = EventKind.INTERVENE
|
|
131
|
+
|
|
132
|
+
trigger: str # which anomaly triggered diagnose
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class FixPayload(BaseModel):
|
|
136
|
+
model_config = ConfigDict(frozen=True)
|
|
137
|
+
kind: Literal[EventKind.FIX] = EventKind.FIX
|
|
138
|
+
|
|
139
|
+
diagnosis_id: str | None = None
|
|
140
|
+
escalation_tier: Literal["numerics", "schemes", "mesh"] | None = None
|
|
141
|
+
applied: bool = False
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class VerifyPayload(BaseModel):
|
|
145
|
+
model_config = ConfigDict(frozen=True)
|
|
146
|
+
kind: Literal[EventKind.VERIFY] = EventKind.VERIFY
|
|
147
|
+
|
|
148
|
+
grade: Literal["A", "B", "C", "D"] | None = None
|
|
149
|
+
check_code: str | None = None
|
|
150
|
+
passed: bool | None = None
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
Payload = Annotated[
|
|
154
|
+
Union[
|
|
155
|
+
ResidualPayload,
|
|
156
|
+
CheckpointPayload,
|
|
157
|
+
WarnPayload,
|
|
158
|
+
StallPayload,
|
|
159
|
+
DivergencePayload,
|
|
160
|
+
CrashPayload,
|
|
161
|
+
IntervenePayload,
|
|
162
|
+
FixPayload,
|
|
163
|
+
VerifyPayload,
|
|
164
|
+
],
|
|
165
|
+
Field(discriminator="kind"),
|
|
166
|
+
]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# ---------------------------------------------------------------------------
|
|
170
|
+
# The Event
|
|
171
|
+
# ---------------------------------------------------------------------------
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class Event(BaseModel):
|
|
175
|
+
"""An immutable, typed, replayable unit of what happened in a run."""
|
|
176
|
+
|
|
177
|
+
model_config = ConfigDict(frozen=True)
|
|
178
|
+
|
|
179
|
+
run_id: str
|
|
180
|
+
seq: int # monotonic order within a run
|
|
181
|
+
kind: EventKind
|
|
182
|
+
severity: Severity = Severity.INFO
|
|
183
|
+
payload: Payload
|
|
184
|
+
ts_sim: float | None = None # simulation time, if applicable
|
|
185
|
+
ts_wall: float = Field(default_factory=time.time) # unix wall clock
|
|
186
|
+
log_offset: int | None = None # byte offset into raw log
|
|
187
|
+
|
|
188
|
+
@model_validator(mode="after")
|
|
189
|
+
def _kind_matches_payload(self) -> "Event":
|
|
190
|
+
if self.payload.kind != self.kind:
|
|
191
|
+
raise ValueError(
|
|
192
|
+
f"Event.kind={self.kind} does not match payload.kind={self.payload.kind}"
|
|
193
|
+
)
|
|
194
|
+
return self
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""One definition of "diverged" (TRD ADP-5).
|
|
2
|
+
|
|
3
|
+
A run diverged when a residual went non-finite: a solver line printed an initial or final
|
|
4
|
+
residual of NaN or Inf, which the log parser turns into a DIVERGENCE event with `is_nan` or
|
|
5
|
+
`is_inf` set (`courant.watcher.parser`). That is the whole definition, and this module is the only
|
|
6
|
+
place it is written. The certification sandbox's run status (`classify_status`, which the
|
|
7
|
+
certification harness reports), the verifier's rule VER-5.2 and
|
|
8
|
+
its `run.divergence` reasons and counts, the replay judge, the stability check and the
|
|
9
|
+
diagnosis all ask it.
|
|
10
|
+
|
|
11
|
+
The anomaly detector's soft DIVERGENCE (`courant.watcher.anomaly`: the representative residual
|
|
12
|
+
climbing over a five-step window, `slope` set, every value finite) is a live early warning,
|
|
13
|
+
not a divergence. Here it is called a residual climb. RRD RM-18 v1 found what two definitions
|
|
14
|
+
cost: on `pisoFoam/RAS/cavity` with the lid speed doubled and with nu tripled, the detector
|
|
15
|
+
fired on the startup transient (100 steps, no NaN, final residual 8e-3, Co 0.5), the sandbox
|
|
16
|
+
reported the run `diverged`, and `courant verify` on the same log, whose parser emits no such
|
|
17
|
+
event, returned TRUSTWORTHY. A climbing residual that matters reaches a verdict through the
|
|
18
|
+
residual and convergence checks, which judge the whole run and not five steps of it.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from collections.abc import Iterable, Mapping
|
|
24
|
+
|
|
25
|
+
from courant.events.core import Event, EventKind
|
|
26
|
+
|
|
27
|
+
__all__ = ["diverged", "divergences", "is_divergence", "is_residual_climb", "non_finite"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def non_finite(payload) -> bool:
|
|
31
|
+
"""Whether a DIVERGENCE payload records a NaN or infinite residual. Takes the payload
|
|
32
|
+
model, or its serialised form (`Event.model_dump`, as the live stream carries it)."""
|
|
33
|
+
if isinstance(payload, Mapping):
|
|
34
|
+
return bool(payload.get("is_nan") or payload.get("is_inf"))
|
|
35
|
+
return bool(getattr(payload, "is_nan", False) or getattr(payload, "is_inf", False))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def is_divergence(event: Event) -> bool:
|
|
39
|
+
"""A residual went non-finite: the one event that makes a run diverged."""
|
|
40
|
+
return event.kind is EventKind.DIVERGENCE and non_finite(event.payload)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def is_residual_climb(event: Event) -> bool:
|
|
44
|
+
"""The anomaly detector's soft DIVERGENCE: a finite residual climbing. Not a divergence."""
|
|
45
|
+
return event.kind is EventKind.DIVERGENCE and not non_finite(event.payload)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def divergences(events: Iterable[Event]) -> list[Event]:
|
|
49
|
+
"""The events that make a run diverged, in order."""
|
|
50
|
+
return [e for e in events if is_divergence(e)]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def diverged(events: Iterable[Event]) -> bool:
|
|
54
|
+
"""Whether the run diverged: some residual went NaN or infinite."""
|
|
55
|
+
return any(is_divergence(e) for e in events)
|
courant/gate/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The CI gate (TRD GATE-7, GATE-8): the logic behind `courant gate` and the GitHub Action."""
|
courant/gate/config.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""`courant.toml`: what a repository tells the gate (TRD GATE-8).
|
|
2
|
+
|
|
3
|
+
fail-on = "not-accept" # or "reject": an insufficient run then passes (GATE-7)
|
|
4
|
+
pack-store = "evidence" # a path inside the repository; the packs are copied there
|
|
5
|
+
courant-version = "0.4.0" # optional: the gate refuses to run under another version
|
|
6
|
+
rules = [] # reserved for an organisation's rules files (OVR-3, Phase 3)
|
|
7
|
+
|
|
8
|
+
[[run]]
|
|
9
|
+
paths = ["runs/*"] # case globs, relative to the repository root
|
|
10
|
+
outputs = "solver-output" # optional: where each run's log and results are
|
|
11
|
+
spec = "specs/task.json" # optional: the task specification the run was asked to meet
|
|
12
|
+
spec-sha256 = "9f2c..." # required with `spec`: the hash it was locked at
|
|
13
|
+
|
|
14
|
+
An unknown key is an error that names it and says what is allowed: never a silent default (a
|
|
15
|
+
misspelt `fail-on` that quietly became `not-accept` would be a check that does not say what the
|
|
16
|
+
repository thinks it says). The same settings come in as the Action's inputs and the `courant
|
|
17
|
+
gate` flags, as one more `[[run]]` group and as overrides of the top-level keys.
|
|
18
|
+
|
|
19
|
+
`outputs` is where the verifier reads. A run named by `paths` is looked up there by its name
|
|
20
|
+
(`outputs/<name>/`, `outputs/<name>.log` or `outputs/<name>.log.gz`, a sidecar `<name>.case.json`
|
|
21
|
+
beside it), because repositories rarely commit solver output: it is an artefact of an earlier
|
|
22
|
+
job, an LFS path or a mounted volume. A run with no output there fails the check whatever
|
|
23
|
+
`fail-on` says.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import re
|
|
29
|
+
import tomllib
|
|
30
|
+
from dataclasses import dataclass
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
from courant.verify.outcome import FAIL_ON
|
|
34
|
+
|
|
35
|
+
TOP_KEYS = ("fail-on", "pack-store", "courant-version", "rules", "run")
|
|
36
|
+
RUN_KEYS = ("paths", "outputs", "spec", "spec-sha256")
|
|
37
|
+
_HEX64 = re.compile(r"^[0-9a-f]{64}$")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ConfigError(ValueError):
|
|
41
|
+
"""`courant.toml` (or an Action input) cannot be used. The gate ends with exit 4."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class RunGroup:
|
|
46
|
+
paths: tuple[str, ...]
|
|
47
|
+
outputs: tuple[str, ...] = ()
|
|
48
|
+
spec: str | None = None
|
|
49
|
+
spec_sha256: str | None = None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class GateConfig:
|
|
54
|
+
runs: tuple[RunGroup, ...] = ()
|
|
55
|
+
fail_on: str = "not-accept"
|
|
56
|
+
pack_store: str | None = None
|
|
57
|
+
courant_version: str | None = None
|
|
58
|
+
rules: tuple[str, ...] = ()
|
|
59
|
+
source: str = "(inputs)"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _strs(value, where: str) -> tuple[str, ...]:
|
|
63
|
+
if isinstance(value, str):
|
|
64
|
+
value = [value]
|
|
65
|
+
if not isinstance(value, list) or not all(isinstance(v, str) and v for v in value):
|
|
66
|
+
raise ConfigError(f"{where} must be a string or a list of strings")
|
|
67
|
+
return tuple(value)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _unknown(table: dict, allowed: tuple[str, ...], where: str, source: str) -> None:
|
|
71
|
+
bad = sorted(set(table) - set(allowed))
|
|
72
|
+
if bad:
|
|
73
|
+
raise ConfigError(f"{source}: unknown key {', '.join(repr(k) for k in bad)} in {where} "
|
|
74
|
+
f"(allowed: {', '.join(allowed)})")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _group(table: dict, where: str, source: str) -> RunGroup:
|
|
78
|
+
_unknown(table, RUN_KEYS, where, source)
|
|
79
|
+
if "paths" not in table:
|
|
80
|
+
raise ConfigError(f"{source}: {where} has no 'paths'")
|
|
81
|
+
spec = table.get("spec")
|
|
82
|
+
sha = table.get("spec-sha256")
|
|
83
|
+
if spec is not None and not isinstance(spec, str):
|
|
84
|
+
raise ConfigError(f"{source}: {where}: spec must be a path")
|
|
85
|
+
if sha is not None and not isinstance(sha, str):
|
|
86
|
+
raise ConfigError(f"{source}: {where}: spec-sha256 must be a string")
|
|
87
|
+
return make_group(_strs(table["paths"], f"{source}: {where}.paths"),
|
|
88
|
+
_strs(table["outputs"], f"{source}: {where}.outputs") if "outputs" in table else (),
|
|
89
|
+
spec, sha, where=f"{source}: {where}")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def make_group(paths, outputs=(), spec: str | None = None, spec_sha256: str | None = None,
|
|
93
|
+
*, where: str = "inputs") -> RunGroup:
|
|
94
|
+
if spec and not spec_sha256:
|
|
95
|
+
raise ConfigError(f"{where}: 'spec' needs 'spec-sha256', the hash the specification was "
|
|
96
|
+
"locked at before the run; without it nothing stops the specification "
|
|
97
|
+
"from being edited until the run fits it")
|
|
98
|
+
if spec_sha256 and not spec:
|
|
99
|
+
raise ConfigError(f"{where}: 'spec-sha256' without 'spec'")
|
|
100
|
+
if spec_sha256 and not _HEX64.match(spec_sha256.strip().lower()):
|
|
101
|
+
raise ConfigError(f"{where}: spec-sha256 must be 64 hexadecimal digits")
|
|
102
|
+
return RunGroup(tuple(paths), tuple(outputs), spec,
|
|
103
|
+
spec_sha256.strip().lower() if spec_sha256 else None)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def check_fail_on(value: str, source: str = "fail-on") -> str:
|
|
107
|
+
if value not in FAIL_ON:
|
|
108
|
+
raise ConfigError(f"{source}: fail-on must be one of {', '.join(FAIL_ON)}, not {value!r}")
|
|
109
|
+
return value
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def load_config(path: str | Path) -> GateConfig:
|
|
113
|
+
"""Read `courant.toml`. A missing file is an error; ask `exists` first when it is optional."""
|
|
114
|
+
path = Path(path)
|
|
115
|
+
source = path.name
|
|
116
|
+
try:
|
|
117
|
+
table = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
118
|
+
except OSError as exc:
|
|
119
|
+
raise ConfigError(f"cannot read {path}: {exc.strerror or exc}") from exc
|
|
120
|
+
except tomllib.TOMLDecodeError as exc:
|
|
121
|
+
raise ConfigError(f"{source} is not valid TOML: {exc}") from exc
|
|
122
|
+
_unknown(table, TOP_KEYS, "the top level", source)
|
|
123
|
+
runs = table.get("run", [])
|
|
124
|
+
if not isinstance(runs, list) or not all(isinstance(r, dict) for r in runs):
|
|
125
|
+
raise ConfigError(f"{source}: 'run' must be an array of tables, [[run]]")
|
|
126
|
+
fail_on = table.get("fail-on", "not-accept")
|
|
127
|
+
if not isinstance(fail_on, str):
|
|
128
|
+
raise ConfigError(f"{source}: fail-on must be a string")
|
|
129
|
+
check_fail_on(fail_on, f"{source}: fail-on")
|
|
130
|
+
store = table.get("pack-store")
|
|
131
|
+
if store is not None and not isinstance(store, str):
|
|
132
|
+
raise ConfigError(f"{source}: pack-store must be a path")
|
|
133
|
+
version = table.get("courant-version")
|
|
134
|
+
if version is not None and not isinstance(version, str):
|
|
135
|
+
raise ConfigError(f"{source}: courant-version must be a string")
|
|
136
|
+
rules = _strs(table["rules"], f"{source}: rules") if "rules" in table else ()
|
|
137
|
+
return GateConfig(
|
|
138
|
+
runs=tuple(_group(r, f"[[run]] #{i + 1}", source) for i, r in enumerate(runs)),
|
|
139
|
+
fail_on=fail_on, pack_store=store, courant_version=version, rules=rules, source=source)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def merged(base: GateConfig, *, group: RunGroup | None = None, fail_on: str | None = None,
|
|
143
|
+
pack_store: str | None = None, courant_version: str | None = None) -> GateConfig:
|
|
144
|
+
"""`base` with the Action's inputs applied: a group added, the top-level keys overridden."""
|
|
145
|
+
return GateConfig(
|
|
146
|
+
runs=(*base.runs, *([group] if group else [])),
|
|
147
|
+
fail_on=check_fail_on(fail_on) if fail_on else base.fail_on,
|
|
148
|
+
pack_store=pack_store or base.pack_store,
|
|
149
|
+
courant_version=courant_version or base.courant_version,
|
|
150
|
+
rules=base.rules, source=base.source)
|