Files
leleka/scripts/archcheck/rules.py
T
Pavlo Ratushnyi 52d554e72c STRA-338 S6 part 2: SSE streaming leaves responses.rs; architecture gate rewritten to the 301 limits
The text, buffered and tool-call streaming code of the Responses API (750 lines) moves from control-plane/src/responses.rs to responses/stream.rs without a logic change, and the architecture gate becomes a small package (scripts/archcheck) whose functions stay within 30 lines, complexity 10, nesting 4 and 5 parameters.

The source counters now stop only at a column-0 cfg(test) module, so a single cfg(test) function no longer hides the code after it; that raises some measured baselines (cuda-driver, runtime, model-format, strata-control) without any code change, and the baseline was rewritten using --allow-increase for that reason alone.

Verified: cargo test -p strata-control 277 lib tests, 0 failed; 18 gate self-tests pass; fmt clean.
2026-11-05 13:47:14 +01:00

130 lines
5.7 KiB
Python

"""The rules, as pure functions over plain data (no cargo, no file system)."""
from dataclasses import dataclass, field
@dataclass
class Findings:
errors: list = field(default_factory=list)
debt: list = field(default_factory=list)
stale: list = field(default_factory=list)
violations: dict = field(default_factory=dict)
def layer_index(config):
"""{package: [layers]}; a package listed twice is reported by `assignment_errors`."""
index = {}
for layer, names in config["layers"].items():
for name in names:
index.setdefault(name, []).append(layer)
return index
def assignment_errors(packages, config):
"""Every workspace package must have exactly one layer, and every listed name must be a package."""
layers, known, errors = layer_index(config), {p["name"] for p in packages}, []
for name, assigned in sorted(layers.items()):
if len(assigned) > 1:
errors.append(f"{name} is assigned to more than one layer: {assigned}")
if name not in known:
errors.append(f"{name} has a layer in architecture.json but is not a workspace package")
order = list(config["layers"])
errors += [f"{p['name']} has no layer in architecture.json: assign it to one of {order}"
for p in packages if p["name"] not in layers]
return errors
def edge_violations(pkg, config):
"""{key: message} for the layer and adapter edges of one package."""
layers = layer_index(config)
rank = {layer: i for i, layer in enumerate(config["layers"])}
name, mine = pkg["name"], layers[pkg["name"]][0]
sideways = {tuple(e) for e in config["adapter_edges"]}
found = {}
for dep in (d for d in pkg["normal"] if d in layers):
theirs = layers[dep][0]
if rank[theirs] > rank[mine]:
found[f"layer-up {name} -> {dep}"] = f"{name} ({mine}) depends on {dep} ({theirs})"
elif mine == theirs == config["adapter_layer"] and (name, dep) not in sideways:
found[f"adapter-sideways {name} -> {dep}"] = (
f"adapter {name} depends on adapter {dep}; list the edge in adapter_edges only if it is a real port")
return found
def purity_violations(pkg, config):
"""{key: message} for forbidden external crates in a pure layer."""
name, layer = pkg["name"], layer_index(config)[pkg["name"]][0]
if layer not in config["pure_layers"]:
return {}
banned = set(config["forbidden_in_pure"])
return {f"forbidden-dep {name} {ext}": f"{name} ({layer}) must stay pure but uses {ext}"
for ext in pkg["external"] if ext in banned}
def graph_violations(packages, config):
"""All layer, adapter and purity violations of the workspace."""
layers, found = layer_index(config), {}
for pkg in (p for p in packages if p["name"] in layers):
found.update(edge_violations(pkg, config))
found.update(purity_violations(pkg, config))
return found
def classify(violations, baseline):
"""Split violations into new errors and baselined debt; report baseline entries that no longer apply."""
known = set(baseline["violations"])
errors = [message for key, message in sorted(violations.items()) if key not in known]
debt = [key for key in sorted(violations) if key in known]
stale = [f"violation no longer present: {key}" for key in baseline["violations"] if key not in violations]
return errors, debt, stale
def _size_error(path, lines, allowed, limit):
if allowed is None:
return f"{path} has {lines} lines (limit {limit}); split it instead of adding a new large file"
if lines > allowed:
return f"{path} grew to {lines} lines (baseline {allowed}); large files may only shrink"
return None
def _size_stale(path, allowed, now, limit):
if now is None:
return f"oversize entry for a file that is gone: {path}"
if now <= limit:
return f"{path} is now {now} lines, under the limit: drop its baseline entry"
if now < allowed:
return f"{path} shrank from {allowed} to {now} lines: tighten the baseline"
return None
def size_findings(sizes, baseline, limit):
"""(errors, stale) for the per-file line limit and the per-file non-growth rule."""
errors = [_size_error(p, n, baseline["oversize"].get(p), limit) for p, n in sorted(sizes.items()) if n > limit]
stale = [_size_stale(p, allowed, sizes.get(p), limit) for p, allowed in baseline["oversize"].items()]
return [e for e in errors if e], [s for s in stale if s]
def ratchet_findings(counts, baseline):
"""(errors, stale) for source pattern counts, which may only fall."""
errors, stale = [], []
for key, n in sorted(counts.items()):
allowed = baseline["source"].get(key, 0)
if n > allowed:
errors.append(f"source ratchet {key} rose to {n} (baseline {allowed}); the count may only fall")
elif n < allowed:
stale.append(f"source ratchet {key} fell from {allowed} to {n}: tighten the baseline")
stale += [f"source ratchet {key} is now 0 (baseline {allowed}): tighten the baseline"
for key, allowed in baseline["source"].items() if key not in counts]
return errors, stale
def evaluate(packages, config, baseline, sizes, counts):
"""Run every rule. Returns Findings."""
result = Findings(errors=assignment_errors(packages, config))
result.violations = graph_violations(packages, config)
errors, result.debt, stale = classify(result.violations, baseline)
size_errors, size_stale = size_findings(sizes, baseline, config["max_lines"])
ratchet_errors, ratchet_stale = ratchet_findings(counts, baseline)
result.errors += errors + size_errors + ratchet_errors
result.stale = stale + size_stale + ratchet_stale
return result