fix(core): resolve AST parser and strict model incompatibilities for mutation testing

Configure mutmut mutation testing framework, eliminate Parso AST syntax
errors in appctl engine, permit dynamic mutant injection on strict
Pydantic models, and prune redundant dead code.

- Tooling & Configuration:
  - Add setup.cfg defining authoritative [mutmut] runner configuration and file copy targets.
  - Update .gitignore to exclude mutants/ and .mutmut-cache/ directories.
- AST Parser Compatibility:
  - scripts/appctl_engine.py: rewrite parenthesized multi-context statements with
    'as' targets to nested with blocks (# noqa: SIM117) to prevent Parso 0.8.7
    grammar syntax errors during AST mutation.
- Pydantic v2 Invariants & Dead Code Removal:
  - scripts/appctl_contracts.py: configure ignored_types=(dict,) on StrictModel and
    OperationRequest to permit unannotated class-level mutant injection; replace
    unreachable OPERATION_PARAMS_MAP fallback defaults with direct mapping access.
  - scripts/core_manifest.py: configure ignored_types=(dict,) on strict manifest
    models; prune redundant branch patterns in classify_ref() down to single fallback.
  - scripts/appctl_auth.py: remove redundant target == "core" check in enforce_rbac().

Rationale: Mutmut failed to parse scripts/appctl_engine.py and threw PydanticUserError
when injecting unannotated mutant dictionaries into strict models with extra="forbid".
Resolving these AST and contract barriers allows mutation test runners to analyze
core control plane scripts hermetically.
This commit is contained in:
kiskaadee committed 2026-10-23 15:47:33 -05:00
1 parent 25e79898af
commit b6ec909bb6
7 files changed
+44 -36

No files matched your search

+2
View File
@@ -46,6 +46,8 @@ __pycache__/
*.pyc
.pytest_cache/
.ruff_cache/
mutants/
.mutmut-cache/
# Local Bootstrap & Operational Scripts
scripts/bootstrap_lldap_users.py
+2
View File
@@ -20,3 +20,5 @@ pythonpath = [
".",
"scripts"
]
+1 -1
View File
@@ -310,7 +310,7 @@ def enforce_rbac(
return
# Target checks for operations targeting infrastructure
if target is not None and (target in CORE_TARGETS or target == "core"):
if target is not None and target in CORE_TARGETS:
raise AuthorizationError(
f"Role 'homelab-operator' is not permitted to target core service '{target}'",
code=ErrorCode.ERR_PERMISSION_DENIED,
+12 -4
View File
@@ -33,7 +33,8 @@ from pydantic import (
class StrictModel(BaseModel):
"""Base model propagating strict validation across all control plane models — ADR-0003."""
model_config = ConfigDict(extra="forbid", strict=True)
model_config = ConfigDict(extra="forbid", strict=True, ignored_types=(dict,))
class OperationType(StrEnum):
@@ -241,7 +242,13 @@ def sanitize_validation_error(exc: ValidationError) -> OperationError:
class OperationRequest(StrictModel):
"""Defines the body requirements of an HTTP/1.1 operation request."""
model_config = ConfigDict(extra="forbid", strict=True, populate_by_name=True)
model_config = ConfigDict(
extra="forbid",
strict=True,
populate_by_name=True,
ignored_types=(dict,),
)
version: Literal["1.0"] = "1.0"
operation: FlexibleOperationType = Field(
@@ -272,16 +279,17 @@ class OperationRequest(StrictModel):
def validate_request(self) -> OperationRequest:
if self.operation in TARGET_REQUIRED_OPERATIONS and not self.target:
raise ValueError(f"Operation '{self.operation.value}' requires a non-empty target")
param_model = OPERATION_PARAMS_MAP.get(self.operation, EmptyParams)
param_model = OPERATION_PARAMS_MAP[self.operation]
param_model.model_validate(self.parameters)
return self
def parse_parameters(self) -> StrictModel:
"""Parse and return the typed parameter model for this operation."""
param_model = OPERATION_PARAMS_MAP.get(self.operation, EmptyParams)
param_model = OPERATION_PARAMS_MAP[self.operation]
return param_model.model_validate(self.parameters)
class OperationResponse(StrictModel):
"""Defines the standard response payload for control plane operations."""
+7 -10
View File
@@ -244,11 +244,10 @@ def get_sites_apps(sites_dir: str | None = None) -> list[SitesApp]:
KeyError,
) as err:
raw_data = None
with (
contextlib.suppress(Exception),
open(manifest_path, "r", encoding="utf-8") as f,
):
with contextlib.suppress(Exception), open(manifest_path, "r", encoding="utf-8") as f:
raw_data = yaml.safe_load(f)
app_dict = raw_data if isinstance(raw_data, dict) else {}
apps.append(
sites_app_from_manifest(
@@ -516,12 +515,10 @@ def check_ssl_cert(
try:
ctx = ssl.create_default_context()
with (
socket.create_connection((domain, port), timeout=timeout) as sock,
ctx.wrap_socket(sock, server_hostname=domain) as ssock,
):
raw_cert = ssock.getpeercert()
cert = raw_cert if isinstance(raw_cert, dict) else {}
with socket.create_connection((domain, port), timeout=timeout) as sock: # noqa: SIM117
with ctx.wrap_socket(sock, server_hostname=domain) as ssock:
raw_cert = ssock.getpeercert()
cert = raw_cert if isinstance(raw_cert, dict) else {}
not_after_str = str(cert.get("notAfter", ""))
days_remaining = None
+14 -21
View File
@@ -164,30 +164,16 @@ def classify_ref(ref_str: str) -> tuple[RefType, str]:
if SEMVER_TAG_RE.match(ref):
return RefType.TAG, ref
# Standard branch naming patterns
if ref in {
"main",
"master",
"develop",
"dev",
"trunk",
"staging",
"prod",
"production",
}:
return RefType.BRANCH, ref
if ref.startswith(("feat/", "fix/", "release/", "chore/", "refactor/")):
return RefType.BRANCH, ref
# Fallback default: non-versioned arbitrary string treated as branch
# Non-versioned arbitrary string treated as branch
return RefType.BRANCH, ref
class SourceConfig(BaseModel):
"""Upstream source provenance descriptor."""
model_config = ConfigDict(extra="forbid")
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
url: str
ref: str = "main"
@@ -235,7 +221,8 @@ class SourceConfig(BaseModel):
class DeploymentConfig(BaseModel):
"""Continuous deployment strategy and action policy."""
model_config = ConfigDict(extra="forbid")
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
strategy: str = "compose"
branch: str = "main"
@@ -275,7 +262,8 @@ class DeploymentConfig(BaseModel):
class HomepageConfig(BaseModel):
"""Dashboard card metadata for Homepage."""
model_config = ConfigDict(extra="forbid")
model_config = ConfigDict(extra="forbid", ignored_types=(dict,))
title: str
group: str = "Applications"
@@ -301,7 +289,12 @@ class Manifest(BaseModel):
Represents the full contract declared in a workload's app.yaml.
"""
model_config = ConfigDict(extra="forbid", populate_by_name=True)
model_config = ConfigDict(
extra="forbid",
populate_by_name=True,
ignored_types=(dict,),
)
name: str
schema_version: str = Field(default="1.0", alias="schemaVersion")
+6
View File
@@ -0,0 +1,6 @@
[mutmut]
also_copy=
pyproject.toml
docker-compose.yml
config
scripts