STRA-338: deploy USAGE wide lines wrapped with string continuations (cooked bytes identical), archcheck python within the limits, baselines at zero

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-07 17:37:52 +01:00
co-authored by Claude Sonnet 5.5
parent d9264eda11
commit 5ba57146ed
4 changed files with 442 additions and 412 deletions
+66 -33
View File
@@ -6,30 +6,43 @@ pub const USAGE: &str = "\
leleka - one-command deployment of the Leleka runtime
USAGE
leleka up [OPTIONS] preflight, fetch+verify the model, build the KAR archive, install, start, wait for ready
leleka up [OPTIONS] preflight, fetch+verify the model, build the KAR archive, install, start, wait for \
ready
leleka preflight [OPTIONS] only the host checks (exit 1 when one fails)
leleka run --config FILE the foreground supervisor that systemd starts (engine + gateway + API)
leleka status [OPTIONS] service state and readiness
leleka reconfigure [OPTIONS] change the inference settings of the running engine without reloading the model
leleka logs [OPTIONS] read the service's structured logs: --tail N (default 50), --since 15m|2h|1d|UTC time, --level warn,
--component api|engine|supervisor|runtime-client|gateway|memory, --source requests|api|engine|gateway|leleka,
--request ID (any 6+ characters of a request id: every line of that request, API and engine joined),
leleka logs [OPTIONS] read the service's structured logs: --tail N (default 50), --since 15m|2h|1d|UTC \
time, --level warn,
--component api|engine|supervisor|runtime-client|gateway|memory, --source \
requests|api|engine|gateway|leleka,
--request ID (any 6+ characters of a request id: every line of that request, API \
and engine joined),
--follow, --json (the stored JSON lines as they are)
leleka report [OPTIONS] a sanitized support bundle in one small JSON file you can attach to feedback: versions, commit, Strata pin,
profile, expert tier ON/OFF with its digest, hardware, service health, request statistics, the last
--last N (default 50) request records and recent warnings. No prompts, no model output, no API key or token.
It shows what it would contain and writes nothing until you add --yes; --out FILE|- chooses the place.
leleka report [OPTIONS] a sanitized support bundle in one small JSON file you can attach to feedback: \
versions, commit, Strata pin,
profile, expert tier ON/OFF with its digest, hardware, service health, request \
statistics, the last
--last N (default 50) request records and recent warnings. No prompts, no model \
output, no API key or token.
It shows what it would contain and writes nothing until you add --yes; --out \
FILE|- chooses the place.
Nothing is ever sent anywhere by Leleka: no telemetry upload exists
leleka down [OPTIONS] stop the systemd service
leleka service install|uninstall|status|start|stop [OPTIONS]
keep the service running without a terminal: a Task Scheduler task at logon on Windows (native route),
keep the service running without a terminal: a Task Scheduler task at logon on \
Windows (native route),
the user unit in the distribution (+ a task that keeps the VM alive) on the WSL route
leleka verify [OPTIONS] hash both shards and the archive in full (in parallel), check the pinned digests, renew the
leleka verify [OPTIONS] hash both shards and the archive in full (in parallel), check the pinned digests, \
renew the
verification stamps that let a restart skip the hashing (needs a prepared state);
--quick hashes nothing: it reports the health of the installation (stamps, service, disk, logs)
--quick hashes nothing: it reports the health of the installation (stamps, \
service, disk, logs)
leleka seal-exec --file PATH [--expect-bytes N] [--sparse-ple] -- COMMAND ARG...
copy the archive into a sealed memfd (--sparse-ple: only the byte ranges the serve path reads, as rtx5090-32g does)
and run COMMAND with the descriptor; {FD} in an argument is its number (Linux; for A/B runs outside `leleka run`)
copy the archive into a sealed memfd (--sparse-ple: only the byte ranges the serve \
path reads, as rtx5090-32g does)
and run COMMAND with the descriptor; {FD} in an argument is its number (Linux; for \
A/B runs outside `leleka run`)
leleka profiles [show NAME] list the memory profiles, or print one as JSON
leleka version
@@ -71,46 +84,66 @@ UP / PREFLIGHT OPTIONS
its RAM is not required (foreground / --mode none only)
--service-user NAME system unit only: account the service runs as (default leleka, created if missing)
RECONFIGURE OPTIONS (any of them; the call waits for the request in flight, the engine reopens its serve stack in a few seconds, the weights stay
RECONFIGURE OPTIONS (any of them; the call waits for the request in flight, the engine reopens its serve stack in a \
few seconds, the weights stay
loaded; a refused change keeps the previous settings; --kv-resident is fixed per process and needs `leleka up`)
--context-tokens N tokens of context (1..262144)
--prefill-capacity N prefill chunk: 256 512 1024 2048 3072 4096 6144 8192
--kv-resident N only the value in force is accepted (the K/V window is fixed per process; restart to change it)
--kv-resident N only the value in force is accepted (the K/V window is fixed per process; restart to \
change it)
--prefix-cache-mib auto|off|N host-RAM budget of the cross-session prefix cache
--prefix-cache-tail off|prompt|reply request-end checkpoints
--prefix-cache-block N tokens per prefix block (multiple of 256; 0 = the prefill chunk)
--prefix-retention-min N minutes an idle cached session is kept (0 = no limit)
--cpu-workers N CPU expert workers (1..15)
--spec-min-p P draft-probability floor (0..1)
--gpu-budget-gib N VRAM budget of the engine (1..1024). Fixed when the CUDA context is created: the supervisor restarts
the engine process (the model loads again, minutes), the gateway and the API keep their ports
--gpu-budget-gib N VRAM budget of the engine (1..1024). Fixed when the CUDA context is created: the \
supervisor restarts
the engine process (the model loads again, minutes), the gateway and the API keep their \
ports
--preset dedicated|workstation resource preset (same restart); refused when the host cannot hold it
--persist keep the change across restarts of the service (writes leleka.json)
--assets/--state-dir/--prefix/--api-port/--json as for `up`; `leleka status` prints the settings in force
WINDOWS
leleka.exe runs the engine in one of two ways (docs/windows.md):
--wsl / --native route for up, preflight, verify, status, reconfigure, down: `--wsl` (the default for `up`) runs the Linux
`leleka` inside WSL2 through wsl.exe and talks to it over loopback HTTP; `--native` runs engine, gateway
--wsl / --native route for up, preflight, verify, status, reconfigure, down: `--wsl` (the default for \
`up`) runs the Linux
`leleka` inside WSL2 through wsl.exe and talks to it over loopback HTTP; `--native` \
runs engine, gateway
and API as Windows processes (the model volume must already be on a Windows disk)
--wsl-distro NAME WSL2 distribution to use (default: the default one that is not Docker's) [$LELEKA_WSL_DISTRO]
--wsl-distro NAME WSL2 distribution to use (default: the default one that is not Docker's) \
[$LELEKA_WSL_DISTRO]
--wsl-bin PATH the Linux `leleka` inside the distribution (default: searched in the usual places)
leleka doctor what this Windows machine offers: GPU, RAM, .wslconfig advice, WSL distributions, the Linux leleka
Paths for the WSL route may be Linux paths (/home/me/leleka), \\\\wsl.localhost\\Ubuntu\\... paths or Windows paths (C:\\...; they become
/mnt/c/..., which is far too slow for the model, so --assets is refused there). Native defaults live in %LOCALAPPDATA%\\leleka.
leleka doctor what this Windows machine offers: GPU, RAM, .wslconfig advice, WSL distributions, the \
Linux leleka
Paths for the WSL route may be Linux paths (/home/me/leleka), \\\\wsl.localhost\\Ubuntu\\... paths or Windows \
paths (C:\\...; they become
/mnt/c/..., which is far too slow for the model, so --assets is refused there). Native defaults live in \
%LOCALAPPDATA%\\leleka.
LOGS
Every process writes one JSON object per line to STATE/logs/{leleka,engine,gateway,api,requests}.log (timestamp in UTC with milliseconds,
level, component, event, flat fields); a terminal gets the same event as key=value text. `requests.log` has one record per generation
request: request id and session tag (a hash of the client's session header), dialect, model, profile, prompt / cached / output tokens,
queue wait, time to first token, prefill and decode tok/s, finish reason, error class, whether the engine was lost meanwhile, the GPU
clock, temperature and throttle reasons. The same id is in the `x-leleka-request-id` response header and in the engine's own line
(tokens per speculative round, expert-tier share served from VRAM / PCIe / CPU). Prompts and answers are never logged; the API key and
tokens are scrubbed from every line. Files are size-capped and rotated by the supervisor (leleka.json `logs`), and a repeating event
is sampled (burst, then one line per 10 s with a `suppressed` count). `/metrics?format=prometheus` exposes the same figures as counters,
Every process writes one JSON object per line to STATE/logs/{leleka,engine,gateway,api,requests}.log (timestamp \
in UTC with milliseconds,
level, component, event, flat fields); a terminal gets the same event as key=value text. `requests.log` has one \
record per generation
request: request id and session tag (a hash of the client's session header), dialect, model, profile, prompt / \
cached / output tokens,
queue wait, time to first token, prefill and decode tok/s, finish reason, error class, whether the engine was \
lost meanwhile, the GPU
clock, temperature and throttle reasons. The same id is in the `x-leleka-request-id` response header and in the \
engine's own line
(tokens per speculative round, expert-tier share served from VRAM / PCIe / CPU). Prompts and answers are never \
logged; the API key and
tokens are scrubbed from every line. Files are size-capped and rotated by the supervisor (leleka.json `logs`), \
and a repeating event
is sampled (burst, then one line per 10 s with a `suppressed` count). `/metrics?format=prometheus` exposes the \
same figures as counters,
histograms and gauges.
LELEKA_LOG_LEVEL=debug|info|warn|error, LELEKA_LOG_FORMAT=json|text|legacy, LELEKA_LOG_DEBUG=1 (debug level + the length of redacted text)
are read by every process. `leleka run` starts its children with JSON; a binary started by hand writes key=value text on a terminal and,
LELEKA_LOG_LEVEL=debug|info|warn|error, LELEKA_LOG_FORMAT=json|text|legacy, LELEKA_LOG_DEBUG=1 (debug level + the \
length of redacted text)
are read by every process. `leleka run` starts its children with JSON; a binary started by hand writes key=value \
text on a terminal and,
into a file, the plain lines that the lab scripts (scripts/e2e) parse (also LELEKA_LOG_LEGACY=1).
ENVIRONMENT
+2 -9
View File
@@ -8,18 +8,11 @@
},
"census": {
"prod": {
"leleka-deploy": {
"width": 33
},
"python": {
"complexity": 1,
"width": 2
}
},
"test": {
"python": {
"width": 1
}
}
},
"test": {}
}
}
+184 -181
View File
@@ -1,181 +1,184 @@
"""Measurements taken from the workspace: package graph, file sizes, source pattern counts."""
import json
import pathlib
import re
import subprocess
TEST_DIRS = ("tests",)
def load_metadata(root):
"""Workspace packages with their normal internal and external dependencies."""
cmd = ["cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"]
meta = json.loads(subprocess.run(cmd, cwd=root, check=True, capture_output=True, text=True).stdout)
internal = {p["name"] for p in meta["packages"]}
return sorted((_package(p, internal) for p in meta["packages"]), key=lambda p: p["name"])
def _package(raw, internal):
normal = [d["name"] for d in raw["dependencies"] if d["kind"] is None]
return {
"name": raw["name"],
"dir": pathlib.Path(raw["manifest_path"]).parent,
"normal": sorted({n for n in normal if n in internal}),
"external": sorted({n for n in normal if n not in internal}),
}
def rust_files(directory):
"""Every .rs file under a directory except build output."""
for path in sorted(directory.rglob("*.rs")):
if "target" not in path.relative_to(directory).parts:
yield path
def _text(path):
return path.read_text(encoding="utf-8", errors="replace")
def file_lines(root, packages):
"""{relative posix path: line count} for every .rs file in a workspace package."""
sizes = {}
for pkg in packages:
for path in rust_files(pkg["dir"]):
sizes[path.relative_to(root).as_posix()] = len(_text(path).splitlines())
return sizes
def is_test_file(path, src):
"""A test module in its own file counts like the inline `#[cfg(test)]` module it replaces."""
parts = path.relative_to(src).parts
return path.name == "tests.rs" or path.name.endswith("_tests.rs") or any(d in parts[:-1] for d in TEST_DIRS)
def production_lines(text):
"""Lines before the first `#[cfg(test)]` module (column 0, followed by `mod`); comment lines are dropped.
An inline module under another test cfg (`#[cfg(all(test, ...))]` then `mod x {`) is skipped up to its closing
`}` at column 0; the code after it still counts."""
lines = text.splitlines()
kept = []
index = 0
while index < len(lines):
line = lines[index]
following = lines[index + 1] if index + 1 < len(lines) else ""
if line.startswith("#[cfg(test)]") and following.startswith("mod "):
break
if _is_test_cfg(line) and line.startswith("#[cfg(") and following.startswith("mod ") and following.rstrip().endswith("{"):
index = _after_block(lines, index + 1)
continue
if not line.lstrip().startswith("//"):
kept.append(line)
index += 1
return kept
def _after_block(lines, start):
"""Index of the line after the column-0 `}` that closes the block opened at `start`."""
for index in range(start + 1, len(lines)):
if lines[index].startswith("}"):
return index + 1
return len(lines)
def count_patterns(packages, patterns):
"""{"<pattern id>:<crate>": n} for the non-zero counts, over production code in src/ only (test files and modules declared under a test cfg are skipped)."""
compiled = [(p["id"], re.compile(p["regex"])) for p in patterns]
counts = {}
for pkg in packages:
for pid, n in _package_counts(pkg["dir"] / "src", compiled).items():
counts[f"{pid}:{pkg['name']}"] = n
return counts
_MOD_LINE = re.compile(r"(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*;")
_PATH_ATTR = re.compile(r'#\[path\s*=\s*"([^"]+)"\]')
def test_only_modules(src):
"""Files compiled only for tests: a `mod x;` declared under a `#[cfg(...test...)]` attribute (with or without a
`#[path]`), and every module those files declare in turn. `_under_test_module` extends this to the files below
such a module."""
declared = {path.resolve(): _declarations(_text(path)) for path in rust_files(src)}
found = set()
queue = []
for path, decls in declared.items():
for name, explicit, tested in decls:
target = _module_file(path, name, explicit) if tested else None
if target is not None and target not in found:
found.add(target)
queue.append(target)
while queue:
owner = queue.pop()
for name, explicit, _ in declared.get(owner, []):
target = _module_file(owner, name, explicit)
if target is not None and target not in found:
found.add(target)
queue.append(target)
return found
def _declarations(text):
"""[(module name, #[path] value or None, declared under a test cfg)] of the `mod x;` lines of a file."""
out = []
attrs = []
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("#[") or (attrs and _unbalanced(" ".join(attrs))):
attrs.append(stripped)
continue
decl = _MOD_LINE.match(stripped)
if decl:
block = " ".join(attrs)
explicit = _PATH_ATTR.search(block)
out.append((decl.group(1), explicit.group(1) if explicit else None, _is_test_cfg(block)))
attrs = []
return out
def _unbalanced(text):
return text.count("[") > text.count("]") or text.count("(") > text.count(")")
def _is_test_cfg(block):
return "cfg(" in block and re.search(r"\btest\b", block) is not None and "not(test" not in block
def _module_file(declaring, name, explicit):
here = declaring.parent
if explicit:
target = (here / explicit).resolve()
return target if target.is_file() else None
base = here if declaring.name in ("lib.rs", "main.rs", "mod.rs") else here / declaring.stem
for candidate in (base / f"{name}.rs", base / name / "mod.rs"):
if candidate.is_file():
return candidate.resolve()
return None
def _under_test_module(path, test_files):
"""The file itself or a file in the directory a test-only module owns (`x.rs` owns `x/`, `mod.rs` its folder)."""
resolved = path.resolve()
for owner in test_files:
folder = owner.parent if owner.name == "mod.rs" else owner.with_suffix("")
if resolved == owner or resolved.is_relative_to(folder):
return True
return False
def _package_counts(src, compiled):
totals = {}
if not src.is_dir():
return totals
test_files = test_only_modules(src)
for path in rust_files(src):
if is_test_file(path, src) or _under_test_module(path, test_files):
continue
rows = production_lines(_text(path))
for pid, rx in compiled:
n = sum(len(rx.findall(row)) for row in rows)
if n:
totals[pid] = totals.get(pid, 0) + n
return totals
"""Measurements taken from the workspace: package graph, file sizes, source pattern counts."""
import json
import pathlib
import re
import subprocess
TEST_DIRS = ("tests",)
def load_metadata(root):
"""Workspace packages with their normal internal and external dependencies."""
cmd = ["cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"]
meta = json.loads(subprocess.run(cmd, cwd=root, check=True, capture_output=True, text=True).stdout)
internal = {p["name"] for p in meta["packages"]}
return sorted((_package(p, internal) for p in meta["packages"]), key=lambda p: p["name"])
def _package(raw, internal):
normal = [d["name"] for d in raw["dependencies"] if d["kind"] is None]
return {
"name": raw["name"],
"dir": pathlib.Path(raw["manifest_path"]).parent,
"normal": sorted({n for n in normal if n in internal}),
"external": sorted({n for n in normal if n not in internal}),
}
def rust_files(directory):
"""Every .rs file under a directory except build output."""
for path in sorted(directory.rglob("*.rs")):
if "target" not in path.relative_to(directory).parts:
yield path
def _text(path):
return path.read_text(encoding="utf-8", errors="replace")
def file_lines(root, packages):
"""{relative posix path: line count} for every .rs file in a workspace package."""
sizes = {}
for pkg in packages:
for path in rust_files(pkg["dir"]):
sizes[path.relative_to(root).as_posix()] = len(_text(path).splitlines())
return sizes
def is_test_file(path, src):
"""A test module in its own file counts like the inline `#[cfg(test)]` module it replaces."""
parts = path.relative_to(src).parts
return path.name == "tests.rs" or path.name.endswith("_tests.rs") or any(d in parts[:-1] for d in TEST_DIRS)
def production_lines(text):
"""Lines before the first `#[cfg(test)]` module (column 0, followed by `mod`); comment lines are dropped.
An inline module under another test cfg (`#[cfg(all(test, ...))]` then `mod x {`) is skipped up to its closing
`}` at column 0; the code after it still counts."""
lines = text.splitlines()
kept = []
index = 0
while index < len(lines):
line = lines[index]
following = lines[index + 1] if index + 1 < len(lines) else ""
if line.startswith("#[cfg(test)]") and following.startswith("mod "):
break
opens_test_block = following.startswith("mod ") and following.rstrip().endswith("{")
if _is_test_cfg(line) and line.startswith("#[cfg(") and opens_test_block:
index = _after_block(lines, index + 1)
continue
if not line.lstrip().startswith("//"):
kept.append(line)
index += 1
return kept
def _after_block(lines, start):
"""Index of the line after the column-0 `}` that closes the block opened at `start`."""
for index in range(start + 1, len(lines)):
if lines[index].startswith("}"):
return index + 1
return len(lines)
def count_patterns(packages, patterns):
"""{"<pattern id>:<crate>": n} for the non-zero counts, over production code in src/ only (test files and modules declared under a test cfg
are skipped)."""
compiled = [(p["id"], re.compile(p["regex"])) for p in patterns]
counts = {}
for pkg in packages:
for pid, n in _package_counts(pkg["dir"] / "src", compiled).items():
counts[f"{pid}:{pkg['name']}"] = n
return counts
_MOD_LINE = re.compile(r"(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*;")
_PATH_ATTR = re.compile(r'#\[path\s*=\s*"([^"]+)"\]')
def test_only_modules(src):
"""Files compiled only for tests: a `mod x;` declared under a `#[cfg(...test...)]` attribute (with or without a
`#[path]`), and every module those files declare in turn. `_under_test_module` extends this to the files below
such a module."""
declared = {path.resolve(): _declarations(_text(path)) for path in rust_files(src)}
found = set()
queue = [
target
for path, decls in declared.items()
for name, explicit, tested in decls
if tested and (target := _module_file(path, name, explicit)) is not None
]
while queue:
owner = queue.pop()
if owner in found:
continue
found.add(owner)
for name, explicit, _ in declared.get(owner, []):
target = _module_file(owner, name, explicit)
if target is not None and target not in found:
queue.append(target)
return found
def _declarations(text):
"""[(module name, #[path] value or None, declared under a test cfg)] of the `mod x;` lines of a file."""
out = []
attrs = []
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("#[") or (attrs and _unbalanced(" ".join(attrs))):
attrs.append(stripped)
continue
decl = _MOD_LINE.match(stripped)
if decl:
block = " ".join(attrs)
explicit = _PATH_ATTR.search(block)
out.append((decl.group(1), explicit.group(1) if explicit else None, _is_test_cfg(block)))
attrs = []
return out
def _unbalanced(text):
return text.count("[") > text.count("]") or text.count("(") > text.count(")")
def _is_test_cfg(block):
return "cfg(" in block and re.search(r"\btest\b", block) is not None and "not(test" not in block
def _module_file(declaring, name, explicit):
here = declaring.parent
if explicit:
target = (here / explicit).resolve()
return target if target.is_file() else None
base = here if declaring.name in ("lib.rs", "main.rs", "mod.rs") else here / declaring.stem
for candidate in (base / f"{name}.rs", base / name / "mod.rs"):
if candidate.is_file():
return candidate.resolve()
return None
def _under_test_module(path, test_files):
"""The file itself or a file in the directory a test-only module owns (`x.rs` owns `x/`, `mod.rs` its folder)."""
resolved = path.resolve()
for owner in test_files:
folder = owner.parent if owner.name == "mod.rs" else owner.with_suffix("")
if resolved == owner or resolved.is_relative_to(folder):
return True
return False
def _package_counts(src, compiled):
totals = {}
if not src.is_dir():
return totals
test_files = test_only_modules(src)
for path in rust_files(src):
if is_test_file(path, src) or _under_test_module(path, test_files):
continue
rows = production_lines(_text(path))
for pid, rx in compiled:
n = sum(len(rx.findall(row)) for row in rows)
if n:
totals[pid] = totals.get(pid, 0) + n
return totals
+190 -189
View File
@@ -1,189 +1,190 @@
#!/usr/bin/env python3
"""Negative and positive proofs for the architecture gate: each rule must fail on a synthetic violation.
Usage: python3 scripts/check_architecture_test.py (no cargo, no network)
"""
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from archcheck import baseline as bl # noqa: E402
from archcheck import measure, rules # noqa: E402
CONFIG = {
"max_lines": 400,
"adapter_layer": "L3",
"pure_layers": ["L0", "L1"],
"forbidden_in_pure": ["tokio"],
"layers": {"L0": ["api"], "L1": ["lib"], "L2": ["core"], "L3": ["adapter-a", "adapter-b"], "L4": ["host"]},
"adapter_edges": [["adapter-b", "adapter-a"]],
}
EMPTY = {"violations": [], "oversize": {}, "source": {}}
def pkg(name, normal=(), external=()):
return {"name": name, "dir": pathlib.Path(name), "normal": list(normal), "external": list(external)}
def packages(**overrides):
base = {
"api": pkg("api"), "lib": pkg("lib", ["api"]), "core": pkg("core", ["lib"]),
"adapter-a": pkg("adapter-a", ["core"]), "adapter-b": pkg("adapter-b", ["core", "adapter-a"]),
"host": pkg("host", ["adapter-a", "adapter-b", "core"]),
}
base.update(overrides)
return list(base.values())
def run(pkgs, baseline=None, sizes=None, counts=None):
return rules.evaluate(pkgs, CONFIG, baseline or EMPTY, sizes or {}, counts or {})
def base(violations=(), oversize=None, source=None):
return {"violations": list(violations), "oversize": oversize or {}, "source": source or {}}
class GraphRules(unittest.TestCase):
def test_clean_graph_passes(self):
found = run(packages())
self.assertEqual((found.errors, found.debt, found.stale), ([], [], []))
def test_upward_edge_fails(self):
found = run(packages(core=pkg("core", ["host"])))
self.assertIn("layer-up core -> host", found.violations)
self.assertEqual(len(found.errors), 1)
def test_core_may_not_depend_on_an_adapter(self):
found = run(packages(core=pkg("core", ["adapter-a"])))
self.assertTrue(any("core (L2) depends on adapter-a (L3)" in e for e in found.errors))
def test_sideways_adapter_edge_fails_unless_listed(self):
found = run(packages(**{"adapter-a": pkg("adapter-a", ["adapter-b"])}))
self.assertIn("adapter-sideways adapter-a -> adapter-b", found.violations)
self.assertEqual(run(packages()).errors, [])
def test_unassigned_package_fails(self):
found = run(packages(extra=pkg("extra")))
self.assertTrue(any("extra has no layer" in e for e in found.errors))
def test_pure_crate_with_forbidden_dependency_fails_but_an_adapter_may_use_it(self):
found = run(packages(lib=pkg("lib", ["api"], ["tokio"])))
self.assertIn("forbidden-dep lib tokio", found.violations)
self.assertEqual(run(packages(**{"adapter-a": pkg("adapter-a", ["core"], ["tokio"])})).errors, [])
def test_baselined_violation_is_debt_and_a_fixed_one_is_stale(self):
known = base(violations=["layer-up core -> host"])
found = run(packages(core=pkg("core", ["host"])), known)
self.assertEqual((found.errors, found.debt), ([], ["layer-up core -> host"]))
self.assertEqual(len(run(packages(), known).stale), 1)
class SizeAndRatchetRules(unittest.TestCase):
def test_new_large_file_fails_and_a_file_at_the_limit_passes(self):
self.assertEqual(len(run(packages(), sizes={"big.rs": 401}).errors), 1)
self.assertEqual(run(packages(), sizes={"ok.rs": 400}).errors, [])
def test_baselined_large_file_may_not_grow_and_shrinking_is_stale(self):
known = base(oversize={"big.rs": 900})
self.assertEqual(run(packages(), known, {"big.rs": 900}).errors, [])
self.assertEqual(len(run(packages(), known, {"big.rs": 901}).errors), 1)
self.assertEqual(len(run(packages(), known, {"big.rs": 700}).stale), 1)
def test_ratchet_may_only_fall(self):
known = base(source={"env-read:host": 10})
self.assertEqual(run(packages(), known, counts={"env-read:host": 10}).errors, [])
self.assertEqual(len(run(packages(), known, counts={"env-read:host": 11}).errors), 1)
self.assertEqual(len(run(packages(), known, counts={"env-read:host": 9}).stale), 1)
def test_new_ratchet_key_starts_at_zero(self):
self.assertEqual(len(run(packages(), counts={"env-read:host": 1}).errors), 1)
class BaselineRewrite(unittest.TestCase):
def test_refuses_increase_and_accepts_decrease(self):
old = base(oversize={"a.rs": 500}, source={"env-read:host": 3})
higher = base(["layer-up a -> b"], {"a.rs": 501}, {"env-read:host": 4})
self.assertEqual(len(bl.raised(old, higher)), 3)
self.assertEqual(bl.raised(old, base(oversize={"a.rs": 450}, source={"env-read:host": 2})), [])
def test_code_that_moved_between_crates_keeps_its_total(self):
old = base(source={"env-read:host": 3})
self.assertEqual(bl.raised(old, base(source={"env-read:other": 3})), [])
def test_a_moved_file_is_accepted_but_a_new_large_one_is_not(self):
old = base(oversize={"src/a.rs": 500})
self.assertEqual(bl.raised(old, base(oversize={"src/sub/a.rs": 500})), [])
self.assertEqual(len(bl.raised(old, base(oversize={"src/sub/a.rs": 501}))), 1)
self.assertEqual(len(bl.raised(old, base(oversize={"src/a.rs": 500, "src/b.rs": 450}))), 1)
def test_a_split_may_add_only_its_module_declaration(self):
old = base(oversize={"src/big.rs": 1000})
self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 503, "src/big/tests.rs": 500})), [])
def test_a_split_into_a_same_stem_directory_may_not_gain_lines(self):
old = base(oversize={"src/big.rs": 1000})
self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 500, "src/big/part.rs": 480})), [])
self.assertEqual(len(bl.raised(old, base(oversize={"src/big.rs": 600, "src/big/part.rs": 480}))), 1)
class Measurement(unittest.TestCase):
def test_counter_stops_at_a_test_module_and_skips_comments(self):
text = 'let a = std::env::var("A");\n// env::var("B")\n#[cfg(test)]\nmod t {}\nlet c = env::var("C");\n'
self.assertEqual(measure.production_lines(text), ['let a = std::env::var("A");'])
def test_a_single_cfg_test_function_does_not_hide_the_code_after_it(self):
text = '#[cfg(test)]\nfn only_tests() {}\nlet a = env::var("A");\n'
self.assertEqual(len(measure.production_lines(text)), 3)
def test_an_inline_module_under_another_test_cfg_is_skipped_but_the_code_after_it_counts(self):
text = ('let a = env::var("A");\n#[cfg(all(test, unix))]\nmod proof {\n let b = env::var("B");\n}\n'
'#[cfg(not(test))]\nmod live {\n let c = env::var("C");\n}\nlet d = env::var("D");\n')
rows = measure.production_lines(text)
self.assertEqual([r for r in rows if "env::var" in r], [
'let a = env::var("A");', ' let c = env::var("C");', 'let d = env::var("D");'])
def test_a_module_declared_inside_a_test_only_file_is_not_production_either(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
(src / "proofs" / "top").mkdir(parents=True)
(src / "lib.rs").write_text('let a = env::var("A");\n#[cfg(test)]\n#[path = "proofs/top.rs"]\nmod top;\n')
(src / "proofs" / "top.rs").write_text('#[path = "nested.rs"]\nmod nested;\nmod sibling;\nlet b = env::var("B");\n')
(src / "proofs" / "nested.rs").write_text('let c = env::var("C");\n')
(src / "proofs" / "top" / "sibling.rs").write_text('let d = env::var("D");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 1})
def test_counts_are_per_crate_and_skip_test_files(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
src.mkdir()
(src / "lib.rs").write_text('let a = env::var("A");\n')
(src / "tests.rs").write_text('let b = env::var("B");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 1})
def test_modules_declared_under_a_test_cfg_are_not_production(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
(src / "a" / "proofs").mkdir(parents=True)
(src / "lib.rs").write_text('mod a;\nmod b;\nlet a = env::var("A");\n')
(src / "b.rs").write_text('let b = env::var("B");\n')
(src / "a.rs").write_text(
'let c = env::var("C");\n#[cfg(not(test))]\nmod live;\n'
'#[cfg(all(\n test,\n target_os = "linux"\n))]\n#[path = "a/proofs/x.rs"]\nmod proof;\n'
'#[cfg(test)]\nmod helper;\n')
(src / "a" / "proofs" / "x.rs").write_text('let d = env::var("D");\n')
(src / "a" / "helper.rs").write_text('let e = env::var("E");\n')
(src / "a" / "live.rs").write_text('let f = env::var("F");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 4})
if __name__ == "__main__":
unittest.main()
#!/usr/bin/env python3
"""Negative and positive proofs for the architecture gate: each rule must fail on a synthetic violation.
Usage: python3 scripts/check_architecture_test.py (no cargo, no network)
"""
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from archcheck import baseline as bl # noqa: E402
from archcheck import measure, rules # noqa: E402
CONFIG = {
"max_lines": 400,
"adapter_layer": "L3",
"pure_layers": ["L0", "L1"],
"forbidden_in_pure": ["tokio"],
"layers": {"L0": ["api"], "L1": ["lib"], "L2": ["core"], "L3": ["adapter-a", "adapter-b"], "L4": ["host"]},
"adapter_edges": [["adapter-b", "adapter-a"]],
}
EMPTY = {"violations": [], "oversize": {}, "source": {}}
def pkg(name, normal=(), external=()):
return {"name": name, "dir": pathlib.Path(name), "normal": list(normal), "external": list(external)}
def packages(**overrides):
base = {
"api": pkg("api"), "lib": pkg("lib", ["api"]), "core": pkg("core", ["lib"]),
"adapter-a": pkg("adapter-a", ["core"]), "adapter-b": pkg("adapter-b", ["core", "adapter-a"]),
"host": pkg("host", ["adapter-a", "adapter-b", "core"]),
}
base.update(overrides)
return list(base.values())
def run(pkgs, baseline=None, sizes=None, counts=None):
return rules.evaluate(pkgs, CONFIG, baseline or EMPTY, sizes or {}, counts or {})
def base(violations=(), oversize=None, source=None):
return {"violations": list(violations), "oversize": oversize or {}, "source": source or {}}
class GraphRules(unittest.TestCase):
def test_clean_graph_passes(self):
found = run(packages())
self.assertEqual((found.errors, found.debt, found.stale), ([], [], []))
def test_upward_edge_fails(self):
found = run(packages(core=pkg("core", ["host"])))
self.assertIn("layer-up core -> host", found.violations)
self.assertEqual(len(found.errors), 1)
def test_core_may_not_depend_on_an_adapter(self):
found = run(packages(core=pkg("core", ["adapter-a"])))
self.assertTrue(any("core (L2) depends on adapter-a (L3)" in e for e in found.errors))
def test_sideways_adapter_edge_fails_unless_listed(self):
found = run(packages(**{"adapter-a": pkg("adapter-a", ["adapter-b"])}))
self.assertIn("adapter-sideways adapter-a -> adapter-b", found.violations)
self.assertEqual(run(packages()).errors, [])
def test_unassigned_package_fails(self):
found = run(packages(extra=pkg("extra")))
self.assertTrue(any("extra has no layer" in e for e in found.errors))
def test_pure_crate_with_forbidden_dependency_fails_but_an_adapter_may_use_it(self):
found = run(packages(lib=pkg("lib", ["api"], ["tokio"])))
self.assertIn("forbidden-dep lib tokio", found.violations)
self.assertEqual(run(packages(**{"adapter-a": pkg("adapter-a", ["core"], ["tokio"])})).errors, [])
def test_baselined_violation_is_debt_and_a_fixed_one_is_stale(self):
known = base(violations=["layer-up core -> host"])
found = run(packages(core=pkg("core", ["host"])), known)
self.assertEqual((found.errors, found.debt), ([], ["layer-up core -> host"]))
self.assertEqual(len(run(packages(), known).stale), 1)
class SizeAndRatchetRules(unittest.TestCase):
def test_new_large_file_fails_and_a_file_at_the_limit_passes(self):
self.assertEqual(len(run(packages(), sizes={"big.rs": 401}).errors), 1)
self.assertEqual(run(packages(), sizes={"ok.rs": 400}).errors, [])
def test_baselined_large_file_may_not_grow_and_shrinking_is_stale(self):
known = base(oversize={"big.rs": 900})
self.assertEqual(run(packages(), known, {"big.rs": 900}).errors, [])
self.assertEqual(len(run(packages(), known, {"big.rs": 901}).errors), 1)
self.assertEqual(len(run(packages(), known, {"big.rs": 700}).stale), 1)
def test_ratchet_may_only_fall(self):
known = base(source={"env-read:host": 10})
self.assertEqual(run(packages(), known, counts={"env-read:host": 10}).errors, [])
self.assertEqual(len(run(packages(), known, counts={"env-read:host": 11}).errors), 1)
self.assertEqual(len(run(packages(), known, counts={"env-read:host": 9}).stale), 1)
def test_new_ratchet_key_starts_at_zero(self):
self.assertEqual(len(run(packages(), counts={"env-read:host": 1}).errors), 1)
class BaselineRewrite(unittest.TestCase):
def test_refuses_increase_and_accepts_decrease(self):
old = base(oversize={"a.rs": 500}, source={"env-read:host": 3})
higher = base(["layer-up a -> b"], {"a.rs": 501}, {"env-read:host": 4})
self.assertEqual(len(bl.raised(old, higher)), 3)
self.assertEqual(bl.raised(old, base(oversize={"a.rs": 450}, source={"env-read:host": 2})), [])
def test_code_that_moved_between_crates_keeps_its_total(self):
old = base(source={"env-read:host": 3})
self.assertEqual(bl.raised(old, base(source={"env-read:other": 3})), [])
def test_a_moved_file_is_accepted_but_a_new_large_one_is_not(self):
old = base(oversize={"src/a.rs": 500})
self.assertEqual(bl.raised(old, base(oversize={"src/sub/a.rs": 500})), [])
self.assertEqual(len(bl.raised(old, base(oversize={"src/sub/a.rs": 501}))), 1)
self.assertEqual(len(bl.raised(old, base(oversize={"src/a.rs": 500, "src/b.rs": 450}))), 1)
def test_a_split_may_add_only_its_module_declaration(self):
old = base(oversize={"src/big.rs": 1000})
self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 503, "src/big/tests.rs": 500})), [])
def test_a_split_into_a_same_stem_directory_may_not_gain_lines(self):
old = base(oversize={"src/big.rs": 1000})
self.assertEqual(bl.raised(old, base(oversize={"src/big.rs": 500, "src/big/part.rs": 480})), [])
self.assertEqual(len(bl.raised(old, base(oversize={"src/big.rs": 600, "src/big/part.rs": 480}))), 1)
class Measurement(unittest.TestCase):
def test_counter_stops_at_a_test_module_and_skips_comments(self):
text = 'let a = std::env::var("A");\n// env::var("B")\n#[cfg(test)]\nmod t {}\nlet c = env::var("C");\n'
self.assertEqual(measure.production_lines(text), ['let a = std::env::var("A");'])
def test_a_single_cfg_test_function_does_not_hide_the_code_after_it(self):
text = '#[cfg(test)]\nfn only_tests() {}\nlet a = env::var("A");\n'
self.assertEqual(len(measure.production_lines(text)), 3)
def test_an_inline_module_under_another_test_cfg_is_skipped_but_the_code_after_it_counts(self):
text = ('let a = env::var("A");\n#[cfg(all(test, unix))]\nmod proof {\n let b = env::var("B");\n}\n'
'#[cfg(not(test))]\nmod live {\n let c = env::var("C");\n}\nlet d = env::var("D");\n')
rows = measure.production_lines(text)
self.assertEqual([r for r in rows if "env::var" in r], [
'let a = env::var("A");', ' let c = env::var("C");', 'let d = env::var("D");'])
def test_a_module_declared_inside_a_test_only_file_is_not_production_either(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
(src / "proofs" / "top").mkdir(parents=True)
(src / "lib.rs").write_text('let a = env::var("A");\n#[cfg(test)]\n#[path = "proofs/top.rs"]\nmod top;\n')
top = '#[path = "nested.rs"]\nmod nested;\nmod sibling;\nlet b = env::var("B");\n'
(src / "proofs" / "top.rs").write_text(top)
(src / "proofs" / "nested.rs").write_text('let c = env::var("C");\n')
(src / "proofs" / "top" / "sibling.rs").write_text('let d = env::var("D");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 1})
def test_counts_are_per_crate_and_skip_test_files(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
src.mkdir()
(src / "lib.rs").write_text('let a = env::var("A");\n')
(src / "tests.rs").write_text('let b = env::var("B");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 1})
def test_modules_declared_under_a_test_cfg_are_not_production(self):
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp) / "src"
(src / "a" / "proofs").mkdir(parents=True)
(src / "lib.rs").write_text('mod a;\nmod b;\nlet a = env::var("A");\n')
(src / "b.rs").write_text('let b = env::var("B");\n')
(src / "a.rs").write_text(
'let c = env::var("C");\n#[cfg(not(test))]\nmod live;\n'
'#[cfg(all(\n test,\n target_os = "linux"\n))]\n#[path = "a/proofs/x.rs"]\nmod proof;\n'
'#[cfg(test)]\nmod helper;\n')
(src / "a" / "proofs" / "x.rs").write_text('let d = env::var("D");\n')
(src / "a" / "helper.rs").write_text('let e = env::var("E");\n')
(src / "a" / "live.rs").write_text('let f = env::var("F");\n')
package = dict(pkg("p"), dir=pathlib.Path(tmp))
counts = measure.count_patterns([package], [{"id": "e", "regex": r"env::var\("}])
self.assertEqual(counts, {"e:p": 4})
if __name__ == "__main__":
unittest.main()