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
+41 -33

No files matched your search

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