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/cli/guard.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""No traceback reaches a user (TRD GATE-10).
|
|
2
|
+
|
|
3
|
+
An unexpected exception in any command ends with exit 4 and one line that names the command and
|
|
4
|
+
the Courant version and points at `--debug`, which prints the traceback. An input the user got
|
|
5
|
+
wrong is not an unexpected exception: commands report those themselves (`InputError`).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import functools
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
import traceback
|
|
14
|
+
|
|
15
|
+
import typer
|
|
16
|
+
|
|
17
|
+
#: Set by `--debug` (or by the user) to print the traceback instead of the one line.
|
|
18
|
+
DEBUG_ENV = "COURANT_DEBUG"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def debugging() -> bool:
|
|
22
|
+
return os.environ.get(DEBUG_ENV, "") not in ("", "0")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def internal_error(command: str, exc: BaseException) -> str:
|
|
26
|
+
"""The one line a user sees for an unexpected exception."""
|
|
27
|
+
from courant import __version__
|
|
28
|
+
|
|
29
|
+
return (f"courant {command}: internal error ({type(exc).__name__}) in courant {__version__}. "
|
|
30
|
+
f"Re-run with --debug for the traceback.")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def report(command: str, exc: BaseException, debug: bool = False) -> typer.Exit:
|
|
34
|
+
"""Print the one line (or the traceback under --debug) and return the exit-4 to raise."""
|
|
35
|
+
if debug or debugging():
|
|
36
|
+
traceback.print_exception(exc, file=sys.stderr)
|
|
37
|
+
else:
|
|
38
|
+
print(internal_error(command, exc), file=sys.stderr)
|
|
39
|
+
return typer.Exit(4)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _command_endings() -> tuple[type[BaseException], ...]:
|
|
43
|
+
"""How a command ends on purpose: typer's Exit and Abort, and the usage errors of the click
|
|
44
|
+
typer is built on (`typer.BadParameter` and its kin), whichever click that is. typer 0.27
|
|
45
|
+
vendors its own (`typer._click`); earlier releases used `click`. Naming `click` here made an
|
|
46
|
+
undeclared dependency (a plain `pip install` had no `click` and every command crashed on
|
|
47
|
+
import) and, on typer 0.27, turned a usage error into an internal error."""
|
|
48
|
+
usage = next(c for c in typer.BadParameter.__mro__ if c.__name__ == "ClickException")
|
|
49
|
+
return (typer.Exit, typer.Abort, usage, SystemExit, KeyboardInterrupt)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def guarded(command: str):
|
|
53
|
+
"""Decorator for a typer command. A `debug` keyword (the command's `--debug`) turns the
|
|
54
|
+
traceback on (so does COURANT_DEBUG=1); `typer.Exit` and click's own exceptions pass through
|
|
55
|
+
untouched (`_command_endings`)."""
|
|
56
|
+
|
|
57
|
+
def wrap(fn):
|
|
58
|
+
@functools.wraps(fn)
|
|
59
|
+
def inner(*args, **kwargs):
|
|
60
|
+
try:
|
|
61
|
+
return fn(*args, **kwargs)
|
|
62
|
+
except _command_endings():
|
|
63
|
+
raise
|
|
64
|
+
except Exception as exc: # the point of the guard
|
|
65
|
+
raise report(command, exc, bool(kwargs.get("debug"))) from exc
|
|
66
|
+
|
|
67
|
+
return inner
|
|
68
|
+
|
|
69
|
+
return wrap
|
courant/cli/main.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Courant CLI: verify engineering simulation results, on the machine that ran them.
|
|
2
|
+
|
|
3
|
+
The product:
|
|
4
|
+
verify a verdict on a completed run (accept, reject, insufficient)
|
|
5
|
+
gate the CI check: verify the runs a repository names (the GitHub Action)
|
|
6
|
+
convergence where the engineering answer stopped changing, and what came after
|
|
7
|
+
preflight a broken setup, caught before the solver spends anything
|
|
8
|
+
audit what a folder of runs cost, and how much of it bought nothing
|
|
9
|
+
watch a read-only advisory while the solver runs
|
|
10
|
+
test the Courant Test: score a judge, including an AI model
|
|
11
|
+
demo three real runs, offline, in seconds
|
|
12
|
+
mcp the same tools for an AI agent, over MCP
|
|
13
|
+
|
|
14
|
+
Every command is local and read-only, and none opens a network connection unless that is its
|
|
15
|
+
documented purpose and the user asked for it: `update` (github.com), `doctor --models`, and a
|
|
16
|
+
model judge or extractor the user names (the model door's provider). Each names what it
|
|
17
|
+
contacts before it does (docs/NETWORK.md). There is no account and no Courant service to sign
|
|
18
|
+
in to.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import typer
|
|
24
|
+
from rich.console import Console
|
|
25
|
+
|
|
26
|
+
from courant.cli.commands import audit as audit_cmds
|
|
27
|
+
from courant.cli.commands import convergence as convergence_cmds
|
|
28
|
+
from courant.cli.commands import doctor as doctor_cmds
|
|
29
|
+
from courant.cli.commands import gate as gate_cmds
|
|
30
|
+
from courant.cli.commands import update as update_cmds
|
|
31
|
+
from courant.cli.commands import verify as verify_cmds
|
|
32
|
+
from courant.cli.commands import ctest as ctest_cmds
|
|
33
|
+
from courant.cli.commands import live as live_cmds
|
|
34
|
+
from courant.cli.commands import mcp as mcp_cmds
|
|
35
|
+
from courant.cli.commands import preflight as preflight_cmds
|
|
36
|
+
from courant.cli.commands import spec as spec_cmds
|
|
37
|
+
from courant.cli.commands import tour as tour_cmds
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _Guarded(typer.Typer):
|
|
41
|
+
"""GATE-10: an unexpected exception in any command ends in exit 4 and one line, never a
|
|
42
|
+
traceback; `--debug` (before the command) or COURANT_DEBUG=1 prints it."""
|
|
43
|
+
|
|
44
|
+
def __call__(self, *args, **kwargs):
|
|
45
|
+
import sys
|
|
46
|
+
|
|
47
|
+
from courant.cli import guard
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
return super().__call__(*args, **kwargs)
|
|
51
|
+
except Exception as exc:
|
|
52
|
+
guard.report(sys.argv[1] if len(sys.argv) > 1 else "command", exc)
|
|
53
|
+
raise SystemExit(4) from exc
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
app = _Guarded(
|
|
57
|
+
pretty_exceptions_enable=False,
|
|
58
|
+
add_completion=False,
|
|
59
|
+
help=("Courant: verify engineering simulation results. Is this run trustworthy, did its "
|
|
60
|
+
"answer converge, and if not, why. Local and read-only."),
|
|
61
|
+
no_args_is_help=True,
|
|
62
|
+
)
|
|
63
|
+
console = Console()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@app.callback()
|
|
67
|
+
def _root(debug: bool = typer.Option(False, "--debug", help="Print the traceback of an internal "
|
|
68
|
+
"error instead of one line.")) -> None:
|
|
69
|
+
if debug:
|
|
70
|
+
import os
|
|
71
|
+
|
|
72
|
+
os.environ["COURANT_DEBUG"] = "1"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# --- the product ----------------------------------------------------------
|
|
76
|
+
app.command()(verify_cmds.verify)
|
|
77
|
+
app.command()(gate_cmds.gate)
|
|
78
|
+
app.command()(convergence_cmds.convergence)
|
|
79
|
+
app.command()(preflight_cmds.preflight)
|
|
80
|
+
app.command()(audit_cmds.audit)
|
|
81
|
+
app.command()(live_cmds.watch)
|
|
82
|
+
app.command()(tour_cmds.demo)
|
|
83
|
+
app.command()(mcp_cmds.mcp)
|
|
84
|
+
app.command()(doctor_cmds.doctor)
|
|
85
|
+
app.command()(update_cmds.update)
|
|
86
|
+
app.add_typer(ctest_cmds.app, name="test")
|
|
87
|
+
app.add_typer(spec_cmds.app, name="spec")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@app.command()
|
|
91
|
+
def version() -> None:
|
|
92
|
+
"""Print the Courant version."""
|
|
93
|
+
import platform
|
|
94
|
+
import sys
|
|
95
|
+
|
|
96
|
+
from courant import __version__
|
|
97
|
+
|
|
98
|
+
# From the module, not importlib.metadata: the packaged binary has no
|
|
99
|
+
# distribution metadata to read, and reporting "(dev)" to a customer whose
|
|
100
|
+
# agent the server just rejected as too old helps nobody.
|
|
101
|
+
frozen = getattr(sys, "frozen", False)
|
|
102
|
+
console.print(
|
|
103
|
+
f"courant {__version__} "
|
|
104
|
+
f"[dim]({platform.system().lower()}/{platform.machine()}"
|
|
105
|
+
f"{', packaged' if frozen else ''})[/dim]"
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
#: The extension point: when a package of this name is installed, its `register(app)` adds
|
|
110
|
+
#: commands. The published distribution ships none, and its `courant` is the gate alone.
|
|
111
|
+
EXTENSION = "courant.extensions"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _extend(target: typer.Typer) -> None:
|
|
115
|
+
import importlib
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
module = importlib.import_module(EXTENSION)
|
|
119
|
+
except ModuleNotFoundError as exc:
|
|
120
|
+
if exc.name != EXTENSION:
|
|
121
|
+
raise
|
|
122
|
+
return
|
|
123
|
+
module.register(target)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
_extend(app)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
if __name__ == "__main__":
|
|
130
|
+
app()
|
courant/cli/tail.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
"""Following a solver log that is still being written (Tech Bible §06).
|
|
2
|
+
|
|
3
|
+
``courant watch`` attaches to a solve that is already running, or about to be.
|
|
4
|
+
That means reading a file whose author is a separate process which may not have
|
|
5
|
+
started yet, may be writing faster than we read, and may — when the engineer
|
|
6
|
+
re-runs after a fix — replace the file underneath us mid-read.
|
|
7
|
+
|
|
8
|
+
Handling those three cases is the whole job, and each one is a real thing that
|
|
9
|
+
happens on a cluster rather than a hypothetical:
|
|
10
|
+
|
|
11
|
+
* **The file does not exist yet.** ``courant watch`` is typed *before*
|
|
12
|
+
``simpleFoam > log.simpleFoam``, because that is the natural order and
|
|
13
|
+
because on a scheduler the solve starts whenever the queue says so. Waiting
|
|
14
|
+
is the correct behaviour, not an error.
|
|
15
|
+
* **The file is truncated.** A re-run with the same redirect resets the file
|
|
16
|
+
to zero bytes. For this product that is not corruption — it is the *most
|
|
17
|
+
important* event in the loop: the run being verified after a fix. It is
|
|
18
|
+
reported as a restart, not swallowed.
|
|
19
|
+
* **The file is replaced.** Log rotation, or a re-run with ``>`` creating a
|
|
20
|
+
new inode. Same signal, detected by inode rather than size.
|
|
21
|
+
|
|
22
|
+
We always read from byte 0, never from the tail. Attaching to a solve that is
|
|
23
|
+
already 4,000 iterations in and diagnosing only what happens next would mean
|
|
24
|
+
diagnosing without the residual history, which is most of the evidence. It also
|
|
25
|
+
makes every offset an absolute file offset, which is what the server dedupes
|
|
26
|
+
uploaded events on.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import re
|
|
32
|
+
import time
|
|
33
|
+
from collections.abc import Callable, Iterator
|
|
34
|
+
from dataclasses import dataclass
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
|
|
37
|
+
from courant.case.reads import note
|
|
38
|
+
|
|
39
|
+
#: How often to look for new bytes. Solver logs are written in bursts of a few
|
|
40
|
+
#: hundred bytes per iteration; polling is both simpler and more portable than
|
|
41
|
+
#: inotify/FSEvents, and 250ms is far below human perception on a live display.
|
|
42
|
+
POLL_INTERVAL = 0.25
|
|
43
|
+
|
|
44
|
+
#: Give up waiting for a log that never appears. Long enough to survive a
|
|
45
|
+
#: scheduler queue of a few minutes; short enough that a typo in the path does
|
|
46
|
+
#: not hang a terminal all night.
|
|
47
|
+
DEFAULT_START_TIMEOUT = 600.0
|
|
48
|
+
|
|
49
|
+
#: Silence long enough to mean "the solver is done, or wedged". OpenFOAM writes
|
|
50
|
+
#: at least one line per iteration, and an iteration that takes longer than this
|
|
51
|
+
#: on any real case is itself the anomaly the watcher exists to report.
|
|
52
|
+
DEFAULT_IDLE_TIMEOUT = 120.0
|
|
53
|
+
|
|
54
|
+
READ_SIZE = 1 << 20 # 1 MiB per poll — bounds memory on a fast solve
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True, slots=True)
|
|
58
|
+
class Chunk:
|
|
59
|
+
"""New log text, and where it came from."""
|
|
60
|
+
|
|
61
|
+
text: str
|
|
62
|
+
offset: int # absolute byte offset this chunk starts at
|
|
63
|
+
restarted: bool = False # the file was truncated or replaced before this
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class LogTail:
|
|
67
|
+
"""Follow a growing file, yielding chunks until it stops growing.
|
|
68
|
+
|
|
69
|
+
Not a general-purpose ``tail -f``: it is specialised to the one thing the
|
|
70
|
+
agent needs, which is a byte-accurate, restart-aware stream with a bounded
|
|
71
|
+
definition of "finished".
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
def __init__(
|
|
75
|
+
self,
|
|
76
|
+
path: str | Path,
|
|
77
|
+
*,
|
|
78
|
+
poll_interval: float = POLL_INTERVAL,
|
|
79
|
+
start_timeout: float = DEFAULT_START_TIMEOUT,
|
|
80
|
+
idle_timeout: float | None = DEFAULT_IDLE_TIMEOUT,
|
|
81
|
+
clock=time.monotonic,
|
|
82
|
+
sleep=time.sleep,
|
|
83
|
+
) -> None:
|
|
84
|
+
self.path = Path(path)
|
|
85
|
+
self.poll_interval = poll_interval
|
|
86
|
+
self.start_timeout = start_timeout
|
|
87
|
+
self.idle_timeout = idle_timeout
|
|
88
|
+
self._clock = clock
|
|
89
|
+
self._sleep = sleep
|
|
90
|
+
self._stopped = False
|
|
91
|
+
self.position = 0
|
|
92
|
+
self._inode: int | None = None
|
|
93
|
+
# The first bytes this file had when we read them. Linux reuses a deleted file's inode
|
|
94
|
+
# number at once, so a replacement can keep the inode; a different head shows it.
|
|
95
|
+
self._head: bytes = b""
|
|
96
|
+
|
|
97
|
+
def stop(self) -> None:
|
|
98
|
+
"""Ask the follow loop to finish. Safe from a signal handler."""
|
|
99
|
+
self._stopped = True
|
|
100
|
+
|
|
101
|
+
# -- waiting ------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
def wait_for_file(self) -> bool:
|
|
104
|
+
"""Block until the log appears. False if it never did."""
|
|
105
|
+
deadline = self._clock() + self.start_timeout
|
|
106
|
+
while not self._stopped:
|
|
107
|
+
if self.path.exists():
|
|
108
|
+
return True
|
|
109
|
+
if self._clock() >= deadline:
|
|
110
|
+
return False
|
|
111
|
+
self._sleep(self.poll_interval)
|
|
112
|
+
return False
|
|
113
|
+
|
|
114
|
+
# -- following ----------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
def follow(self) -> Iterator[Chunk]:
|
|
117
|
+
"""Yield chunks until the file goes quiet, or ``stop()`` is called.
|
|
118
|
+
|
|
119
|
+
Ends by returning, never by raising, so a caller's ``for`` loop is also
|
|
120
|
+
its shutdown path: whatever stops the stream, the run still gets
|
|
121
|
+
verified and reported.
|
|
122
|
+
"""
|
|
123
|
+
if not self.wait_for_file():
|
|
124
|
+
return
|
|
125
|
+
|
|
126
|
+
last_data_at = self._clock()
|
|
127
|
+
|
|
128
|
+
while not self._stopped:
|
|
129
|
+
restarted = self._detect_restart()
|
|
130
|
+
text = self._read_new()
|
|
131
|
+
|
|
132
|
+
if text:
|
|
133
|
+
yield Chunk(text=text, offset=self.position - len(text.encode()),
|
|
134
|
+
restarted=restarted)
|
|
135
|
+
last_data_at = self._clock()
|
|
136
|
+
elif restarted:
|
|
137
|
+
# The file was replaced but nothing is in it yet. Tell the
|
|
138
|
+
# caller now rather than sitting on it: this is the re-run
|
|
139
|
+
# starting, and the display should say so.
|
|
140
|
+
yield Chunk(text="", offset=0, restarted=True)
|
|
141
|
+
last_data_at = self._clock()
|
|
142
|
+
elif self.idle_timeout is not None and (
|
|
143
|
+
self._clock() - last_data_at >= self.idle_timeout
|
|
144
|
+
):
|
|
145
|
+
return
|
|
146
|
+
|
|
147
|
+
self._sleep(self.poll_interval)
|
|
148
|
+
|
|
149
|
+
def read_all(self) -> str:
|
|
150
|
+
"""Everything written so far, without following. For a finished run."""
|
|
151
|
+
if not self.path.exists():
|
|
152
|
+
return ""
|
|
153
|
+
self._detect_restart()
|
|
154
|
+
return self._read_new()
|
|
155
|
+
|
|
156
|
+
# -- internals ----------------------------------------------------------
|
|
157
|
+
|
|
158
|
+
def _detect_restart(self) -> bool:
|
|
159
|
+
"""True if the file was truncated or replaced since the last read."""
|
|
160
|
+
try:
|
|
161
|
+
stat = self.path.stat()
|
|
162
|
+
except FileNotFoundError:
|
|
163
|
+
# Deleted mid-run. Treat the next appearance as a restart rather
|
|
164
|
+
# than resuming at a stale offset into a different file.
|
|
165
|
+
self._inode, self.position, self._head = None, 0, b""
|
|
166
|
+
return False
|
|
167
|
+
|
|
168
|
+
replaced = self._inode is not None and stat.st_ino != self._inode
|
|
169
|
+
truncated = stat.st_size < self.position
|
|
170
|
+
if not replaced and not truncated and self._head:
|
|
171
|
+
replaced = self._read_head(len(self._head)) != self._head
|
|
172
|
+
self._inode = stat.st_ino
|
|
173
|
+
|
|
174
|
+
if replaced or truncated:
|
|
175
|
+
self.position, self._head = 0, b""
|
|
176
|
+
return True
|
|
177
|
+
return False
|
|
178
|
+
|
|
179
|
+
def _read_head(self, n: int) -> bytes:
|
|
180
|
+
try:
|
|
181
|
+
with self.path.open("rb") as handle:
|
|
182
|
+
return handle.read(n)
|
|
183
|
+
except FileNotFoundError:
|
|
184
|
+
return b""
|
|
185
|
+
|
|
186
|
+
def _read_new(self) -> str:
|
|
187
|
+
"""Bytes since ``position``, decoded leniently."""
|
|
188
|
+
try:
|
|
189
|
+
with self.path.open("rb") as handle:
|
|
190
|
+
handle.seek(self.position)
|
|
191
|
+
raw = handle.read(READ_SIZE)
|
|
192
|
+
except FileNotFoundError:
|
|
193
|
+
return ""
|
|
194
|
+
|
|
195
|
+
if not raw:
|
|
196
|
+
return ""
|
|
197
|
+
|
|
198
|
+
# A chunk boundary can split a multi-byte character. Dropping the
|
|
199
|
+
# partial tail and rewinding is what keeps offsets byte-exact — decoding
|
|
200
|
+
# with `errors="replace"` would silently change the length.
|
|
201
|
+
text, consumed = _decode_whole_characters(raw)
|
|
202
|
+
if self.position < HEAD_BYTES:
|
|
203
|
+
self._head = (self._head + raw[:consumed])[:HEAD_BYTES]
|
|
204
|
+
self.position += consumed
|
|
205
|
+
return text
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
#: How many of a log's first bytes identify it (a solver banner, then the case header).
|
|
209
|
+
HEAD_BYTES = 256
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _decode_whole_characters(raw: bytes) -> tuple[str, int]:
|
|
213
|
+
"""Decode as much valid UTF-8 as possible; return the text and bytes used."""
|
|
214
|
+
for cut in range(len(raw), max(len(raw) - 4, -1), -1):
|
|
215
|
+
try:
|
|
216
|
+
return raw[:cut].decode("utf-8"), cut
|
|
217
|
+
except UnicodeDecodeError:
|
|
218
|
+
continue
|
|
219
|
+
# Not a truncation problem — genuinely invalid bytes. Solver logs are ASCII
|
|
220
|
+
# in practice; a binary blob in one is not worth stalling a run over.
|
|
221
|
+
return raw.decode("utf-8", errors="replace"), len(raw)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def wait_for_log(
|
|
225
|
+
case_dir: str | Path,
|
|
226
|
+
*,
|
|
227
|
+
timeout: float = DEFAULT_START_TIMEOUT,
|
|
228
|
+
poll_interval: float = 1.0,
|
|
229
|
+
on_wait: Callable[[], None] | None = None,
|
|
230
|
+
clock=time.monotonic,
|
|
231
|
+
sleep=time.sleep,
|
|
232
|
+
) -> Path | None:
|
|
233
|
+
"""Wait for a solver log to appear in a case directory.
|
|
234
|
+
|
|
235
|
+
``LogTail`` can already wait for a *named* file that does not exist yet. This
|
|
236
|
+
is the case where we do not know the name either, which is the normal one:
|
|
237
|
+
an engineer opens two panes and types ``courant watch .`` in the first
|
|
238
|
+
before ``simpleFoam > log.simpleFoam`` in the second. Exiting with "no log
|
|
239
|
+
found" would make the tool demand an ordering the engineer did not choose.
|
|
240
|
+
"""
|
|
241
|
+
deadline = clock() + timeout
|
|
242
|
+
announced = False
|
|
243
|
+
while True:
|
|
244
|
+
found = find_log(case_dir)
|
|
245
|
+
if found is not None:
|
|
246
|
+
return found
|
|
247
|
+
if clock() >= deadline:
|
|
248
|
+
return None
|
|
249
|
+
if on_wait is not None and not announced:
|
|
250
|
+
on_wait()
|
|
251
|
+
announced = True
|
|
252
|
+
sleep(poll_interval)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
#: OpenFOAM utilities that write a `log.<name>` beside the solver's. Named
|
|
256
|
+
#: rather than inferred because the decisive one runs *after* the solver:
|
|
257
|
+
#: `reconstructPar` is the last step of every parallel workflow, so its log is
|
|
258
|
+
#: always newer than the solve it belongs to.
|
|
259
|
+
_UTILITIES = frozenset({
|
|
260
|
+
"blockMesh", "snappyHexMesh", "decomposePar", "reconstructPar",
|
|
261
|
+
"reconstructParMesh", "checkMesh", "setFields", "mapFields", "topoSet",
|
|
262
|
+
"createPatch", "extrudeMesh", "surfaceFeatureExtract", "renumberMesh",
|
|
263
|
+
"transformPoints", "refineMesh", "splitMeshRegions", "foamDictionary",
|
|
264
|
+
"changeDictionary", "redistributePar", "collapseEdges", "zipUpMesh",
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
#: A solver iterates; a utility does not. Either marker is decisive.
|
|
268
|
+
_TIME_LOOP = re.compile(r"^(?:Starting time loop|Time = )", re.M)
|
|
269
|
+
|
|
270
|
+
#: Every OpenFOAM log opens with a banner naming what produced it.
|
|
271
|
+
_EXEC_LINE = re.compile(r"^Exec\s*:\s*(\S+)", re.M)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _log_rank(path: Path) -> int:
|
|
275
|
+
"""2 = a solve · 1 = unknown · 0 = a known utility.
|
|
276
|
+
|
|
277
|
+
THE BANNER WINS, and this order is the whole point. The obvious rule —
|
|
278
|
+
"a solver iterates, a utility does not, so look for `Time =`" — is wrong,
|
|
279
|
+
and measurably so: `decomposePar` and `reconstructPar` both print a
|
|
280
|
+
`Time = <t>` line per time directory they touch. Ranking those two by
|
|
281
|
+
content puts them level with the solve they bracket.
|
|
282
|
+
|
|
283
|
+
So a log whose `Exec :` line names a known utility is a utility, whatever it
|
|
284
|
+
printed. Content is the fallback for an application we do not have in the
|
|
285
|
+
list, where evidence of a time loop is the best signal available.
|
|
286
|
+
"""
|
|
287
|
+
try:
|
|
288
|
+
with open(path, "rb") as fh:
|
|
289
|
+
head = fh.read(64 * 1024).decode("utf-8", "replace")
|
|
290
|
+
except OSError:
|
|
291
|
+
return 1
|
|
292
|
+
note(path) # VER-14: this head decided which log is the solve's
|
|
293
|
+
|
|
294
|
+
exec_match = _EXEC_LINE.search(head)
|
|
295
|
+
if exec_match:
|
|
296
|
+
app = exec_match.group(1).rsplit("/", 1)[-1]
|
|
297
|
+
if app in _UTILITIES:
|
|
298
|
+
return 0
|
|
299
|
+
# A named application that is not a known utility: a solver, or a solver
|
|
300
|
+
# we have never heard of. Either way it outranks a utility.
|
|
301
|
+
return 2 if _TIME_LOOP.search(head) else 1
|
|
302
|
+
|
|
303
|
+
if _TIME_LOOP.search(head):
|
|
304
|
+
return 2
|
|
305
|
+
|
|
306
|
+
# No banner: not an OpenFOAM log, or truncated before the header was written.
|
|
307
|
+
stem = path.name[4:] if path.name.startswith("log.") else path.stem
|
|
308
|
+
return 0 if stem in _UTILITIES else 1
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def find_log(case_dir: str | Path) -> Path | None:
|
|
312
|
+
"""Guess the log an OpenFOAM run is writing to.
|
|
313
|
+
|
|
314
|
+
Convention is ``log.<solver>`` in the case directory — near-universal, and
|
|
315
|
+
what every OpenFOAM tutorial and Allrun script produces.
|
|
316
|
+
|
|
317
|
+
NEWEST IS NOT ENOUGH, and the case where it fails is the one we most want to
|
|
318
|
+
work. A parallel workflow is `blockMesh · decomposePar · mpirun solver ·
|
|
319
|
+
reconstructPar`, so the newest `log.*` in a finished parallel case is
|
|
320
|
+
`log.reconstructPar` — a few lines of utility output with no residuals in it.
|
|
321
|
+
Watching that file reports a clean run. Measured on a decomposed cavity case
|
|
322
|
+
that had diverged to a Courant number of 1580: Courant followed
|
|
323
|
+
`log.decomposePar` and returned **Trust Grade A**.
|
|
324
|
+
|
|
325
|
+
So: rank by what the file contains, and only then by age. Newest still wins
|
|
326
|
+
among logs of equal rank, which is what makes re-running a case pick up the
|
|
327
|
+
new solve rather than yesterday's.
|
|
328
|
+
|
|
329
|
+
A known utility's log is never the run's log. When only those exist (the
|
|
330
|
+
solver's output went elsewhere, or the solver never ran) there is no solver
|
|
331
|
+
log, and None says so; `utility_logs` names what was there. Returning
|
|
332
|
+
`log.checkMesh` made `courant verify` judge a mesh report as the run
|
|
333
|
+
(insufficient, VER-5.5) on a case whose solver had run, without saying why.
|
|
334
|
+
"""
|
|
335
|
+
case = Path(case_dir)
|
|
336
|
+
candidates = [
|
|
337
|
+
p for p in case.glob("log.*")
|
|
338
|
+
if p.is_file() and not p.name.endswith((".gz", ".bak"))
|
|
339
|
+
]
|
|
340
|
+
candidates += [p for p in case.glob("*.log") if p.is_file()]
|
|
341
|
+
if not candidates:
|
|
342
|
+
return None
|
|
343
|
+
rank, _, best = max((_log_rank(p), p.stat().st_mtime, p) for p in candidates)
|
|
344
|
+
return best if rank > 0 else None
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def utility_logs(case_dir: str | Path) -> list[str]:
|
|
348
|
+
"""The known utilities' logs in a case directory, by name: what `find_log` passed over."""
|
|
349
|
+
case = Path(case_dir)
|
|
350
|
+
return sorted(p.name for p in case.glob("log.*")
|
|
351
|
+
if p.is_file() and p.name[4:] in _UTILITIES)
|