From cff8b36c1af500833bde0042a9d501464435cbe7 Mon Sep 17 00:00:00 2001 From: ephico2real2 Date: Tue, 1 Dec 2026 09:08:36 -0600 Subject: [PATCH 1/3] #256, #258: quotaBelowRequested reads the pods' live use; the team label is metadata-keys.yaml teamKey #256: TierCatalog.compare takes the use, and neither caller passed it, so quotaBelowRequested was always false. Pipeline.quota_used reads the status.used of the live ResourceQuota that Git's quota is, from the watch cache that the capacity check reads, and the plan and the revert pass it. A key that the change lowers and whose use cannot be read (no live quota, a watch that has not listed, is stale or refused) counts as below: fail closed, logged quota_used_unknown. A key that the change does not lower never does. #258: cmapi.net/team was hard-coded for placement, the fact team, the daily allowance per team, change_requests.team and the list views. The new stanza teamKey names the label, cmapi.net/team by default; a named key must be a declared label. The company example names company.net/mnemonic. Contract, portal types, Helm schema, docs/02, docs/18 and the glossary follow. --- cmapi-portal-ui/src/api/schema.generated.ts | 10 +- cmapi/contract/openapi.json | 16 ++-- cmapi/src/cmapi/core/metadata.py | 37 +++++++- cmapi/src/cmapi/core/models.py | 8 +- cmapi/src/cmapi/core/pipeline.py | 56 +++++++++-- cmapi/src/cmapi/core/problem_docs.py | 2 +- cmapi/src/cmapi/core/tiers.py | 24 +++-- cmapi/src/cmapi/jobs/open_pr.py | 2 +- cmapi/src/cmapi/plugins/capacity/placement.py | 7 +- cmapi/src/cmapi/plugins/expiration/router.py | 4 +- cmapi/src/cmapi/plugins/namespaces/router.py | 2 +- cmapi/src/cmapi/plugins/quotas/__init__.py | 4 +- cmapi/src/cmapi/routers/__init__.py | 2 +- .../core/test_quota_below_requested_256.py | 54 +++++++++++ cmapi/tests/core/test_team_key_258.py | 73 +++++++++++++++ .../service/test_helm_metadata_values.py | 2 +- .../service/test_quota_below_requested_256.py | 93 +++++++++++++++++++ cmapi/tests/service/test_team_key_258.py | 50 ++++++++++ deploy/helm/cmapi/config/metadata-keys.yaml | 3 + deploy/helm/cmapi/values.schema.json | 4 +- deploy/helm/cmapi/values.yaml | 2 +- docs/02-technical-design-v2.md | 6 +- docs/14-authorization.md | 8 +- docs/18-configuration.md | 15 +-- docs/21-usage-from-thanos.md | 4 +- docs/GLOSSARY.md | 2 + docs/citations.lock.json | 10 +- .../policies/metadata-keys.company.yaml | 3 + .../policies/metadata-keys.yaml | 3 + 29 files changed, 440 insertions(+), 66 deletions(-) create mode 100644 cmapi/tests/core/test_quota_below_requested_256.py create mode 100644 cmapi/tests/core/test_team_key_258.py create mode 100644 cmapi/tests/service/test_quota_below_requested_256.py create mode 100644 cmapi/tests/service/test_team_key_258.py diff --git a/cmapi-portal-ui/src/api/schema.generated.ts b/cmapi-portal-ui/src/api/schema.generated.ts index 34deaf86..3de44ef6 100644 --- a/cmapi-portal-ui/src/api/schema.generated.ts +++ b/cmapi-portal-ui/src/api/schema.generated.ts @@ -3647,7 +3647,7 @@ export interface components { sync: components["schemas"]["NamespaceSync"]; /** * Team - * @description cmapi.net/team + * @description The team: the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default * @example payments */ team: string | null; @@ -3938,7 +3938,7 @@ export interface components { } | null; /** * Team - * @description The team the namespace is for: the create's `cmapi.net/team` label must be the same. Left out on an instance whose metadata keys have no team label; the cap of 3 active placements is then the caller's own + * @description The team the namespace is for: the create's team label (metadata-keys.yaml `teamKey`, `cmapi.net/team` by default) must be the same. Left out on an instance whose metadata keys have no team label; the cap of 3 active placements is then the caller's own * @example payments */ team?: string | null; @@ -11551,7 +11551,7 @@ export interface operations { env?: string | null; /** @description Only the namespaces on this cluster. */ clusterId?: string | null; - /** @description Only the namespaces of this team (`cmapi.net/team`). */ + /** @description Only the namespaces of this team (the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default). */ team?: string | null; /** @description Only the namespaces in one state: `permanent`, `active`, `expiring`, `grace` or `pending_delete`, or `attention` for the three that need action (expiring, grace and pending_delete). Another value returns 422 `validation-failed`. */ state?: string | null; @@ -13310,7 +13310,7 @@ export interface operations { env?: string | null; /** @description Only the namespaces on this cluster. */ clusterId?: string | null; - /** @description Only the namespaces of this team (`cmapi.net/team`). */ + /** @description Only the namespaces of this team (the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default). */ team?: string | null; /** @description Only the namespaces of this tier (`cmapi.net/tier`). */ tier?: string | null; @@ -13491,7 +13491,7 @@ export interface operations { env?: string | null; /** @description Only the namespaces on this cluster. */ clusterId?: string | null; - /** @description Only the namespaces of this team (`cmapi.net/team`). */ + /** @description Only the namespaces of this team (the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default). */ team?: string | null; /** @description Only the namespaces of this tier (`cmapi.net/tier`). */ tier?: string | null; diff --git a/cmapi/contract/openapi.json b/cmapi/contract/openapi.json index 228d2d57..943b974a 100644 --- a/cmapi/contract/openapi.json +++ b/cmapi/contract/openapi.json @@ -5449,7 +5449,7 @@ "type": "null" } ], - "description": "cmapi.net/team", + "description": "The team: the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default", "examples": [ "payments" ], @@ -6077,7 +6077,7 @@ "type": "null" } ], - "description": "The team the namespace is for: the create's `cmapi.net/team` label must be the same. Left out on an instance whose metadata keys have no team label; the cap of 3 active placements is then the caller's own", + "description": "The team the namespace is for: the create's team label (metadata-keys.yaml `teamKey`, `cmapi.net/team` by default) must be the same. Left out on an instance whose metadata keys have no team label; the cap of 3 active placements is then the caller's own", "examples": [ "payments" ], @@ -20260,7 +20260,7 @@ } }, { - "description": "Only the namespaces of this team (`cmapi.net/team`).", + "description": "Only the namespaces of this team (the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default).", "in": "query", "name": "team", "required": false, @@ -20273,7 +20273,7 @@ "type": "null" } ], - "description": "Only the namespaces of this team (`cmapi.net/team`).", + "description": "Only the namespaces of this team (the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default).", "examples": [ "payments" ], @@ -22905,7 +22905,7 @@ } }, { - "description": "Only the namespaces of this team (`cmapi.net/team`).", + "description": "Only the namespaces of this team (the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default).", "in": "query", "name": "team", "required": false, @@ -22918,7 +22918,7 @@ "type": "null" } ], - "description": "Only the namespaces of this team (`cmapi.net/team`).", + "description": "Only the namespaces of this team (the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default).", "examples": [ "payments" ], @@ -23378,7 +23378,7 @@ } }, { - "description": "Only the namespaces of this team (`cmapi.net/team`).", + "description": "Only the namespaces of this team (the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default).", "in": "query", "name": "team", "required": false, @@ -23391,7 +23391,7 @@ "type": "null" } ], - "description": "Only the namespaces of this team (`cmapi.net/team`).", + "description": "Only the namespaces of this team (the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default).", "examples": [ "payments" ], diff --git a/cmapi/src/cmapi/core/metadata.py b/cmapi/src/cmapi/core/metadata.py index d8cafea9..7bafbd5d 100644 --- a/cmapi/src/cmapi/core/metadata.py +++ b/cmapi/src/cmapi/core/metadata.py @@ -12,6 +12,8 @@ extraAnnotations adoptionLabels keys read when an existing namespace is adopted (story #26), never sent by a requester liveOnlyKeys keys that only the cluster writes, left out when Git is compared with the live namespace (#481) + teamKey the label that names a namespace's team (#258): placement, the approval fact `team`, the daily + auto-approval allowance per team and change_requests.team. Default cmapi.net/team The class names that the approval rules read (keyClasses) are unchanged: a key of a required or extra stanza is "governed", and a key that allowOther admits is "team". @@ -62,6 +64,11 @@ # stanza (requiredLabel) cannot load as a file with no rule in it. _LIST_STANZAS = ("system", "operatorOnly", "reservedPrefixes", "sensitiveKeys", "emailDomains", "liveOnlyKeys") _MAP_STANZAS = ("requiredLabels", "requiredAnnotations", "extraLabels", "extraAnnotations", "adoptionLabels") +_TEXT_STANZAS = ("teamKey",) +_STANZAS = _LIST_STANZAS + _MAP_STANZAS + _TEXT_STANZAS +# The label that names a namespace's team when the file has no teamKey (#258): the key that cmapi read before it was +# configurable, so a file without the stanza keeps its behaviour. +DEFAULT_TEAM_KEY = "cmapi.net/team" # The keys that the cluster or its controllers write on a live namespace and Git never holds, when the file has no # liveOnlyKeys: the comparison of Git with the cluster leaves them out (#481, design section 4.2). Each is an fnmatch glob. DEFAULT_LIVE_ONLY_KEYS = ("kubernetes.io/metadata.name", "openshift.io/*", "argocd.argoproj.io/*", @@ -587,7 +594,7 @@ class MetadataKeys: def __init__(self, raw: Mapping[str, Any]): if not isinstance(raw, Mapping): # An empty file reads as None: it has no stanza, so no key would be required (#338). - raise ValueError(f"metadata-keys.yaml is a mapping of the stanzas {list(_LIST_STANZAS + _MAP_STANZAS)}, " + raise ValueError(f"metadata-keys.yaml is a mapping of the stanzas {list(_STANZAS)}, " f"not {_kind_of(raw)}") problems: list[str] = [] old = [s for s in _OLD_STANZAS if s in raw] @@ -596,11 +603,11 @@ def __init__(self, raw: Mapping[str, Any]): raise ValueError(f"metadata-keys.yaml has the stanzas {old} of the old format; write requiredLabels, " "requiredAnnotations, extraLabels and extraAnnotations instead (docs/02, \"Labels and annotations\")") for stanza in raw: - if stanza not in _LIST_STANZAS + _MAP_STANZAS: + if stanza not in _STANZAS: # A misspelt stanza (requiredLabel) would otherwise load as a file without its rules (#338). - near = difflib.get_close_matches(str(stanza), _LIST_STANZAS + _MAP_STANZAS, n=1) + near = difflib.get_close_matches(str(stanza), _STANZAS, n=1) problems.append(f"unknown stanza {stanza!r}" + (f": did you mean {near[0]}?" if near else - f"; the stanzas are {list(_LIST_STANZAS + _MAP_STANZAS)}")) + f"; the stanzas are {list(_STANZAS)}")) self.system = self._texts(raw, "system", problems) for key in EXPIRY_KEYS: # Only expiresAt writes them (rule 7 of #479), so a file that leaves them out of system cannot let a request. @@ -643,6 +650,7 @@ def __init__(self, raw: Mapping[str, Any]): extra_name, problems) self._check_name_keys(problems) self._check_defaults(problems) + self.team_key = self._team_key(raw, problems) self.adoption_labels: dict[str, tuple[str, ...]] = {} for key, spec in self._mapping(raw, "adoptionLabels", problems).items(): if not isinstance(spec, Mapping) or set(spec) - {"recognise"}: @@ -664,6 +672,27 @@ def __init__(self, raw: Mapping[str, Any]): if problems: raise ValueError("invalid metadata-keys.yaml: " + "; ".join(problems)) + def _team_key(self, raw: Mapping[str, Any], problems: list[str]) -> str: + """teamKey (#258): the label that names a namespace's team. A file that names one must declare it as a label, in + requiredLabels or extraLabels.keys, with its rule: a key the file does not declare would be read on no namespace, + and the daily auto-approval allowance per team would then apply to none, silently. Left out, it is cmapi.net/team, + as before the stanza, declared or not.""" + if "teamKey" not in raw: + return DEFAULT_TEAM_KEY + key = raw["teamKey"] + if not isinstance(key, str) or not key: + problems.append(f"teamKey must be a label key, as text, not {_kind_of(key)}") + return DEFAULT_TEAM_KEY + if key not in self.rules["label"]: + declared = " (it is declared as an annotation)" if key in self.rules["annotation"] else "" + problems.append(f"teamKey: {key} is not a label that requiredLabels or extraLabels.keys declares{declared}; " + "name a declared label, or leave teamKey out for cmapi.net/team") + return key + + def team_of(self, labels: Mapping[str, Any] | None) -> str | None: + """A namespace's team: the value of its teamKey label, None when it has none.""" + return (labels or {}).get(self.team_key) + @staticmethod def _texts(raw: Mapping[str, Any], name: str, problems: list[str]) -> list[str]: """A stanza that is a list of text. Empty (null) is []. A text is refused: list("x.com") would read it as its diff --git a/cmapi/src/cmapi/core/models.py b/cmapi/src/cmapi/core/models.py index 504ddbc7..28293049 100644 --- a/cmapi/src/cmapi/core/models.py +++ b/cmapi/src/cmapi/core/models.py @@ -653,7 +653,8 @@ class GitMetadata(Api): class NamespaceView(ClusterScoped): name: str = Field(description="Namespace name", examples=["payments-dev"]) env: str | None = Field(description="Environment label", examples=["dev"]) - team: str | None = Field(description="cmapi.net/team", examples=["payments"]) + team: str | None = Field(description="The team: the label that metadata-keys.yaml names in `teamKey`, " + "`cmapi.net/team` by default", examples=["payments"]) tier: str | None = Field(description="cmapi.net/tier", examples=["small"]) labels: dict[str, str] = Field(description="Labels", examples=[{"cmapi.net/team": "payments"}]) annotations: dict[str, str] = Field(description="Annotations", examples=[{"cmapi.net/team-dl": "payments-team@ephico2real.com"}]) @@ -1229,8 +1230,9 @@ class PlacementConstraints(Api): class PlacementRequest(RequestBody): environment: str = Field(description="The environment of the new namespace: one this instance serves", examples=["dev"]) - team: LabelValue | None = Field(default=None, description="The team the namespace is for: the create's `cmapi.net/team` " - "label must be the same. Left out on an instance whose metadata " + team: LabelValue | None = Field(default=None, description="The team the namespace is for: the create's team label " + "(metadata-keys.yaml `teamKey`, `cmapi.net/team` by default) " + "must be the same. Left out on an instance whose metadata " "keys have no team label; the cap of 3 active placements is then " "the caller's own", examples=["payments"]) tier: str = Field(default="small", description="A tier of GET /tiers, or custom", examples=["small"]) diff --git a/cmapi/src/cmapi/core/pipeline.py b/cmapi/src/cmapi/core/pipeline.py index 583278e1..1c8b6dc2 100644 --- a/cmapi/src/cmapi/core/pipeline.py +++ b/cmapi/src/cmapi/core/pipeline.py @@ -25,7 +25,7 @@ snapshot_hash, standing, unmanaged_phrase) from cmapi.core.approvals import BEYOND_FACTS, ApprovalLedger, Requirement from cmapi.core.capacity_backend import CapacityHold, SimulatedCapacity, capacity_exceeded -from cmapi.core.capacity_ledger import binding_hard, quota_facts, totals_of +from cmapi.core.capacity_ledger import REQUEST_KEYS, binding_hard, nano_units, quota_facts, totals_of from cmapi.core.clients.kube import BadResponse, ClusterUnreachable, KubeError from cmapi.core.config import InstanceConfig, environment_not_served from cmapi.core.db.models import ChangeRequestRow @@ -442,7 +442,7 @@ def _plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any deltas = {k: qty(hard.get(f"requests.{k}", "0")) - qty(old_hard.get(f"requests.{k}", "0")) for k in ("cpu", "memory")} cpu_delta, mem_delta = float(deltas["cpu"]), float(deltas["memory"]) target = binding_hard(hard) - placement_id = self._placement(body, action, cluster_id, env, labels.get("cmapi.net/team"), target) + placement_id = self._placement(body, action, cluster_id, env, self.cfg.metadata.team_of(labels), target) cap = self.capacity.check(cluster_id, env, max(cpu_delta, 0), max(mem_delta, 0), exclude_placement=placement_id, namespace=ns) if cap.status == "exceeded": @@ -460,7 +460,7 @@ def _plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any if old_hard.keys() != hard.keys() or any(qty(old_hard[k]) != qty(hard[k]) for k in hard): usage_view, usage_facts = plan_usage(self.usage.namespace(cluster_id, ns), old_hard, hard) facts = {"plugin": "namespaces", "action": action, "environment": env, "namespace": ns, "clusterId": cluster_id, - "team": labels.get("cmapi.net/team"), "tier": tier, "capacity": cap.status, "capacityFresh": cap.fresh, + "team": self.cfg.metadata.team_of(labels), "tier": tier, "capacity": cap.status, "capacityFresh": cap.fresh, "automated": requester.automated, "requesterClient": who.client_id if who.kind == "service" else None, "clusterLabels": dict(st.policy.labels), "warnings": [f.message for f in findings], "reason": reason, **exp_facts, **usage_facts, @@ -471,7 +471,8 @@ def _plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any elif action != "create": # quotaIncreasePct over what Git holds; none held is a write from nothing, 100% on each key (compare). tierChange # is from the tier that Git's Namespace names; one that names none and is not moved is rendered on `tier`. - facts.update(self.cfg.tiers.compare(env, old_tier if old_tier or moved else tier, old_hard, tier, hard).facts()) + facts.update(self.cfg.tiers.compare(env, old_tier if old_tier or moved else tier, old_hard, tier, hard, + self.quota_used(cluster_id, ns, old_rq)).facts()) # Beyond the tier: each overridable value that differs from the tier and from the value that Git holds. A value that # was approved before is not beyond the tier again. beyond = {k: v for k, v in self.cfg.tiers.beyond(env, tier, hard, limit_range).items() @@ -640,7 +641,7 @@ def _plan_delete(self, st: Any, who: Identity, requester: Requester, ns: str, *, age_days = (utc_today() - created).days if created else 0 pods, pvcs = self.workload_counts(cluster_id, ns) facts = {"plugin": "namespaces", "action": "delete", "environment": env, "namespace": ns, "clusterId": cluster_id, - "team": labels.get("cmapi.net/team"), "automated": requester.automated, + "team": self.cfg.metadata.team_of(labels), "automated": requester.automated, "requesterClient": who.client_id if who.kind == "service" else None, "protected": self.cfg.approvals.is_protected(labels), "namespaceAgeDays": age_days, "pods": pods, "pvcs": pvcs, "reason": reason, "clusterLabels": dict(st.policy.labels), @@ -799,7 +800,7 @@ def _plan_adoption(self, who: Identity, cluster_id: str, ns: str, *, own_applica for f in findings: counts[f.rule] = counts.get(f.rule, 0) + 1 facts = {"plugin": ADOPTION_PLUGIN, "action": "adopt", "environment": env, "namespace": ns, "clusterId": cluster_id, - "team": adopted_meta["label"].get("cmapi.net/team"), "tier": tier, "capacity": "fits", "capacityFresh": True, + "team": self.cfg.metadata.team_of(adopted_meta["label"]), "tier": tier, "capacity": "fits", "capacityFresh": True, "automated": requester.automated, "requesterClient": who.client_id if who.kind == "service" else None, "clusterLabels": dict(st.policy.labels), "warnings": [f.message for f in findings], "reason": None, "findings": dict(sorted(counts.items())), "findingCount": len(findings), @@ -929,7 +930,8 @@ def restore_facts(self, cluster_id: str, env: str, ns: str, current: Mapping[str existing = namespace_doc(current) is not None exposure_base = old_hard if existing or tier not in offered else offered[tier].quota # A create has no quota change: a planned one carries no tierChange or quotaIncreasePct, and neither does its restore. - facts = {**(tiers.compare(env, old_tier, old_hard, tier, hard).facts() if existing else {}), + facts = {**(tiers.compare(env, old_tier, old_hard, tier, hard, self.quota_used(cluster_id, ns, old_rq)).facts() + if existing else {}), "capacity": cap.status, "capacityFresh": cap.fresh, "beyondTier": bool(beyond), "beyondTierKeys": sorted(beyond), # A folder that Git no longer holds is written again as a create: exposure over what the tier gives, and the # metadata of a new namespace (the first cmapi.net/team is no change of it). @@ -954,6 +956,46 @@ def restore_facts(self, cluster_id: str, env: str, ns: str, current: Mapping[str facts.update(expiry.facts()) return cap, facts, usage_view, beyond, hold + def quota_used(self, cluster_id: str, ns: str, quota: Mapping[str, Any] | None) -> dict[str, str] | None: + """What the pods of `ns` request now, per quota key, for the fact quotaBelowRequested (#256): the `status.used` of + the live ResourceQuota that Git's `quota` is ("Used is the current observed total usage of the resource in the + namespace", the ResourceQuota API reference), read from the cluster's watch cache, which the capacity check reads too. + A short name (`cpu`, `memory`) reports the same use as its long one (capacity_ledger.REQUEST_KEYS). + + None when the use cannot be known: no quota in Git, no watch cache, a watch that is stale, has not listed, or is + refused (401, 403) as the capacity check judges it (capacity_backend._read_cached_quotas), or a live namespace + without that quota. TierCatalog.compare then counts each key that the change lowers as below (fail closed). A + namespace that the fresh watch does not hold has no pods, so it requests nothing.""" + if quota is None: + return self._use_unknown(cluster_id, ns, "Git holds no ResourceQuota that the change acts on") + try: + cache = self.registry.cache(cluster_id) + except Problem as exc: + return self._use_unknown(cluster_id, ns, f"no watch cache: {exc.detail}") + for kind in ("Namespace", "ResourceQuota"): + stale, last = cache.kind_stale(kind) + status, error = cache.kind_error(kind) + if stale or status in (401, 403): + why = "has not listed" if last is None else "is stale" if stale else f"is refused ({status})" + return self._use_unknown(cluster_id, ns, f"the {kind} watch {why}" + (f": {error}" if error else "")) + if cache.get("Namespace", None, ns) is None: + return {k: "0" for k in self.cfg.tiers.sizable} + name = (quota.get("metadata") or {}).get("name") + live = cache.get("ResourceQuota", ns, name) if isinstance(name, str) else None + if live is None: + return self._use_unknown(cluster_id, ns, f"the live namespace has no ResourceQuota {name}") + raw = (live.get("status") or {}).get("used") or {} + used = {k: str(v) for k, v in raw.items() if nano_units(v) is not None} + for long, short in REQUEST_KEYS.values(): + if long not in used and short in used: + used[long] = used[short] + return used + + @staticmethod + def _use_unknown(cluster_id: str, ns: str, reason: str) -> None: + log.info("quota_used_unknown", cluster_id=cluster_id, namespace=ns, reason=reason[:300]) + return None + def _live_committed(self, cluster_id: str, ns: str, current: Mapping[str, str | None]) -> dict[str, Decimal]: """What the namespace adds to the cluster's commitment now (CapacityLedger), or, with no ledger to read, what Git's quotas bind: the capacity check then answers unknown whatever the delta.""" diff --git a/cmapi/src/cmapi/core/problem_docs.py b/cmapi/src/cmapi/core/problem_docs.py index f46c066c..13d4a60b 100644 --- a/cmapi/src/cmapi/core/problem_docs.py +++ b/cmapi/src/cmapi/core/problem_docs.py @@ -83,7 +83,7 @@ "placement-not-found": "Call `POST /api/v1/capacity:place` again and send its new `placementId`. A placement holds its cluster " "for 15 minutes and serves one create.", "placement-mismatch": "Send the create to the cluster that the placement chose, with the same environment and " - "`cmapi.net/team`, and no more CPU or memory than it holds, or place again for this target.", + "team label (metadata-keys.yaml `teamKey`, `cmapi.net/team` by default), and no more CPU or memory than it holds, or place again for this target.", "environment-not-served": "Send the request to the instance that serves the environment: `instanceUrl` is its API and " "`portalUrl` its portal. Each is left out when this instance's directory does not name one.", "cluster-not-writable": "Choose a cluster that takes writes, or ask the platform team to add this cluster to `clusters.yaml`.", diff --git a/cmapi/src/cmapi/core/tiers.py b/cmapi/src/cmapi/core/tiers.py index f71c827c..ec763a4e 100644 --- a/cmapi/src/cmapi/core/tiers.py +++ b/cmapi/src/cmapi/core/tiers.py @@ -278,6 +278,8 @@ class QuotaChange: increase_pct: dict[str, float] # per sizable key, negative for a decrease delta: dict[str, Decimal] # per sizable key, in base units below_used: list[str] = field(default_factory=list) # keys whose new hard < what pods request now (quota used) + # Keys that the change lowers and whose use could not be read: counted as below, fail closed (#256) + unknown_lowered: list[str] = field(default_factory=list) @property def quota_increase_pct(self) -> float: # the fact approval-rules.yaml thresholds read @@ -286,7 +288,7 @@ def quota_increase_pct(self) -> float: # the fact approval-rules.yaml thres def facts(self) -> dict[str, Any]: """The approval facts, named as approval-rules.yaml reads them.""" return {"tierChange": self.tier_change, "quotaIncreasePct": self.quota_increase_pct, - "quotaBelowRequested": bool(self.below_used)} + "quotaBelowRequested": bool(self.below_used or self.unknown_lowered)} # --------------------------------------------------------------------------- catalog @@ -713,14 +715,24 @@ def compare(self, env: str, current_tier: str | None, current_hard: Mapping[str, new_tier: str | None, new_hard: Mapping[str, str], used: Mapping[str, str] | None = None) -> QuotaChange: """current_hard: what Git holds (#710). A tier that is None, or that the catalog no longer has, ranks below every tier, - and a key that a side does not hold is 0: a revert restores a folder as Git held it (Pipeline.restore_facts).""" - pct, delta, below = {}, {}, [] + and a key that a side does not hold is 0: a revert restores a folder as Git held it (Pipeline.restore_facts). + + used: what the namespace's pods request now, per sizable key (the live quota's status.used, Pipeline.quota_used); + None, or a key it does not hold, is a use that could not be read. A key whose new hard is below its use is + below_used: Kubernetes keeps the pods that run and refuses new ones ("Neither contention nor changes to quota will + affect already created resources", https://kubernetes.io/docs/concepts/policy/resource-quotas/). A key that the change + lowers and whose use is unknown is unknown_lowered, and counts as below: an approval fact that cannot be read must + not open the gate it guards (#256, fail closed). A key that the change does not lower cannot newly fall below.""" + pct, delta, below, unknown = {}, {}, [], [] for k in self.sizable: old, new = qty(current_hard.get(k, "0")), qty(new_hard.get(k, "0")) delta[k] = new - old pct[k] = float((new - old) / old * 100) if old else (100.0 if new else 0.0) - if used and k in used and new < qty(used[k]): - below.append(k) + if used is not None and k in used: + if new < qty(used[k]): + below.append(k) + elif new < old: + unknown.append(k) cur_c = self.file.tiers.get(current_tier, TierDef(order=0)).custom new_c = self.file.tiers.get(new_tier, TierDef(order=0)).custom if cur_c and new_c: @@ -735,7 +747,7 @@ def compare(self, env: str, current_tier: str | None, current_hard: Mapping[str, o_old = self.file.tiers[current_tier].order if current_tier in self.file.tiers else floor o_new = self.file.tiers[new_tier].order if new_tier in self.file.tiers else floor change = "up" if o_new > o_old else "down" if o_new < o_old else "same" - return QuotaChange(tier_change=change, increase_pct=pct, delta=delta, below_used=below) + return QuotaChange(tier_change=change, increase_pct=pct, delta=delta, below_used=below, unknown_lowered=unknown) def is_outdated(self, env: str, tier: str, rendered_hash: str | None) -> bool: """True when the namespace's cmapi.net/tier-hash is not the catalog's current one.""" diff --git a/cmapi/src/cmapi/jobs/open_pr.py b/cmapi/src/cmapi/jobs/open_pr.py index f9338de6..af114aea 100644 --- a/cmapi/src/cmapi/jobs/open_pr.py +++ b/cmapi/src/cmapi/jobs/open_pr.py @@ -112,7 +112,7 @@ def open_revert(ctx: AppContext, s: Session, job: JobRow) -> None: f"{row.request_id} was planned: plan the change again") ctx.pipeline.check_plugin_offered("namespaces", row.env) facts = {"plugin": "namespaces", "action": action, "environment": row.env, "namespace": row.namespace, - "clusterId": row.cluster_id, "team": labels.get("cmapi.net/team") or row.team, + "clusterId": row.cluster_id, "team": ctx.cfg.metadata.team_of(labels) or row.team, "clusterLabels": dict(policy.labels), "automated": True, "reason": "revert", "capacity": "fits", "capacityFresh": True, "warnings": []} cap, usage, beyond, hold = CapacityResult("fits", True, None, {"source": "revert"}), None, {}, None diff --git a/cmapi/src/cmapi/plugins/capacity/placement.py b/cmapi/src/cmapi/plugins/capacity/placement.py index 257e1190..e8deb7ed 100644 --- a/cmapi/src/cmapi/plugins/capacity/placement.py +++ b/cmapi/src/cmapi/plugins/capacity/placement.py @@ -56,12 +56,13 @@ def ask_of(c: AppContext, body: dict[str, Any]) -> Ask: dict(((cons.get("clusterSelector") or {}).get("matchLabels")) or {})) -def _team_namespaces(st: ClusterState, team: str | None) -> int: +def _team_namespaces(st: ClusterState, team: str | None, team_key: str) -> int: + """The namespaces of the team on the cluster: those whose teamKey label (metadata-keys.yaml, #258) is the team.""" cache = st.cache if cache is None or team is None: return 0 return sum(1 for ns in cache.all("Namespace") - if ((ns.get("metadata") or {}).get("labels") or {}).get("cmapi.net/team") == team) + if ((ns.get("metadata") or {}).get("labels") or {}).get(team_key) == team) def candidate(c: AppContext, st: ClusterState, session: Session, ask: Ask, latest: Any, @@ -93,7 +94,7 @@ def candidate(c: AppContext, st: ClusterState, session: Session, ask: Ask, lates return Candidate(st.cluster_id, (p.labels or {}).get("region") if p else None, dict(p.labels) if p else {}, bool(p and p.writes), not_connected, bool(block.get("enabled", True)), block.get("maxNamespaces"), float(block.get("weight", 1.0)), size, basis, es.overcommit, committed, detail, namespaces, reserved, - latest.complete_at, latest.detail, zones, p95, _team_namespaces(st, ask.team), zones_complete) + latest.complete_at, latest.detail, zones, p95, _team_namespaces(st, ask.team, c.cfg.metadata.team_key), zones_complete) def candidates(c: AppContext, session: Session, ask: Ask, now: datetime) -> list[Candidate]: diff --git a/cmapi/src/cmapi/plugins/expiration/router.py b/cmapi/src/cmapi/plugins/expiration/router.py index 80fd8208..65bac607 100644 --- a/cmapi/src/cmapi/plugins/expiration/router.py +++ b/cmapi/src/cmapi/plugins/expiration/router.py @@ -51,7 +51,7 @@ description="Text that the name, the team label or the app label contains. Case does not matter.")] Env = Annotated[str | None, Query(examples=["dev"], description="Only the namespaces of this environment (`cmapi.net/env`).")] ClusterFilter = Annotated[str | None, Query(alias="clusterId", examples=["CRC"], description="Only the namespaces on this cluster.")] -Team = Annotated[str | None, Query(examples=["payments"], description="Only the namespaces of this team (`cmapi.net/team`).")] +Team = Annotated[str | None, Query(examples=["payments"], description="Only the namespaces of this team (the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default).")] State = Annotated[str | None, Query(examples=["attention"], description="Only the namespaces in one state: `permanent`, `active`, `expiring`, `grace` or " "`pending_delete`, or `attention` for the three that need action (expiring, grace " @@ -133,7 +133,7 @@ def expiration_rows(c: AppContext, who: Identity, day: date) -> tuple[list[dict[ # Where expiration is off a kept date is not acted on (no notice, no delete), so its state is permanent. state = c.cfg.expiration.state(ExpiryInfo(m["name"], env, created or day, expires), day) rows.append({"name": m["name"], "clusterId": st.cluster_id, "env": labels.get("cmapi.net/env") or env, - "team": labels.get("cmapi.net/team"), "app": labels.get("cmapi.net/app"), "created": created, + "team": c.cfg.metadata.team_of(labels), "app": labels.get("cmapi.net/app"), "created": created, "expiresAt": raw, "daysLeft": (expires - day).days if expires else None, "state": state, "graceEnds": expires + timedelta(days=rules.grace_days) if expires and rules else None, "lifetimeDays": (expires - created).days if expires and created else None, diff --git a/cmapi/src/cmapi/plugins/namespaces/router.py b/cmapi/src/cmapi/plugins/namespaces/router.py index e1b23950..00fae843 100644 --- a/cmapi/src/cmapi/plugins/namespaces/router.py +++ b/cmapi/src/cmapi/plugins/namespaces/router.py @@ -128,7 +128,7 @@ def _namespace_view(c: AppContext, cluster_id: str, obj: dict[str, Any], holders m = obj["metadata"] labels, ann = m.get("labels") or {}, m.get("annotations") or {} holder = holders.get(m["name"]) - return {"clusterId": cluster_id, "name": m["name"], "env": labels.get("cmapi.net/env"), "team": labels.get("cmapi.net/team"), + return {"clusterId": cluster_id, "name": m["name"], "env": labels.get("cmapi.net/env"), "team": c.cfg.metadata.team_of(labels), "tier": labels.get("cmapi.net/tier"), "labels": labels, "annotations": ann, "managed": labels.get("cmapi.net/managed") == "true", "expiresAt": ann.get("cmapi.net/expires-at"), "etag": None, "openRequest": holder["requestId"] if holder else None, diff --git a/cmapi/src/cmapi/plugins/quotas/__init__.py b/cmapi/src/cmapi/plugins/quotas/__init__.py index b4ed8e53..0af5b61a 100644 --- a/cmapi/src/cmapi/plugins/quotas/__init__.py +++ b/cmapi/src/cmapi/plugins/quotas/__init__.py @@ -32,7 +32,7 @@ description="Text that the name, the team label or the app label contains. Case does not matter.")] Env = Annotated[str | None, Query(examples=["dev"], description="Only the namespaces of this environment (`cmapi.net/env`).")] ClusterFilter = Annotated[str | None, Query(alias="clusterId", examples=["CRC"], description="Only the namespaces on this cluster.")] -Team = Annotated[str | None, Query(examples=["payments"], description="Only the namespaces of this team (`cmapi.net/team`).")] +Team = Annotated[str | None, Query(examples=["payments"], description="Only the namespaces of this team (the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default).")] Tier = Annotated[str | None, Query(examples=["small"], description="Only the namespaces of this tier (`cmapi.net/tier`).")] Sort = Annotated[str, Query(examples=["used"], description="`name` sorts by name, A to Z. `used` puts the highest use first: the largest of " @@ -80,7 +80,7 @@ def pct(k: str) -> float: tier = labels.get("cmapi.net/tier") tier_hash = (q.get("metadata", {}).get("annotations") or {}).get("cmapi.net/tier-hash") rows.append({"name": m["name"], "clusterId": st.cluster_id, "env": labels.get("cmapi.net/env"), - "team": labels.get("cmapi.net/team"), "app": labels.get("cmapi.net/app"), "tier": tier, + "team": c.cfg.metadata.team_of(labels), "app": labels.get("cmapi.net/app"), "tier": tier, "cpu": [used.get("requests.cpu", "0"), hard.get("requests.cpu")], "memory": [used.get("requests.memory", "0"), hard.get("requests.memory")], "pods": [used.get("pods", "0"), hard.get("pods")], diff --git a/cmapi/src/cmapi/routers/__init__.py b/cmapi/src/cmapi/routers/__init__.py index 8eb3d2a1..429ba98b 100644 --- a/cmapi/src/cmapi/routers/__init__.py +++ b/cmapi/src/cmapi/routers/__init__.py @@ -95,7 +95,7 @@ def refused(refusal: Refusal, who: Identity) -> Problem: @contextmanager def team_request(c: AppContext, who: Identity, team: str | None) -> Iterator[None]: """The team's bucket: one token for each change request that a write opens for the team (the namespace's - cmapi.net/team, as the request records it), whoever sends it. Entered once the plan knows the team and before the + team label, metadata-keys.yaml teamKey, as the request records it), whoever sends it. Entered once the plan knows the team and before the request is recorded, around the transaction that records it; a dry run, a replay of an Idempotency-Key and a refused plan open no request and take no token. A transaction that ends in an error records no request, so its token is given back (#695 review).""" diff --git a/cmapi/tests/core/test_quota_below_requested_256.py b/cmapi/tests/core/test_quota_below_requested_256.py new file mode 100644 index 00000000..dab5eede --- /dev/null +++ b/cmapi/tests/core/test_quota_below_requested_256.py @@ -0,0 +1,54 @@ +"""#256: TierCatalog.compare and the fact quotaBelowRequested, with the use the pods request now. + +A key whose new hard is below what the pods request now is below_used. A key that the change lowers and whose use could +not be read is unknown_lowered and counts as below: an approval fact that cannot be read must not open the gate it guards. +""" +from __future__ import annotations + +import pytest + +from cmapi.core.tiers import TierCatalog +from conftest import EX + +ENVS = {"rnd", "dev", "qa", "uat", "prod"} + + +@pytest.fixture(scope="module") +def cat() -> TierCatalog: + return TierCatalog.load(EX / "config" / "tiers.yaml", ENVS) + + +def down(cat, used): + return cat.compare("prod", "large", cat.quota_for("prod", "large"), "small", cat.quota_for("prod", "small"), used) + + +def test_a_decrease_above_the_use_is_not_below(cat): + ch = down(cat, {"requests.cpu": "1", "requests.memory": "1Gi", "pods": "3"}) + assert ch.below_used == [] and ch.unknown_lowered == [] + assert ch.facts()["quotaBelowRequested"] is False + + +def test_a_decrease_below_the_use_is_below(cat): + ch = down(cat, {"requests.cpu": "12", "requests.memory": "1Gi", "pods": "3"}) + assert ch.below_used == ["requests.cpu"] and ch.facts()["quotaBelowRequested"] is True + + +def test_a_decrease_whose_use_is_unknown_counts_as_below(cat): + ch = down(cat, None) + assert ch.below_used == [] and set(ch.unknown_lowered) == set(cat.sizable) + assert ch.facts()["quotaBelowRequested"] is True + + +def test_a_key_the_use_does_not_report_is_unknown(cat): + ch = down(cat, {"requests.cpu": "1", "requests.memory": "1Gi"}) + assert ch.unknown_lowered == ["pods"] and ch.facts()["quotaBelowRequested"] is True + + +def test_a_raise_whose_use_is_unknown_is_not_below(cat): + ch = cat.compare("prod", "small", cat.quota_for("prod", "small"), "large", cat.quota_for("prod", "large"), None) + assert ch.unknown_lowered == [] and ch.facts()["quotaBelowRequested"] is False + + +def test_the_same_quota_whose_use_is_unknown_is_not_below(cat): + small = cat.quota_for("prod", "small") + assert cat.compare("prod", "small", small, "small", small, None).facts()["quotaBelowRequested"] is False diff --git a/cmapi/tests/core/test_team_key_258.py b/cmapi/tests/core/test_team_key_258.py new file mode 100644 index 00000000..c6e82c39 --- /dev/null +++ b/cmapi/tests/core/test_team_key_258.py @@ -0,0 +1,73 @@ +"""#258: the label that names a namespace's team is metadata-keys.yaml `teamKey`, not a key hard-coded in the pipeline. + +Before the fix core/pipeline.py read `cmapi.net/team` for placement, the approval fact `team`, the daily auto-approval +allowance per team and change_requests.team. The owner's company example declares no `cmapi.net/team`, so with it no +namespace had a team and the allowance never applied. The loader now reads `teamKey`, `cmapi.net/team` when it is left out, +and refuses one that the file does not declare as a label: the allowance would then apply to no namespace, silently. +""" +from __future__ import annotations + +import copy +import re + +import pytest +import yaml + +from cmapi.core.metadata import DEFAULT_TEAM_KEY, MetadataKeys +from conftest import EX +from test_metadata_loader_shape_338 import shipped + +COMPANY = EX / "cluster-configs/policies/metadata-keys.company.yaml" +REFERENCE = EX / "cluster-configs/policies/metadata-keys.yaml" + + +@pytest.fixture +def company() -> dict: + return copy.deepcopy(yaml.safe_load(COMPANY.read_text())) + + +def test_the_company_example_names_the_mnemonic_as_its_team(company): + keys = MetadataKeys(company) + assert keys.team_key == "company.net/mnemonic" + assert keys.team_of({"company.net/mnemonic": "abc", "cmapi.net/team": "other"}) == "abc" + + +def test_a_file_without_team_key_keeps_cmapi_net_team(): + raw = yaml.safe_load(REFERENCE.read_text()) + raw.pop("teamKey", None) + keys = MetadataKeys(raw) + assert keys.team_key == DEFAULT_TEAM_KEY == "cmapi.net/team" + assert keys.team_of({"cmapi.net/team": "payments"}) == "payments" + assert keys.team_of({}) is None and keys.team_of(None) is None + + +def test_a_team_key_in_extra_labels_is_accepted(company): + company["extraLabels"]["keys"] = {"company.net/squad": {"pattern": "^[a-z]{2,20}$", "example": "checkout"}} + company["teamKey"] = "company.net/squad" + assert MetadataKeys(company).team_key == "company.net/squad" + + +@pytest.mark.parametrize("value, message", [ + ("cmapi.net/team", "teamKey: cmapi.net/team is not a label that requiredLabels or extraLabels.keys declares"), + ("company.net/mnemonic-confluence", "(it is declared as an annotation)"), + ("cmapi.net/tier", "teamKey: cmapi.net/tier is not a label that requiredLabels or extraLabels.keys declares"), + ("", "teamKey must be a label key, as text, not the text ''"), + (["company.net/mnemonic"], "teamKey must be a label key, as text, not a list"), +]) +def test_a_team_key_that_is_not_a_declared_label_is_refused(company, value, message): + company["teamKey"] = value + with pytest.raises(ValueError, match=re.escape(message)): + MetadataKeys(company) + + +def test_a_misspelt_team_key_stanza_is_refused(company): + company["teamkey"] = company.pop("teamKey") + with pytest.raises(ValueError, match=re.escape("unknown stanza 'teamkey': did you mean teamKey?")): + MetadataKeys(company) + + +@pytest.mark.parametrize("name", sorted(shipped())) +def test_every_shipped_copy_names_a_declared_team_label(name): + """A shipped file whose team label is not declared would give no namespace a team, and the allowance would apply to none.""" + keys = MetadataKeys(shipped()[name]) + assert keys.team_key in keys.rules["label"], (name, keys.team_key) diff --git a/cmapi/tests/service/test_helm_metadata_values.py b/cmapi/tests/service/test_helm_metadata_values.py index 0003d18b..6d87f10f 100644 --- a/cmapi/tests/service/test_helm_metadata_values.py +++ b/cmapi/tests/service/test_helm_metadata_values.py @@ -232,7 +232,7 @@ def test_the_schema_names_what_the_loader_reads(): assert tuple(rule["properties"]["format"]["enum"]) == metadata.FORMATS block = schema["properties"]["metadata"] assert set(block["properties"]) == set(_chart_keys()) - assert set(block["then"]["required"]) == set(block["properties"]) - {"liveOnlyKeys"} + assert set(block["then"]["required"]) == set(block["properties"]) - {"liveOnlyKeys", "teamKey"} assert schema["$schema"] == "http://json-schema.org/draft-07/schema#" diff --git a/cmapi/tests/service/test_quota_below_requested_256.py b/cmapi/tests/service/test_quota_below_requested_256.py new file mode 100644 index 00000000..053000fe --- /dev/null +++ b/cmapi/tests/service/test_quota_below_requested_256.py @@ -0,0 +1,93 @@ +"""#256: the fact quotaBelowRequested reads what the namespace's pods request now. + +docs/01, "Quota changes on existing namespaces": "A decrease below what pods already request is refused unless +approver-platform approve, because new pods would be rejected at admission." The rule is `when: quotaBelowRequested` +(approval-rules.yaml). Before the fix Pipeline never passed the use to TierCatalog.compare, so the fact was always false and +the rule never fired. The use is the live ResourceQuota's status.used, from the cluster's watch cache. A use that cannot be +read (no live quota, a stale watch) counts as below for a key that the change lowers: fail closed. + +payments-dev holds requests.cpu 16 in Git and on the cluster (a tier rendered by an older catalog), and a label change +renders the tier's 8 again: a lowering of 8 CPUs. +""" +from __future__ import annotations + +import yaml + +from test_catalog_drift_710 import BASE, LABEL, NAME, OWN, QUOTA_FILE, created, patch, rendered_by_an_older_catalog, stored_facts + +RULE = "threshold quotaBelowRequested" + + +def lowered_with_use(world, cpu_used: str | None) -> None: + """Git and the cluster hold 16 CPUs; the pods request `cpu_used` now (None: the live quota is gone). The watch has + listed what the cluster holds.""" + client, ctx, git, kube, validator, keys = world + created(world) + rendered_by_an_older_catalog(world, {"requests.cpu": "16"}) + if cpu_used is None: + kube.delete("ResourceQuota", NAME, OWN) + else: + kube.objects[("ResourceQuota", NAME, OWN)]["status"]["used"]["requests.cpu"] = cpu_used + cache = ctx.registry.cache("CRC") + cache._list("Namespace") + cache._list("ResourceQuota") + + +def reasons(body: dict) -> list[str]: + return body["approval"]["reasons"] + + +def test_a_lowering_below_what_the_pods_request_needs_the_rules_approval(world): + lowered_with_use(world, "12") + plan = patch(world, LABEL, dry_run=True) + assert plan.status_code == 200, plan.text + assert yaml.safe_load(plan.json()["files"][QUOTA_FILE])["spec"]["hard"]["requests.cpu"] == "8" + assert any(RULE in r for r in reasons(plan.json())), reasons(plan.json()) + r = patch(world, LABEL, dry_run=False) + assert r.status_code == 202, r.text + assert r.json()["status"] == "pending_approval", r.json() + assert stored_facts(world, r.json()["requestId"])["quotaBelowRequested"] is True + + +def test_a_lowering_above_what_the_pods_request_adds_nothing(world): + lowered_with_use(world, "2") + plan = patch(world, LABEL, dry_run=True) + assert plan.status_code == 200, plan.text + assert not any(RULE in x for x in reasons(plan.json())), reasons(plan.json()) + r = patch(world, LABEL, dry_run=False) + assert r.status_code == 202, r.text + assert stored_facts(world, r.json()["requestId"])["quotaBelowRequested"] is False + + +def test_a_lowering_whose_use_cannot_be_read_counts_as_below(world): + """The live namespace has no -quota (deleted by hand, or not synced): what its pods request is not known.""" + lowered_with_use(world, None) + plan = patch(world, LABEL, dry_run=True) + assert plan.status_code == 200, plan.text + assert any(RULE in r for r in reasons(plan.json())), reasons(plan.json()) + + +def test_a_lowering_on_a_stale_watch_counts_as_below(world): + """The quota watch had no good read for longer than its relist window: its status.used is not current.""" + client, ctx, git, kube, validator, keys = world + lowered_with_use(world, "2") + ctx.registry.cache("CRC").state["ResourceQuota"].last_good = 1.0 + plan = patch(world, LABEL, dry_run=True) + assert plan.status_code == 200, plan.text + assert any(RULE in r for r in reasons(plan.json())), reasons(plan.json()) + + +def test_a_revert_that_lowers_below_what_the_pods_request_carries_the_fact(world): + """Pipeline.restore_facts, the facts of :revert, reads the same use (the folder Git holds now, against the one restored).""" + client, ctx, git, kube, validator, keys = world + lowered_with_use(world, "12") + current = {p: c for p, c in git.branches["main"].items() if p.startswith(BASE)} + rq = yaml.safe_load(current[QUOTA_FILE]) + rq["spec"]["hard"]["requests.cpu"] = "4" + restored = {**current, QUOTA_FILE: yaml.safe_dump(rq, sort_keys=False)} + _, facts, *_ = ctx.pipeline.restore_facts("CRC", "dev", NAME, current, restored) + assert facts["quotaBelowRequested"] is True, facts + kube.objects[("ResourceQuota", NAME, OWN)]["status"]["used"]["requests.cpu"] = "3" + ctx.registry.cache("CRC")._list("ResourceQuota") + _, facts, *_ = ctx.pipeline.restore_facts("CRC", "dev", NAME, current, restored) + assert facts["quotaBelowRequested"] is False, facts diff --git a/cmapi/tests/service/test_team_key_258.py b/cmapi/tests/service/test_team_key_258.py new file mode 100644 index 00000000..2676bbcb --- /dev/null +++ b/cmapi/tests/service/test_team_key_258.py @@ -0,0 +1,50 @@ +"""#258: with the owner's company metadata (teamKey company.net/mnemonic) a namespace's team is its mnemonic. + +Before the fix core/pipeline.py read `cmapi.net/team`, which the company file does not declare: no namespace had a team, so +change_requests.team was empty and the daily auto-approval allowance per team (approval-rules.yaml maxPerTeamPerDay) never +applied. Here the allowance is 1: the team's second auto-approvable create of the day waits for an approver. +""" +from __future__ import annotations + +import shutil + +import pytest + +from cmapi.core.db.models import ChangeRequestRow +from conftest import EXAMPLES, build_world +from test_flow import OLA, auth + +URL = "/api/v1/clusters/CRC/namespaces" +SENT = {"company.net/mnemonic": "abc", "company.net/lob": "amgsst", "company.net/cl": "1"} + + +@pytest.fixture +def company(test_config, fresh_db, keys, monkeypatch, tmp_path): + d = tmp_path / "config" + shutil.copytree(test_config, d) + shutil.copy(EXAMPLES / "cluster-configs/policies/metadata-keys.company.yaml", d / "metadata-keys.yaml") + with build_world(d, keys, monkeypatch) as world: + yield world + + +def create(world, namespace: str) -> dict: + client, ctx, git, kube, validator, keys = world + r = client.post(URL, json={"namespace": namespace, "tier": "small", "labels": dict(SENT), "annotations": {}, + "justification": "The owner's sample namespace"}, headers=auth(keys, "ola", **OLA)) + assert r.status_code == 202, r.text + return r.json() + + +def test_the_mnemonic_is_the_team_and_the_daily_allowance_applies(company, monkeypatch): + client, ctx, git, kube, validator, keys = company + monkeypatch.setattr(ctx.cfg.approvals, "max_per_team", 1) + first = create(company, "abc-dev") + assert first["status"] == "approved", first + second = create(company, "abc-two") + assert second["status"] == "pending_approval", second + with ctx.db.session() as s: + rows = {rid: s.get(ChangeRequestRow, rid) for rid in (first["requestId"], second["requestId"])} + assert {r.team for r in rows.values()} == {"abc"} + assert rows[second["requestId"]].plan["facts"]["team"] == "abc" + assert rows[second["requestId"]].requirement["autoFallback"] == "team-allowance", rows[second["requestId"]].requirement + assert ctx.cfg.metadata.team_key == "company.net/mnemonic" diff --git a/deploy/helm/cmapi/config/metadata-keys.yaml b/deploy/helm/cmapi/config/metadata-keys.yaml index 89f88ab5..8f839fb0 100644 --- a/deploy/helm/cmapi/config/metadata-keys.yaml +++ b/deploy/helm/cmapi/config/metadata-keys.yaml @@ -35,3 +35,6 @@ liveOnlyKeys: [kubernetes.io/metadata.name, "openshift.io/*", "argocd.argoproj.i # The organisation's mail domains, one or more. ephico2real.com is a placeholder. Read by cmapi (plan time) # and by the Kyverno bundle (CI and admission), so every email-valued governed key is checked the same way. emailDomains: [ephico2real.com] +# The label that names a namespace's team (#258): placement, the approval fact team, the daily auto-approval allowance +# per team and the request's team. A declared label; left out, it is cmapi.net/team. +teamKey: cmapi.net/team diff --git a/deploy/helm/cmapi/values.schema.json b/deploy/helm/cmapi/values.schema.json index b976921c..758a9e5c 100644 --- a/deploy/helm/cmapi/values.schema.json +++ b/deploy/helm/cmapi/values.schema.json @@ -35,7 +35,7 @@ ] }, "metadata": { - "description": "metadata-keys.yaml as structured values: the whole file, each stanza written out ({} or [] when empty), except liveOnlyKeys, which takes the loader's default when left out. Empty ({}): the chart's config/metadata-keys.yaml, or configFiles.\"metadata-keys.yaml\". docs/18-configuration.md, \"metadata-keys.yaml\".", + "description": "metadata-keys.yaml as structured values: the whole file, each stanza written out ({} or [] when empty), except liveOnlyKeys and teamKey, which take the loader's defaults when left out. Empty ({}): the chart's config/metadata-keys.yaml, or configFiles.\"metadata-keys.yaml\". docs/18-configuration.md, \"metadata-keys.yaml\".", "type": "object", "additionalProperties": false, "properties": { @@ -116,6 +116,8 @@ "sensitiveKeys": {"description": "A change of one of these keys adds an approver-platform approval", "$ref": "#/definitions/keyList"}, "liveOnlyKeys": {"description": "Keys that only the cluster writes, left out when Git is compared with the live namespace; * matches as in fnmatch", "type": "array", "items": {"type": "string", "pattern": "^\\S+$"}}, + "teamKey": {"description": "The label that names a namespace's team (#258): a label that requiredLabels or extraLabels.keys declares. Left out: cmapi.net/team", + "$ref": "#/definitions/key"}, "emailDomains": { "description": "The mail domains of the format email-in-domains", "type": "array", diff --git a/deploy/helm/cmapi/values.yaml b/deploy/helm/cmapi/values.yaml index 9db6faa3..75af29b6 100644 --- a/deploy/helm/cmapi/values.yaml +++ b/deploy/helm/cmapi/values.yaml @@ -341,7 +341,7 @@ podDisruptionBudget: # -------------------------------------------------------------------------- labels and annotations # metadata-keys.yaml as structured values (#335): the required and optional labels and annotations of a namespace, # and the keys cmapi reserves. The block is the whole file, not a patch of the chart's file: write each of its ten -# stanzas, {} or [] when empty; liveOnlyKeys (#481) may be left out, for the loader's default. values.schema.json +# stanzas, {} or [] when empty; liveOnlyKeys (#481) and teamKey (#258) may be left out, for the loader's defaults. values.schema.json # refuses a missing or misspelled stanza, an unknown field and a wrong type at helm install, upgrade, lint and # template, before a pod starts. Empty: the chart's config/metadata-keys.yaml, # or configFiles."metadata-keys.yaml"; setting both fails. docs/18-configuration.md, "metadata-keys.yaml", has an example. diff --git a/docs/02-technical-design-v2.md b/docs/02-technical-design-v2.md index 58c69509..d9d60484 100644 --- a/docs/02-technical-design-v2.md +++ b/docs/02-technical-design-v2.md @@ -1114,6 +1114,8 @@ sensitiveKeys: [cmapi.net/team, network.ephico2real.com/zone] # a change adds # The organisation's mail domains, one or more. ephico2real.com is a placeholder. Read by cmapi (plan time) # and by the Kyverno bundle (CI and admission), so every email-valued governed key is checked the same way. emailDomains: [ephico2real.com] +# The label that names a namespace's team (#258): a declared label. Left out, it is cmapi.net/team. +teamKey: cmapi.net/team ``` **The four stanzas (#215).** `requiredLabels` and `requiredAnnotations` name the keys that each namespace carries. `extraLabels` and `extraAnnotations` name optional keys in `keys`, and `allowOther` admits any other key under one of its prefixes, within its limits (`max` for each kind; `maxValueBytes` and `maxBytesTotal` for annotations). A key can be a label and an annotation at once, with a rule for each. Each key's rule takes at most one of these, and optional `namespacePrefix`, `namespaceSuffix`, `default`, `title`, `description` and `example`: @@ -1138,6 +1140,8 @@ The Kyverno policies come from the same stanzas (#212). Not built yet: the porta cmapi.net/team is required ownership and cost metadata. Any value matching the pattern is accepted from any caller; it is not checked against the caller's roles or groups (mustMatchBinding is retired). +**The team label (#258).** `teamKey` names the label that is a namespace's team: placement's team, the approval fact `team`, the daily auto-approval allowance per team (`maxPerTeamPerDay`), the team's rate-limit bucket and `change_requests.team` all read it, as do the `team` columns of the namespace, quota and expiration lists. It is `cmapi.net/team` when the file has none, so a file written before the stanza keeps its behaviour. A file that names one must declare it as a label in `requiredLabels` or `extraLabels.keys`, or the loader refuses it: a key that no namespace carries would leave the allowance applying to none, silently. The company example has no `cmapi.net/team` and names `teamKey: company.net/mnemonic`, so a namespace's team there is its mnemonic. + **Syntax.** Pydantic checks Kubernetes syntax before policy runs. A key is an optional DNS subdomain prefix of up to 253 characters, a slash, and a name of up to 63 characters that starts and ends with a letter or digit. Label values follow the same name rule or are empty. Annotation values can be any string. cmapi's byte caps sit well under Kubernetes' 256 KiB total because every value lands in Git and in PR diffs. A secret scanner runs in CI on every PR, since annotations are readable by anyone with Git access. ```python @@ -1358,7 +1362,7 @@ At startup an invalid catalog stops cmapi with every problem listed. On reload c | Plan a create or tier change | resolve(env, tier), quota\_for(env, tier, quota, approved), limits\_for(env, tier, limitRange, hard, approved) | The full spec.hard and the full LimitRange values; each custom value is checked against the bounds and step. A value that Git already holds (approved) is not checked against the bounds again | | Beyond the tier | beyond(env, tier, hard, limit range), rendered\_overrides(quota object, the LimitRange objects) | Each overridable value that differs from the tier, for the facts beyondTier and beyondTierKeys; and the approved overrides of a namespace, read from the annotation cmapi.net/beyond-tier | | Capacity and placement | the resolved requests.cpu and requests.memory | The size reserved; an increase reserves only the delta | -| Approval rules | compare(env, old tier, old hard, new tier, new hard, used) | Facts tier, tierChange (up, down, same, to-custom, from-custom, custom), quotaIncreasePct and quotaBelowRequested | +| Approval rules | compare(env, old tier, old hard, new tier, new hard, used) | Facts tier, tierChange (up, down, same, to-custom, from-custom, custom), quotaIncreasePct and quotaBelowRequested. `used` is the live ResourceQuota's status.used from the watch cache (Pipeline.quota_used, #256); a key that the change lowers and whose use cannot be read counts as below (fail closed) | | Render | render(namespace, cluster, instance, env, tier, request, quota, limits, approved) | The ResourceQuota and one LimitRange for each resource, called by core/render/manifests.py, which writes each to its own file. Each object names its own beyond-tier keys in cmapi.net/beyond-tier | | PATCH or PUT .../quota | normalise(env, hard) | The named tier when the values equal one exactly, otherwise custom | | Quota view | is\_outdated(env, tier, rendered hash) | State tier-outdated, a filter on GET /api/v1/quotas | diff --git a/docs/14-authorization.md b/docs/14-authorization.md index bd860f80..a0d9d7bd 100644 --- a/docs/14-authorization.md +++ b/docs/14-authorization.md @@ -175,9 +175,9 @@ A role can have a list of environments. The route checks the permission again wh | Route group | Where the environment comes from | Source | |---|---|---| -| Create, change, delete or extend a namespace, or set or remove its expiry | The cluster's environment | `cmapi/src/cmapi/core/pipeline.py:282`, `:590` | +| Create, change, delete or extend a namespace, or set or remove its expiry | The cluster's environment | `cmapi/src/cmapi/core/pipeline.py:282`, `:591` | | Read the namespaces of a cluster | The cluster's environment | `cmapi/src/cmapi/plugins/namespaces/router.py:196`, `:237` | -| List the adoption candidates or the skipped namespaces, or adopt a namespace (#739: `namespaces:write`) | The cluster's environment | `cmapi/src/cmapi/plugins/adoption/router.py:57`, `cmapi/src/cmapi/core/pipeline.py:707` | +| List the adoption candidates or the skipped namespaces, or adopt a namespace (#739: `namespaces:write`) | The cluster's environment | `cmapi/src/cmapi/plugins/adoption/router.py:57`, `cmapi/src/cmapi/core/pipeline.py:708` | | Read one request, its events or its approval status | The request's environment | `cmapi/src/cmapi/routers/requests.py:103`, `:116`, `:130` | | Approve, reject, cancel, retry or revert a request | The request's environment | `requests.py:154`, `:188`, `:206`, `:233`, `:267` | | Confirm a prune | The request's environment | `cmapi/src/cmapi/routers/admin.py:136` | @@ -321,7 +321,7 @@ A tool signs in with the client credentials grant. It is a service client, or an | The tool sends `onBehalfOf`: a username or an employee ID | cmapi looks the value up in the directory. The person must be enabled, or the answer is 422 `unknown-user`. The person is recorded as the requester and the tool as the caller. The request is recorded as automated | `checks.py:89-95` | | A person sends `onBehalfOf` | 422 `on-behalf-of-not-allowed` | `checks.py:74-78`; `problem_docs.py:104` | -Self-approval uses the requester and the submitter. The ledger refuses the requester as approver: `requester_sub` is the `sub` of the named person (`checks.py:49-53`, `pipeline.py:865`, `approvals.py:355-356`). It also refuses the submitter, which is the `sub` of the tool, unless the approval rule has `selfApproval: true` (`cmapi/src/cmapi/core/db/repo.py:247-249`, `approvals.py:353-354`). The record keeps the submitter in `submittedBySub`, and the response leaves it out (`checks.py:59-64`, `views.py:25-27`). +Self-approval uses the requester and the submitter. The ledger refuses the requester as approver: `requester_sub` is the `sub` of the named person (`checks.py:49-53`, `pipeline.py:866`, `approvals.py:355-356`). It also refuses the submitter, which is the `sub` of the tool, unless the approval rule has `selfApproval: true` (`cmapi/src/cmapi/core/db/repo.py:247-249`, `approvals.py:353-354`). The record keeps the submitter in `submittedBySub`, and the response leaves it out (`checks.py:59-64`, `views.py:25-27`). With `onBehalfOf`, cmapi trusts the tool to name the person. The directory proves that the person exists and is enabled. It does not prove that the person signed in. @@ -368,7 +368,7 @@ The code `forbidden` has two more causes. Each is a refusal of the code, not of | Cause | Detail | Source | |---|---|---| | A caller cancels a request that is not theirs and does not hold `namespaces:protect` in its environment | "Only the requester or an operator can cancel" | `cmapi/src/cmapi/core/lifecycle.py:125`, `cmapi/src/cmapi/routers/requests.py:211` | -| A write sets or removes an operator-only label or annotation (`cmapi.net/protected`, `do-not-delete`) and the caller does not hold `namespaces:protect` in the environment | "Needs namespaces:protect in . Keys: ." (the cluster's environment, #532) | `cmapi/src/cmapi/core/metadata.py:1405` | +| A write sets or removes an operator-only label or annotation (`cmapi.net/protected`, `do-not-delete`) and the caller does not hold `namespaces:protect` in the environment | "Needs namespaces:protect in . Keys: ." (the cluster's environment, #532) | `cmapi/src/cmapi/core/metadata.py:1434` | The ledger also refuses a relay client without `approvals:relay` with this code ("Relay client lacks approvals:relay", `cmapi/src/cmapi/core/approvals.py:347`), but no route can reach it: the approve route in `routers/requests.py` passes no relay to `ApprovalLedger.approve` (see "What is not built"). diff --git a/docs/18-configuration.md b/docs/18-configuration.md index 9edcd4e7..26f1060c 100644 --- a/docs/18-configuration.md +++ b/docs/18-configuration.md @@ -148,7 +148,7 @@ http: `docs.public` is true) have no caller and are not limited by cmapi. With `docs.public: false` the seven docs paths take a token from the caller's `read` bucket. - **The team.** A create, a change, a delete or an expiry write that opens a change request takes one token from the bucket of - the namespace's `cmapi.net/team` after the write (the team that the request records: a change that moves a namespace to + the namespace's team label (`teamKey` of metadata-keys.yaml) after the write (the team that the request records: a change that moves a namespace to another team takes from the new team's), whoever sends it, after its plan and before the request is recorded. A dry run, a replay of an Idempotency-Key and a refused plan open no request and take no team token, and a write whose request is not recorded (a lost race to its key, a conflict, an error) gives its token back. Any caller with `namespaces:create` can name @@ -437,6 +437,7 @@ The rules for the labels and the annotations that a requester sets on a namespac | `adoptionLabels` | mapping of key to `{recognise: [values]}` | `{}` | Labels that mark a namespace that another tool made. A requester cannot set them: the class of such a key is `reserved`. Today cmapi reads only the keys, for that class. The adoption (story #26) reads the values: a namespace that carries one is listed as `recognised` among the candidates, and the plan reports it as `adoption-label` | | `sensitiveKeys` | list of keys | `[]` | A change of the value of one of these keys adds the fact `sensitiveKeyChanged`, once per request: a value that Git holds changes or goes, or a change of an existing namespace adds a required or extra key (#481). The first value of a create, and the first set of an operator-only key, are not a change. The shipped files list `cmapi.net/protected` and `do-not-delete`: protecting a namespace needs no extra approval, and removing the protection adds one approver-platform approval (#366) | | `emailDomains` | list of domains | `[]` | The mail domains for a key with `format: email-in-domains`. A key of that format needs at least one domain | +| `teamKey` | a label key | `cmapi.net/team` | The label that names a namespace's team (#258). Placement (`POST /api/v1/capacity:place`, whose `team` the create's label must match), the approval fact `team`, the daily allowance `maxPerTeamPerDay`, the team's rate-limit bucket, `change_requests.team` and the `team` of the namespace, quota and expiration lists read it. A key that the file names here must be a label that `requiredLabels` or `extraLabels.keys` declares, or the file is refused (`teamKey: is not a label that requiredLabels or extraLabels.keys declares`): a key read on no namespace would leave the allowance applying to none, silently. Without the stanza it is `cmapi.net/team`, declared or not, as before the stanza. The company example names `company.net/mnemonic` | | `liveOnlyKeys` | list of key globs | `[kubernetes.io/metadata.name, "openshift.io/*", "argocd.argoproj.io/*", app.kubernetes.io/instance]` | Keys that the cluster or its controllers write on a live namespace and Git never holds. `GET .../namespaces/{ns}` compares each governed, extra and operator-only key of Git with the live namespace (`sync`, #481) and leaves these out, so they are never drift. `*` matches as in `fnmatch`. Without the stanza, the default applies; an empty list compares every such key. System and reserved keys are never compared | Where `emailDomains` is set: in each deployment's metadata configuration. On CRC it is `deploy/manifests/environments/crc/20-config.yaml`, key `emailDomains`; on kind it is the same key in `deploy/manifests/environments/kind/20-config.yaml`. The examples are `examples/cluster-configs/policies/metadata-keys.yaml` (`[ephico2real.com]`, a placeholder) and the company profile `metadata-keys.company.yaml` (`[company.net]`). To change it on CRC, edit that key, apply the ConfigMap, then `oc rollout restart deploy/cmapi-api deploy/cmapi-worker -n cmapi`. The domain is checked for format only: cmapi never looks a DL up. @@ -553,14 +554,14 @@ Some key names are in the code, not only in the file. The `system` list of the r | `cmapi.net/cluster-id`, `cmapi.net/managed`, `cmapi.net/env`, `cmapi.net/tier`, `cmapi.net/requested-by-user` (labels) | `core/render/manifests.py`, `core/tiers.py` (`render`) | The renderer writes them on each namespace. The ResourceQuota and the LimitRange carry `cmapi.net/cluster-id`, `cmapi.net/managed` and `cmapi.net/tier` | | `cmapi.net/instance`, `cmapi.net/request-id`, `cmapi.net/requested-by`, `cmapi.net/tier-hash`, `cmapi.net/beyond-tier` (annotations) | `core/render/manifests.py`, `core/tiers.py` (`render`) | The renderer writes them. `cmapi.net/tier-hash` and `cmapi.net/beyond-tier` are on the ResourceQuota and the LimitRange | | `cmapi.net/expiry` (label), `cmapi.net/expires-at` (annotation) | `core/render/manifests.py`, `core/pipeline.py` | The renderer writes them for a namespace with an expiry date. The planner reads `cmapi.net/expires-at` and `cmapi.net/tier` back from Git | -| `cmapi.net/team` | `core/pipeline.py`, `plugins/quotas/__init__.py`, `plugins/namespaces/router.py` | The label gives the fact `team` of a plan, and the column `change_requests.team`. The limit `maxPerTeamPerDay` counts requests for this value (`RequestRepo.auto_approvals_today`). A namespace with no such label has no team, and no daily allowance applies to it (#258) | +| `cmapi.net/team` | `core/metadata.py` (`DEFAULT_TEAM_KEY`) | The team label when the file has no `teamKey` (#258). The team label gives the fact `team` of a plan, and the column `change_requests.team`. The limit `maxPerTeamPerDay` counts requests for this value (`RequestRepo.auto_approvals_today`). A namespace with no team label has no team, and no daily allowance applies to it | | `cmapi.net/team-dl` | `core/metadata.py` (`_governed`) | A bad address in this key is refused with the code `invalid-team-dl`. A bad address in each other key of the format `email-in-domains` is refused with `invalid_value` | | `cmapi.net/app` | `plugins/quotas/__init__.py` | The quota list shows it as `app` | | `cmapi.net/cluster-id`, `cmapi.net/managed` | `core/policygen.py` (`SYSTEM_REQUIRED`) | The rendered policies require both on a managed namespace | | `cmapi.net/env` | `core/policygen.py` (`ENV_LABEL`) | The rendered policy for an environment requires `cmapi.net/env` to equal that environment | | `cmapi.net/expires-at`, `cmapi.net/expiry`, `cleanup.kyverno.io/ttl` | `core/policygen.py` (`EXPIRY_KEYS`) | The rendered policy `deny-expiry-in-prod` refuses each of them in `prod` | -A file that does not declare `cmapi.net/team` is valid. Then the per-team allowance does not apply (the fact `team` is empty and `Pipeline.submit` skips the count). The owner's company example declares no `cmapi.net/team`, so with that file no namespace has a team in cmapi's sense. +A file with no `teamKey` that does not declare `cmapi.net/team` is valid, as before #258. Then no namespace has a team: the per-team allowance does not apply (the fact `team` is empty and `Pipeline.submit` skips the count). Name the team label in `teamKey` instead: the owner's company example declares no `cmapi.net/team` and names `teamKey: company.net/mnemonic`, so a namespace's team there is its mnemonic. `cmapi/tests/core/test_team_key_258.py` holds every shipped file to a declared team label. ### Setting the keys through the Helm values @@ -568,10 +569,10 @@ With the Helm chart, an operator sets the file as the structured value `metadata The rules of the value: -- **The block is the whole file**, not a patch of the chart's file. Write each of the stanzas of the table above, `{}` or `[]` when one is empty. Only `liveOnlyKeys` (#481) may be left out: the loader's default applies, so a block written before it still installs and upgrades. The schema refuses a block that leaves out any other, so a partial block cannot silently drop the reserved keys or the required ones. +- **The block is the whole file**, not a patch of the chart's file. Write each of the stanzas of the table above, `{}` or `[]` when one is empty. Only `liveOnlyKeys` (#481) and `teamKey` (#258) may be left out: the loader's defaults apply, so a block written before it still installs and upgrades. The schema refuses a block that leaves out any other, so a partial block cannot silently drop the reserved keys or the required ones. - **Empty (`metadata: {}`, the default):** the chart's `config/metadata-keys.yaml`, or the full text in `configFiles."metadata-keys.yaml"`. That text stays the fallback, and the schema does not read inside it. - **Both set:** the render fails: `metadata and configFiles."metadata-keys.yaml" both set metadata-keys.yaml: set one of them`. -- **What the schema refuses:** an unknown or misspelled stanza or field (`additionalProperties: false` at each level, so the old stanzas `governed` and `team` too); a missing stanza other than `liveOnlyKeys`; a wrong type (a text for a list, a limit that is not a whole number of zero or more); a key that is not a valid label or annotation key, including an empty prefix such as `/foo`; a `format` on a label; more than one of `pattern`, `enum` and `format`; `value.from` with a source other than `namespace`, `environment`, `cluster` or `instance`, or beside a `pattern`, `enum`, `format`, `namespacePrefix: true` or `default`; a `namespaceSuffix` that is not a boolean; a `default` that is not `{from: }`; an `allowOther.example` key that is not a valid key or, for labels, a value that is not a label value; an empty `enum`, or a label `enum` value that a label cannot hold; an `adoptionLabels` entry with no `recognise`; a rule or an `example` that is not text; a required key with no `example` and no `value` (#332); a domain that is not a DNS name. The loader still checks what JSON Schema cannot: that a `pattern` compiles and is in the subset of "Patterns" above (its grammar nests parentheses, which the schema's own `pattern` keyword cannot describe), that an `example` passes its key's rule, that `email-in-domains` has a domain, that a key is not reserved or declared twice. +- **What the schema refuses:** an unknown or misspelled stanza or field (`additionalProperties: false` at each level, so the old stanzas `governed` and `team` too); a missing stanza other than `liveOnlyKeys` and `teamKey`; a wrong type (a text for a list, a limit that is not a whole number of zero or more); a key that is not a valid label or annotation key, including an empty prefix such as `/foo`; a `format` on a label; more than one of `pattern`, `enum` and `format`; `value.from` with a source other than `namespace`, `environment`, `cluster` or `instance`, or beside a `pattern`, `enum`, `format`, `namespacePrefix: true` or `default`; a `namespaceSuffix` that is not a boolean; a `default` that is not `{from: }`; an `allowOther.example` key that is not a valid key or, for labels, a value that is not a label value; an empty `enum`, or a label `enum` value that a label cannot hold; an `adoptionLabels` entry with no `recognise`; a rule or an `example` that is not text; a required key with no `example` and no `value` (#332); a domain that is not a DNS name. The loader still checks what JSON Schema cannot: that a `pattern` compiles and is in the subset of "Patterns" above (its grammar nests parentheses, which the schema's own `pattern` keyword cannot describe), that an `example` passes its key's rule, that `email-in-domains` has a domain, that a key is not reserved or declared twice. - `configFiles` takes only the five names of the chart's files. Another name, such as `metadata-key.yaml`, is refused; before #335 the chart ignored it and rendered its own file. An example, a site that requires its own owner label beside the reference keys (`deploy/environments/.yaml`): @@ -802,7 +803,7 @@ A `when` line reads these facts. The names are fixed in the code. An unknown nam | `plugin`, `action`, `environment`, `namespace`, `clusterId`, `reason`, `team`, `tier` | The request | `core/pipeline.py` | | `tierChange` | `up`, `down`, `same`, `to-custom`, `from-custom` or `custom`. Set for a change of an existing namespace only | `TierCatalog.compare` | | `quotaIncreasePct` | The largest increase of a sizable key, in percent. Set for a change of an existing namespace only | `QuotaChange.quota_increase_pct` | -| `quotaBelowRequested` | A new quota is below what the pods request now. It is always `false` today: `TierCatalog.compare` takes the usage as an argument, and the planner does not pass it (`core/pipeline.py`, #256) | `QuotaChange.facts` | +| `quotaBelowRequested` | On a change of an existing namespace's quota (a plan, or a revert): a sizable key's new hard value is below what the pods request now, so Kubernetes would refuse new pods (#256). The use is the `status.used` of the live ResourceQuota that Git's quota is, from the cluster's watch cache. A key that the change lowers and whose use cannot be read counts as below (fail closed): the watch has not listed, is stale (no good read for 30 minutes) or is refused (401, 403), or the live namespace has no such quota. A namespace that the watch does not hold has no pods. A key that the change does not lower is not below for want of a read. The planner logs `quota_used_unknown` with the reason | `Pipeline.quota_used`, `TierCatalog.compare` | | `requestToPeakRatio` | On a change of an existing namespace's quota, with `usage` `ok`: the largest planned hard limit over the namespace's 14-day peak, of a resource the change raises (#310). Absent otherwise, so a rule that reads it adds nothing | `plan_usage`, `capacity/usage.py` | | `usage` | On a change of an existing namespace's quota: `ok`, `insufficient-data` (no usage source, or under 80% of the window's samples) or `unavailable` (Thanos did not answer, or the cluster's import check found the reader without its own Thanos grants, #724). The shipped rule adds approver-platform on `usage == "unavailable"`. If the active policy has no matching usage threshold that adds that group, the planner supplies one platform slot (#310) | `plan_usage`, `capacity/usage.py` | | `capacity`, `capacityFresh` | `fits`, `warn`, `exceeded` or `unknown`, and whether the data is fresh. `unknown`, not fresh, when the cluster has neither `simulatedCapacity` nor fresh counted node allocatable, no watch cache, ResourceQuotas not listed yet, ResourceQuota reads refused (401 or 403), or a ResourceQuota watch with no good read for 30 minutes (#393). What is committed comes from the cluster's quota ledger: per namespace the smallest unscoped managed quota, scoped quotas left out (#302). The check adds the capacity that open requests hold (`capacity_reservations`, #62): each request with an increase holds it from submit until it leaves the holding states, and a hold stops counting once the ledger shows its quota. Submit checks again under the cluster's lock and takes the hold in the same transaction, so a request that fit when planned but not beside a hold taken since is refused (`exceeded`) or decided on the new answer; the last `:approve` and a `:retry` from `failed` check again and answer 422 `capacity-exceeded` when the request no longer fits | `core/capacity_backend.py`, `core/capacity_ledger.py` | @@ -1131,7 +1132,7 @@ environments: | `monitoring.serviceMonitor`, `.prometheusRule`, `.perses` | | `enabled: false` | The scrape, the alerts and the dashboards | | `networkPolicy.enabled`, `.monitoringNamespace` | | `true`, `openshift-user-workload-monitoring` | The network policies | | `securityContext`, `containerSecurityContext`, `podDisruptionBudget` | | Restricted | Non-root, no capabilities, the runtime default seccomp profile | -| `metadata` | mapping | `{}` | `metadata-keys.yaml` as structured values: the whole file, each stanza written out but `liveOnlyKeys`, which may be left out. Checked by `values.schema.json`. Empty: the chart's file, or `configFiles."metadata-keys.yaml"`. Setting both fails (see "Setting the keys through the Helm values") | +| `metadata` | mapping | `{}` | `metadata-keys.yaml` as structured values: the whole file, each stanza written out but `liveOnlyKeys` and `teamKey`, which may be left out. Checked by `values.schema.json`. Empty: the chart's file, or `configFiles."metadata-keys.yaml"`. Setting both fails (see "Setting the keys through the Helm values") | | `configFiles.` | text | `{}` | The full text of `approval-rules.yaml`, `authz-roles.yaml`, `tiers.yaml`, `expiration.yaml` or `metadata-keys.yaml`, to use in place of the file of the chart. Another name is refused | A site sets its own values in `deploy/environments/.yaml`, and passes the file with `-f`. The chart refuses an image with no digest, so deploy from `deploy/images.lock.yaml`. diff --git a/docs/21-usage-from-thanos.md b/docs/21-usage-from-thanos.md index 0de76529..2ea289ac 100644 --- a/docs/21-usage-from-thanos.md +++ b/docs/21-usage-from-thanos.md @@ -115,9 +115,9 @@ from the file. The file also creates the Namespace `cmapi-system` and the Servic | Rule | API group and resources | Verbs | Why cmapi needs it | |---|---|---|---| -| 1 (`examples/baseline/cmapi-reader-rbac.yaml:23-25`) | core: `namespaces`, `nodes`, `resourcequotas`, `limitranges`, `serviceaccounts` | get, list, watch | Namespaces, ResourceQuotas and LimitRanges are the kinds `WatchCache` watches (`cmapi/src/cmapi/core/clients/kube.py:402`), and check 6 lists Namespaces (`cmapi/src/cmapi/core/registry.py:601`). `NodeCache` watches Nodes (`cmapi/src/cmapi/core/clients/nodes.py:33`, `:114`). The adoption plan lists a namespace's ServiceAccounts to count what stays unmanaged: `Pipeline._unadopted_counts` (`cmapi/src/cmapi/core/pipeline.py:670-680`), over `UNADOPTED_KINDS` (`cmapi/src/cmapi/core/adoption.py:43`) | +| 1 (`examples/baseline/cmapi-reader-rbac.yaml:23-25`) | core: `namespaces`, `nodes`, `resourcequotas`, `limitranges`, `serviceaccounts` | get, list, watch | Namespaces, ResourceQuotas and LimitRanges are the kinds `WatchCache` watches (`cmapi/src/cmapi/core/clients/kube.py:402`), and check 6 lists Namespaces (`cmapi/src/cmapi/core/registry.py:601`). `NodeCache` watches Nodes (`cmapi/src/cmapi/core/clients/nodes.py:33`, `:114`). The adoption plan lists a namespace's ServiceAccounts to count what stays unmanaged: `Pipeline._unadopted_counts` (`cmapi/src/cmapi/core/pipeline.py:671-681`), over `UNADOPTED_KINDS` (`cmapi/src/cmapi/core/adoption.py:43`) | | 2 (`examples/baseline/cmapi-reader-rbac.yaml:26-28`) | core: `pods`, `persistentvolumeclaims` | list | The delete thresholds count a namespace's pods and PVCs: `Pipeline.workload_counts` (`cmapi/src/cmapi/core/pipeline.py:256-262`) | -| 3 (`examples/baseline/cmapi-reader-rbac.yaml:29-31`) | `rbac.authorization.k8s.io`: `roles`, `rolebindings`, `clusterroles`, `clusterrolebindings` | get, list, watch | The adoption plan lists a namespace's RoleBindings in the same count: `Pipeline._unadopted_counts` (`cmapi/src/cmapi/core/pipeline.py:670-680`). No code reads the other three today | +| 3 (`examples/baseline/cmapi-reader-rbac.yaml:29-31`) | `rbac.authorization.k8s.io`: `roles`, `rolebindings`, `clusterroles`, `clusterrolebindings` | get, list, watch | The adoption plan lists a namespace's RoleBindings in the same count: `Pipeline._unadopted_counts` (`cmapi/src/cmapi/core/pipeline.py:671-681`). No code reads the other three today | | 4 (`examples/baseline/cmapi-reader-rbac.yaml:32-34`) | `security.openshift.io`: `securitycontextconstraints` | get, list, watch | No code reads it today | | 5 (`examples/baseline/cmapi-reader-rbac.yaml:35-37`) | `user.openshift.io`: `users`, `groups`, `identities` | get, list, watch | The identity check reads `users/~`, which every authenticated user may read (`cmapi/src/cmapi/core/clients/kube.py:262-264`); no code lists the others today | | 6 (`examples/baseline/cmapi-reader-rbac.yaml:38-40`) | `quota.openshift.io`: `clusterresourcequotas` | get, list, watch | No code reads it today | diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index af031f8d..a970f313 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -23,6 +23,7 @@ Status: read from `main` at `afd1206` on 2026-11-23. Each row was read from the | `instance.yaml` | The file with the key `instance`: name, allowed environments, token issuer and audience, Git repository, identity, CORS, problem base URL, docs and policy settings. | [18-configuration.md](18-configuration.md) | | `tiers.yaml` | The tier catalog: the quota and limits of each tier in each environment. | [18-configuration.md](18-configuration.md) | | `metadata-keys.yaml` | The file of the label and annotation keys: the system keys, the keys a requester sets, `operatorOnly`, `sensitiveKeys`, `liveOnlyKeys`, and `emailDomains`. | [18-configuration.md](18-configuration.md), [metadata-keys.yaml](../examples/cluster-configs/policies/metadata-keys.yaml) | +| `teamKey`, team label | The label of `metadata-keys.yaml` that names a namespace's team (#258): placement, the approval fact `team`, the daily allowance `maxPerTeamPerDay`, the team's rate-limit bucket and `change_requests.team` read it. `cmapi.net/team` when the file has none; a declared label otherwise. The company example names `company.net/mnemonic`. | [18-configuration.md](18-configuration.md), [core/metadata.py](../cmapi/src/cmapi/core/metadata.py) | | `approval-rules.yaml` | The file that decides, from the facts of a request, how many approvals it needs and from which groups, and which auto-approval policies apply. | [18-configuration.md](18-configuration.md) | | `authz-roles.yaml` | The file that maps each role to its permissions and, optionally, to the environments where it applies. | [core/authz.py](../cmapi/src/cmapi/core/authz.py), [18-configuration.md](18-configuration.md) | | `clusters.yaml`, `capacity.yaml` | `clusters.yaml` lists the clusters (`environment`, `writes`, `delivery`, `clusterTokens` and more). `capacity.yaml` holds the overcommit, the warn and critical commitment targets and the KPI thresholds. | [18-configuration.md](18-configuration.md) | @@ -110,6 +111,7 @@ Status: read from `main` at `afd1206` on 2026-11-23. Each row was read from the | `base_sha` (`baseSha`) | The Git commit that the plan was made against. | [core/models.py](../cmapi/src/cmapi/core/models.py) | | `request_events` | The table of one state change or note of a request, in order. `GET /api/v1/requests/{request_id}/events` reads it. Migration 0007 makes its time the insertion time. | [16-data-model.md](16-data-model.md) | | Approval | One approval of one request by one person, in `approvals`. A person counts once (migration 0002). Requesters cannot approve their own request (409 `self-approval`). | [16-data-model.md](16-data-model.md), [core/docs.py](../cmapi/src/cmapi/core/docs.py) | +| `quotaBelowRequested` | The approval fact of a quota change whose new hard value of a sizable key is below what the namespace's pods request now (the live ResourceQuota's `status.used`, #256). A lowered key whose use cannot be read counts as below (fail closed). | [18-configuration.md](18-configuration.md), [core/tiers.py](../cmapi/src/cmapi/core/tiers.py) | | Auto-approval | An `auto:` rule of `approval-rules.yaml` that approves a plan with no person. A Kyverno warning keeps it from applying. `approvals:pause` stops it. | [18-configuration.md](18-configuration.md), [core/lifecycle.py](../cmapi/src/cmapi/core/lifecycle.py) | | `:cancel`, `:approve`, `:reject`, `:retry`, `:revert` | The verbs on `/api/v1/requests/{request_id}`, each with its permission (`requests:cancel`, `requests:approve`, `requests:reject`, `requests:retry`; `:revert` also needs `requests:retry`). | [14-authorization.md](14-authorization.md), [core/lifecycle.py](../cmapi/src/cmapi/core/lifecycle.py) | | In sync, Pending, Drift, Unknown | The state of a namespace in the portal and in the API field `state`. `pending`: an open request holds the namespace, also after the merge and before the cluster has it. `drift`: no request is open and a governed, extra or operator-only key differs between Git and the cluster, or the cluster does not have the namespace. `in-sync`: they are the same. `unknown`: cmapi cannot compare. | [schema.generated.ts](../cmapi-portal-ui/src/api/schema.generated.ts), [NamespacesTab.tsx](../cmapi-portal-ui/src/portal/NamespacesTab.tsx) | diff --git a/docs/citations.lock.json b/docs/citations.lock.json index b8b237b0..87fa178f 100644 --- a/docs/citations.lock.json +++ b/docs/citations.lock.json @@ -496,7 +496,7 @@ "docs/14-authorization.md|cmapi/src/cmapi/core/lifecycle.py|125-125": [ " raise Problem.forbidden(\"Only the requester or an operator can cancel\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/metadata.py|1405-1405": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/metadata.py|1434-1434": [ " raise Problem.forbidden(f\"{_operator_only_reason((sources or {}).get('environment'))} Keys: {keys}.\")" ], "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|194-196": [ @@ -513,13 +513,13 @@ "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|296-296": [ " operator = self.cfg.roles.is_operator(who, env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|590-590": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|591-591": [ " self.cfg.roles.require(who, \"namespaces:write\", env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|707-707": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|708-708": [ " self.cfg.roles.require(who, ADOPT_PERMISSION, env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|865-865": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|866-866": [ " requirement=requirement_to_json(req), requester=plan.requester.record(), requester_sub=plan.requester.sub," ], "docs/14-authorization.md|cmapi/src/cmapi/core/problem_docs.py|104-104": [ @@ -1569,7 +1569,7 @@ " if old_hard.keys() != hard.keys() or any(qty(old_hard[k]) != qty(hard[k]) for k in hard):", " usage_view, usage_facts = plan_usage(self.usage.namespace(cluster_id, ns), old_hard, hard)" ], - "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|670-680": [ + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|671-681": [ " def _unadopted_counts(self, cluster_id: str, ns: str) -> dict[str, int | None]:", " \"\"\"D2: how many ServiceAccounts and RoleBindings the namespace has, which the adoption leaves unmanaged. A kind that", " cannot be read is null (not known), never 0.\"\"\"", diff --git a/examples/cluster-configs/policies/metadata-keys.company.yaml b/examples/cluster-configs/policies/metadata-keys.company.yaml index 827a1b71..10bdcb76 100644 --- a/examples/cluster-configs/policies/metadata-keys.company.yaml +++ b/examples/cluster-configs/policies/metadata-keys.company.yaml @@ -50,3 +50,6 @@ sensitiveKeys: [company.net/mnemonic, company.net/lob, cmapi.net/protected, do-n # cluster (sync of GET .../namespaces/{ns}) leaves them out (#481). fnmatch globs; also the default without this stanza. liveOnlyKeys: [kubernetes.io/metadata.name, "openshift.io/*", "argocd.argoproj.io/*", app.kubernetes.io/instance] emailDomains: [company.net] +# The team is the mnemonic (#258): placement, the approval fact team, the daily auto-approval allowance per team and the +# request's team read it. The file declares no cmapi.net/team, the default, so without this line no namespace has a team. +teamKey: company.net/mnemonic diff --git a/examples/cluster-configs/policies/metadata-keys.yaml b/examples/cluster-configs/policies/metadata-keys.yaml index 89f88ab5..8f839fb0 100644 --- a/examples/cluster-configs/policies/metadata-keys.yaml +++ b/examples/cluster-configs/policies/metadata-keys.yaml @@ -35,3 +35,6 @@ liveOnlyKeys: [kubernetes.io/metadata.name, "openshift.io/*", "argocd.argoproj.i # The organisation's mail domains, one or more. ephico2real.com is a placeholder. Read by cmapi (plan time) # and by the Kyverno bundle (CI and admission), so every email-valued governed key is checked the same way. emailDomains: [ephico2real.com] +# The label that names a namespace's team (#258): placement, the approval fact team, the daily auto-approval allowance +# per team and the request's team. A declared label; left out, it is cmapi.net/team. +teamKey: cmapi.net/team From c5647f456437cb7226a4e0755df1a31c137f60b3 Mon Sep 17 00:00:00 2001 From: ephico2real2 Date: Tue, 1 Dec 2026 10:55:15 -0600 Subject: [PATCH 2/3] #256, #258 review fixes: use read only when a bound is lowered (or newly added); scoped quota is unknown; default approver when no rule reads quotaBelowRequested; deletes count against the team allowance; company portal places with its team key Reviewer 1 (Codex gpt-6.2-astra) and reviewer 2 (Fable) findings, plus one coordinator finding fixed by reviewer 2. Record: docs/reviews/2026-12-01-issue-256-258/. --- cmapi-portal-ui/src/api/schema.generated.ts | 4 +- .../src/portal/NewNamespaceTab.tsx | 6 +- cmapi-portal-ui/src/portal/metadataForm.ts | 13 +- .../tests/api/metadata-keys.company.json | 1 + cmapi-portal-ui/tests/api/standin.mjs | 4 +- cmapi-portal-ui/tests/contract.test.mjs | 16 +- cmapi/contract/openapi.json | 4 +- cmapi/src/cmapi/core/approvals.py | 11 +- cmapi/src/cmapi/core/capacity_ledger.py | 19 +- cmapi/src/cmapi/core/metadata.py | 2 + cmapi/src/cmapi/core/models.py | 6 +- cmapi/src/cmapi/core/pipeline.py | 20 +- cmapi/src/cmapi/core/tiers.py | 55 +- .../core/test_quota_below_requested_256.py | 98 ++ cmapi/tests/core/test_team_key_258.py | 10 + cmapi/tests/service/test_expire_check_263.py | 19 + cmapi/tests/service/test_review_771.py | 146 +++ docs/02-technical-design-v2.md | 2 +- docs/09-portal-ui-testing.md | 2 +- docs/14-authorization.md | 12 +- docs/16-data-model.md | 2 +- docs/18-configuration.md | 7 +- docs/GLOSSARY.md | 4 +- docs/citations.lock.json | 12 +- .../2026-12-01-issue-256-258/README.md | 23 + .../2026-12-01-issue-256-258/final.diff | 946 ++++++++++++++++++ .../reviewer-1-codex.md | 769 ++++++++++++++ .../reviewer-2-fable.md | 400 ++++++++ 28 files changed, 2548 insertions(+), 65 deletions(-) create mode 100644 cmapi/tests/service/test_review_771.py create mode 100644 docs/reviews/2026-12-01-issue-256-258/README.md create mode 100644 docs/reviews/2026-12-01-issue-256-258/final.diff create mode 100644 docs/reviews/2026-12-01-issue-256-258/reviewer-1-codex.md create mode 100644 docs/reviews/2026-12-01-issue-256-258/reviewer-2-fable.md diff --git a/cmapi-portal-ui/src/api/schema.generated.ts b/cmapi-portal-ui/src/api/schema.generated.ts index 3de44ef6..7e361fb7 100644 --- a/cmapi-portal-ui/src/api/schema.generated.ts +++ b/cmapi-portal-ui/src/api/schema.generated.ts @@ -2620,7 +2620,7 @@ export interface components { state: "permanent" | "active" | "expiring" | "grace" | "pending_delete"; /** * Team - * @description Team (`cmapi.net/team`) + * @description Team from the label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default) * @example payments */ team: string | null; @@ -3381,7 +3381,7 @@ export interface components { onBehalfOf?: string | null; /** * Placementid - * @description The `placementId` of POST /api/v1/capacity:place: its hold becomes this request's own. The placement must be active and made for the path's cluster, its environment and the `cmapi.net/team` label sent here + * @description The `placementId` of POST /api/v1/capacity:place: its hold becomes this request's own. The placement must be active and made for the path's cluster, its environment and the team label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default) * @example null */ placementId?: string | null; diff --git a/cmapi-portal-ui/src/portal/NewNamespaceTab.tsx b/cmapi-portal-ui/src/portal/NewNamespaceTab.tsx index 722716a6..dc205d19 100644 --- a/cmapi-portal-ui/src/portal/NewNamespaceTab.tsx +++ b/cmapi-portal-ui/src/portal/NewNamespaceTab.tsx @@ -33,7 +33,7 @@ import { isoDay } from "./format"; import { Field, fieldName, MetadataSection } from "./MetadataFields"; import { bodyOf, checkAll, checkExtras, checkName, defaultSource, endValue, errorsByField, expiryInfo, expiryRulesOf, joinName, nameEnds, nameSuggestion, - shownValues, valueKey + shownValues, teamFieldOf, valueKey } from "./metadataForm"; import type { ExpiryInfo, ExtraCheck, ExtraRow, Kind, MetaField, MetaForm, Source } from "./metadataForm"; import { NamespaceNameField } from "./NamespaceNameField"; @@ -81,7 +81,6 @@ const CHECK_AFTER_MS = 150; /** How long the team, tier and region stay still before the Placement preview ranks them: each ranking spends the caller's * :place bucket (10 a minute), so typing a team name does not rank each prefix. */ const RANK_AFTER_MS = 600; -const TEAM_KEY = "cmapi.net/team"; const LABEL_VALUE = /^[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$/; const GI = 2 ** 30; @@ -314,7 +313,8 @@ export function NewNamespaceTab({ config, open }: TabProps) { const activeRegion = inEnv.some((c) => c.labels.region === region) ? region : ANY_REGION; const instance = me.state === "ok" ? me.data.instance : ""; // The team the namespace is for, as the form shows it: placement ranks for it, and the create must carry the same label. - const teamField = form?.fields.find((f) => f.kind === "label" && f.key === TEAM_KEY) ?? null; + // Its key is the instance's team label (metadata-keys.yaml teamKey, #258), which the answer of GET /api/v1/metadata-keys names. + const teamField = form ? teamFieldOf(form) : null; const team = form && teamField ? shownValues(form, typed, { namespace: "", environment: env, cluster: "", instance })[valueKey(teamField)] ?? "" : ""; // A label value (PlacementRequest.team), or the preview waits: the form's own check names what is wrong with it. An instance // whose keys have no team label places with no team. diff --git a/cmapi-portal-ui/src/portal/metadataForm.ts b/cmapi-portal-ui/src/portal/metadataForm.ts index 364829ab..dc10728c 100644 --- a/cmapi-portal-ui/src/portal/metadataForm.ts +++ b/cmapi-portal-ui/src/portal/metadataForm.ts @@ -88,6 +88,9 @@ export interface ExpiryRules { /** What the form reads from one answer of GET /api/v1/metadata-keys. */ export interface MetaForm { + /** The label that names a namespace's team (metadata-keys.yaml teamKey, #258): labels.x-cmapi-team-key, which the answer + * leaves out when it is cmapi.net/team. POST /api/v1/capacity:place takes its value as `team`. */ + teamKey: string; /** Inputs, then read-only fields, then optional inputs, for each kind; operator-only keys are not offered. */ fields: MetaField[]; /** A label value's syntax (labels.additionalProperties): Kubernetes' IsValidLabelValue, which cmapi checks first. */ @@ -124,7 +127,7 @@ type Json = Record; export const KEYWORDS = { /** The members of the answer itself. */ answer: { read: ["labels", "annotations", "x-cmapi-expiration"], ignored: {} }, - map: { read: ["type", "properties", "required", "additionalProperties", "propertyNames", "x-cmapi-other-keys"], ignored: {} }, + map: { read: ["type", "properties", "required", "additionalProperties", "propertyNames", "x-cmapi-other-keys", "x-cmapi-team-key"], ignored: {} }, property: { read: ["type", "pattern", "allOf", "maxLength", "minLength", "enum", "title", "description", "examples", "readOnly", "x-cmapi-rule", "x-cmapi-derived-from", "x-cmapi-format", "x-cmapi-namespace-prefix", "x-cmapi-namespace-suffix", "x-cmapi-default-from", @@ -295,7 +298,13 @@ export function fieldsOf(view: unknown): MetaForm { ]; ordered.forEach((f, i) => fields.push({ ...f, id: `ns-${kind}-${i}` })); } - return { fields, labelValue, operatorOnlyLabels, operatorOnly, otherKeys, expiration: expirationOf(view), edits }; + const teamKey = isObject(view.labels) ? textOf(view.labels["x-cmapi-team-key"]) : null; + return { fields, teamKey: teamKey ?? "cmapi.net/team", labelValue, operatorOnlyLabels, operatorOnly, otherKeys, expiration: expirationOf(view), edits }; +} + +/** The field of the team label, whose value placement ranks for and the create must carry; null when the form offers none. */ +export function teamFieldOf(form: MetaForm): MetaField | null { + return form.fields.find((f) => f.kind === "label" && f.key === form.teamKey) ?? null; } /** The key of a field's value in the form's state: a key can be a label and an annotation, each with its own value. */ diff --git a/cmapi-portal-ui/tests/api/metadata-keys.company.json b/cmapi-portal-ui/tests/api/metadata-keys.company.json index 07f92166..7c796ad6 100644 --- a/cmapi-portal-ui/tests/api/metadata-keys.company.json +++ b/cmapi-portal-ui/tests/api/metadata-keys.company.json @@ -116,6 +116,7 @@ } } }, + "x-cmapi-team-key": "company.net/mnemonic", "required": [ "name", "company.net/app-environment", diff --git a/cmapi-portal-ui/tests/api/standin.mjs b/cmapi-portal-ui/tests/api/standin.mjs index 8c2cf8fb..e4ba927f 100644 --- a/cmapi-portal-ui/tests/api/standin.mjs +++ b/cmapi-portal-ui/tests/api/standin.mjs @@ -820,7 +820,7 @@ export function missingKeysOf(keys, maps, sources) { /** NamespaceView of a record: the list's (no Git, no etag) or the detail's (router.py _namespace_view and get_namespace). */ export function namespaceViewOf(keys, rec, withGit, environment = rec.env) { const live = rec.live ?? { labels: {}, annotations: {} }; - return { clusterId: rec.clusterId, name: rec.name, env: live.labels["cmapi.net/env"] ?? null, team: live.labels["cmapi.net/team"] ?? null, tier: live.labels["cmapi.net/tier"] ?? null, + return { clusterId: rec.clusterId, name: rec.name, env: live.labels["cmapi.net/env"] ?? null, team: live.labels[keys.labels["x-cmapi-team-key"] ?? "cmapi.net/team"] ?? null, tier: live.labels["cmapi.net/tier"] ?? null, labels: live.labels, annotations: live.annotations, managed: live.labels["cmapi.net/managed"] === "true", expiresAt: live.annotations["cmapi.net/expires-at"] ?? null, etag: withGit ? recordEtag(rec) : null, openRequest: rec.openRequest?.requestId ?? null, mnemonic: prefixOf(keys, rec.live), git: withGit ? { ...rec.git, edits: gitEditsOf(keys, rec.git, environment), @@ -1172,7 +1172,7 @@ export function apiHandler({ issuer, portalOrigin }) { const p = state.placements.get(body.placementId); if (!p || p.used) return problem(res, refuse(422, "placement-not-found", `No active placement ${body.placementId}: it expired, was used by another create, or never existed. Place again.`), cors); // The team that the namespace will carry: the request's, or the one cmapi fills in (a default), as facts["team"]. - if (p.clusterId !== clusterId || p.env !== env || p.team !== (made.filled.label["cmapi.net/team"] ?? null)) { + if (p.clusterId !== clusterId || p.env !== env || p.team !== (made.filled.label[state.metadataKeys.labels["x-cmapi-team-key"] ?? "cmapi.net/team"] ?? null)) { return problem(res, refuse(422, "placement-mismatch", `Placement ${body.placementId} was made for another target`), cors); } } diff --git a/cmapi-portal-ui/tests/contract.test.mjs b/cmapi-portal-ui/tests/contract.test.mjs index 9517cd3d..f05acfb4 100644 --- a/cmapi-portal-ui/tests/contract.test.mjs +++ b/cmapi-portal-ui/tests/contract.test.mjs @@ -30,7 +30,7 @@ console.log("ok - contract"); // #336: the New namespace form evaluates or shows each keyword that GET /api/v1/metadata-keys sends, or lists it as // ignored with its reason (src/portal/metadataForm.ts, KEYWORDS). A keyword in neither list fails here: the generator // (MetadataKeys.json_schema) gained a rule that the form would silently check less than cmapi does. -const { KEYWORDS } = await import("../src/portal/metadataForm.ts"); +const { fieldsOf, KEYWORDS, teamFieldOf } = await import("../src/portal/metadataForm.ts"); const samples = JSON.parse(readFileSync(join(app, "..", "cmapi", "src", "cmapi", "contract", "samples.json"), "utf8")); const answers = { reference: samples.operations.core_metadata_keys.response.body, company: JSON.parse(readFileSync(join(app, "tests", "api", "metadata-keys.company.json"), "utf8")), @@ -64,3 +64,17 @@ for (const [name, answer] of Object.entries(answers)) { } assert.deepEqual(unknown, [], "keywords of GET /api/v1/metadata-keys that the form neither evaluates nor lists as ignored"); console.log("ok - the New namespace form reads each keyword of GET /api/v1/metadata-keys or lists it as ignored"); + +// #258: the New namespace form places for the value of the instance's team label, which the answer names when it is not +// cmapi.net/team. A form that looked for cmapi.net/team on the company answer placed with no team, and the create, whose +// team is the mnemonic, was refused (422 placement-mismatch). +for (const [name, key] of [["reference", "cmapi.net/team"], ["company", "company.net/mnemonic"], ["company-479", "cmapi.net/team"]]) { + const form = fieldsOf(answers[name]); + assert.equal(form.teamKey, key, `${name}: the team label`); + const field = teamFieldOf(form); + assert.deepEqual(field && [field.kind, field.key, field.required, field.derivedFrom], ["label", key, true, null], `${name}: its field`); +} +// An answer with no field of its team label places with no team (PlacementRequest.team: "Left out on an instance whose +// metadata keys have no team label"). +assert.equal(teamFieldOf({ ...fieldsOf(answers.company), teamKey: "cmapi.net/team" }), null); +console.log("ok - the New namespace form finds the team that placement ranks for by the answer's team label"); diff --git a/cmapi/contract/openapi.json b/cmapi/contract/openapi.json index 943b974a..bee4afec 100644 --- a/cmapi/contract/openapi.json +++ b/cmapi/contract/openapi.json @@ -3067,7 +3067,7 @@ "type": "null" } ], - "description": "Team (`cmapi.net/team`)", + "description": "Team from the label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default)", "examples": [ "payments" ], @@ -4701,7 +4701,7 @@ "type": "null" } ], - "description": "The `placementId` of POST /api/v1/capacity:place: its hold becomes this request's own. The placement must be active and made for the path's cluster, its environment and the `cmapi.net/team` label sent here", + "description": "The `placementId` of POST /api/v1/capacity:place: its hold becomes this request's own. The placement must be active and made for the path's cluster, its environment and the team label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default)", "examples": [ null ], diff --git a/cmapi/src/cmapi/core/approvals.py b/cmapi/src/cmapi/core/approvals.py index bbaf57ae..21b156ed 100644 --- a/cmapi/src/cmapi/core/approvals.py +++ b/cmapi/src/cmapi/core/approvals.py @@ -141,7 +141,9 @@ def _added(self, facts: Mapping[str, Any]) -> list[tuple[Slot, str, frozenset[st A request beyond its tier always gets an answer from a rule. When no threshold that reads a beyond-tier fact is true, one approver of defaults.group is added: an instance that removes the rule does not open the gate by accident. A - rule that means no extra approval says so with `add: 0`. + rule that means no extra approval says so with `add: 0`. A quota lowered below what the pods request, or lowered + while their use cannot be read (quotaBelowRequested, #256), gets its answer the same way: docs/01, "A decrease + below what pods already request is refused unless approver-platform approve". """ out = [] for expr, t in self.thresholds: @@ -155,6 +157,13 @@ def _added(self, facts: Mapping[str, Any]) -> list[tuple[Slot, str, frozenset[st # A site may still mount the policy shipped before live usage existed. out.append((Slot("approver-platform", 1, "Live usage unavailable"), "live usage unavailable: +1 approver-platform", frozenset({"usage"}))) + if facts.get("quotaBelowRequested") and not any("quotaBelowRequested" in names for _, _, names in out): + # The fact was always false before #256, so a file without the rule never answered it. A file that answers it, + # with any group or with `add: 0`, is the site's policy and stands, also for a use that could not be read. + g = self.defaults["group"] + out.append((Slot(g, 1, "Quota below what pods request"), + f"quota below what pods request, and no rule reads quotaBelowRequested: +1 {g}", + frozenset({"quotaBelowRequested"}))) if facts.get("beyondTier") and not any(names & BEYOND_FACTS for _, _, names in out): g = self.defaults["group"] out.append((Slot(g, 1, "Value beyond the tier"), f"beyond the tier, and no rule reads beyondTier: +1 {g}", diff --git a/cmapi/src/cmapi/core/capacity_ledger.py b/cmapi/src/cmapi/core/capacity_ledger.py index b521d1ef..51c1f847 100644 --- a/cmapi/src/cmapi/core/capacity_ledger.py +++ b/cmapi/src/cmapi/core/capacity_ledger.py @@ -24,15 +24,9 @@ from decimal import Context, Decimal from typing import Any, Iterable, Mapping -from cmapi.core.tiers import qty +from cmapi.core.tiers import REQUEST_KEYS, binding_hard as binding_hard, qty RESOURCES = ("cpu", "memory") -# A quota's `cpu` and `memory` are the same resources as `requests.cpu` and `requests.memory` -# (https://kubernetes.io/docs/concepts/policy/resource-quotas/): the pod evaluator charges a pod's requests to both names, -# and quota admission refuses a pod that exceeds either hard value (kubernetes v1.34.0, pkg/quota/v1/evaluator/core/pods.go, -# podComputeUsageHelper; staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go, LessThanOrEqual). So a quota with both -# lets the namespace commit the smaller of the two, and that is what is counted, once. -REQUEST_KEYS = {"cpu": ("requests.cpu", "cpu"), "memory": ("requests.memory", "memory")} MANAGED = "cmapi.net/managed" @@ -87,17 +81,6 @@ def _bound(hard: Mapping[str, Any], used: Mapping[str, Any], resource: str) -> B return Bound(value, None) -def binding_hard(hard: Mapping[str, Any] | None) -> dict[str, str]: - """A quota's hard values with each short name (`cpu`, `memory`) folded into its long name, the smaller of the two: the - limit that admission enforces and the ledger counts (#393). The planner sizes a change from this, so a quota in Git that - bounds CPU by `cpu` alone, or by a `cpu` tighter than its `requests.cpu`, is not read as no bound (#710).""" - out = {k: str(v) for k, v in (hard or {}).items()} - for long, short in REQUEST_KEYS.values(): - if short in out: - out[long] = min(out.get(long, out[short]), out[short], key=qty) - return out - - def quota_facts(obj: Mapping[str, Any]) -> QuotaFacts | None: """The facts of a quota that cmapi manages, or None for any other quota.""" meta = obj.get("metadata") or {} diff --git a/cmapi/src/cmapi/core/metadata.py b/cmapi/src/cmapi/core/metadata.py index 7bafbd5d..e731992a 100644 --- a/cmapi/src/cmapi/core/metadata.py +++ b/cmapi/src/cmapi/core/metadata.py @@ -1608,6 +1608,8 @@ def json_schema(self, kind: str, op: str) -> dict[str, Any]: # A character is one to four bytes in UTF-8, so a bound on bytes is at least this bound on characters. extra["maxLength"] = other.max_value_bytes schema: dict[str, Any] = {"type": "object", "properties": properties} + if kind == "label" and not patch and self.team_key != DEFAULT_TEAM_KEY: + schema["x-cmapi-team-key"] = self.team_key # A filled-in key is required too (#479, A1): a client sends its value or leaves it out, and cmapi fills it in. required = [key for key, rule in rules.items() if rule.required] if required and not patch: diff --git a/cmapi/src/cmapi/core/models.py b/cmapi/src/cmapi/core/models.py index 28293049..5ca33fd8 100644 --- a/cmapi/src/cmapi/core/models.py +++ b/cmapi/src/cmapi/core/models.py @@ -415,7 +415,8 @@ class NamespaceCreate(RequestBody): placement_id: str | None = Field(default=None, description="The `placementId` of POST /api/v1/capacity:place: its hold " "becomes this request's own. The placement must be active and " "made for the path's cluster, its environment and the " - "`cmapi.net/team` label sent here", examples=[None]) + "team label named by metadata-keys.yaml `teamKey` " + "(`cmapi.net/team` by default)", examples=[None]) on_behalf_of: str | None = Field(default=None, description="Username or employee ID, for services and automation", examples=[None]) justification: str | None = Field(default=None, description="Why the namespace is needed", examples=["Payments service dev namespace"]) @@ -754,7 +755,8 @@ class ExpirationRow(Api): name: str = Field(description="Namespace", examples=["sprint-dev"]) cluster_id: str = Field(description="Cluster", examples=["CRC"]) env: str | None = Field(description="Environment (`cmapi.net/env`)", examples=["dev"]) - team: str | None = Field(description="Team (`cmapi.net/team`)", examples=["payments"]) + team: str | None = Field(description="Team from the label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by " + "default)", examples=["payments"]) app: str | None = Field(default=None, description="`cmapi.net/app`", examples=[None]) created: date | None = Field(description="The day the namespace was created on the cluster (its creationTimestamp), UTC", examples=["2026-10-01"]) diff --git a/cmapi/src/cmapi/core/pipeline.py b/cmapi/src/cmapi/core/pipeline.py index 1c8b6dc2..ad9b6e4f 100644 --- a/cmapi/src/cmapi/core/pipeline.py +++ b/cmapi/src/cmapi/core/pipeline.py @@ -25,7 +25,7 @@ snapshot_hash, standing, unmanaged_phrase) from cmapi.core.approvals import BEYOND_FACTS, ApprovalLedger, Requirement from cmapi.core.capacity_backend import CapacityHold, SimulatedCapacity, capacity_exceeded -from cmapi.core.capacity_ledger import REQUEST_KEYS, binding_hard, nano_units, quota_facts, totals_of +from cmapi.core.capacity_ledger import REQUEST_KEYS, binding_hard, is_scoped, nano_units, quota_facts, totals_of from cmapi.core.clients.kube import BadResponse, ClusterUnreachable, KubeError from cmapi.core.config import InstanceConfig, environment_not_served from cmapi.core.db.models import ChangeRequestRow @@ -472,7 +472,7 @@ def _plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any # quotaIncreasePct over what Git holds; none held is a write from nothing, 100% on each key (compare). tierChange # is from the tier that Git's Namespace names; one that names none and is not moved is rendered on `tier`. facts.update(self.cfg.tiers.compare(env, old_tier if old_tier or moved else tier, old_hard, tier, hard, - self.quota_used(cluster_id, ns, old_rq)).facts()) + self._use_if_lowered(cluster_id, ns, old_rq, old_hard, hard)).facts()) # Beyond the tier: each overridable value that differs from the tier and from the value that Git holds. A value that # was approved before is not beyond the tier again. beyond = {k: v for k, v in self.cfg.tiers.beyond(env, tier, hard, limit_range).items() @@ -834,7 +834,9 @@ def rerender(request_id: str) -> dict[str, str | None]: def submit(self, who: Identity, plan: Plan, repo: RequestRepo, jobs: JobRepo, *, idempotency_key: str | None, body_fingerprint: str, justification: str | None) -> ChangeRequestRow: rid = repo.next_id() # takes the day's advisory lock: submits are serial from here to the commit - decide_again = plan.action != "delete" and bool(plan.facts.get("team")) + # A delete too: the expired-namespace policy approves one, and the team's daily allowance is a guard that no policy + # switches off (docs/01). Any other delete falls back on the guard "delete" first, as when it was planned. + decide_again = bool(plan.facts.get("team")) if plan.hold is not None: # The cluster as it is now, under its lock, with every hold taken since the plan (#62): what the rules decide on. # A request that no longer fits is refused here and nothing is recorded. @@ -930,8 +932,8 @@ def restore_facts(self, cluster_id: str, env: str, ns: str, current: Mapping[str existing = namespace_doc(current) is not None exposure_base = old_hard if existing or tier not in offered else offered[tier].quota # A create has no quota change: a planned one carries no tierChange or quotaIncreasePct, and neither does its restore. - facts = {**(tiers.compare(env, old_tier, old_hard, tier, hard, self.quota_used(cluster_id, ns, old_rq)).facts() - if existing else {}), + facts = {**(tiers.compare(env, old_tier, old_hard, tier, hard, + self._use_if_lowered(cluster_id, ns, old_rq, old_hard, hard)).facts() if existing else {}), "capacity": cap.status, "capacityFresh": cap.fresh, "beyondTier": bool(beyond), "beyondTierKeys": sorted(beyond), # A folder that Git no longer holds is written again as a create: exposure over what the tier gives, and the # metadata of a new namespace (the first cmapi.net/team is no change of it). @@ -984,6 +986,8 @@ def quota_used(self, cluster_id: str, ns: str, quota: Mapping[str, Any] | None) live = cache.get("ResourceQuota", ns, name) if isinstance(name, str) else None if live is None: return self._use_unknown(cluster_id, ns, f"the live namespace has no ResourceQuota {name}") + if is_scoped(live.get("spec") or {}): + return self._use_unknown(cluster_id, ns, f"ResourceQuota {name} measures only its scope") raw = (live.get("status") or {}).get("used") or {} used = {k: str(v) for k, v in raw.items() if nano_units(v) is not None} for long, short in REQUEST_KEYS.values(): @@ -991,6 +995,12 @@ def quota_used(self, cluster_id: str, ns: str, quota: Mapping[str, Any] | None) used[long] = used[short] return used + def _use_if_lowered(self, cluster_id: str, ns: str, quota: Mapping[str, Any] | None, old_hard: Mapping[str, str], + hard: Mapping[str, str]) -> dict[str, str] | None: + """quota_used for a change that lowers a sizable bound, None for any other: a change of a label, a raise or a quota + kept as it is cannot fall below the use, so it reads no watch and logs no quota_used_unknown (TierCatalog.lowered).""" + return self.quota_used(cluster_id, ns, quota) if self.cfg.tiers.lowered(old_hard, hard) else None + @staticmethod def _use_unknown(cluster_id: str, ns: str, reason: str) -> None: log.info("quota_used_unknown", cluster_id=cluster_id, namespace=ns, reason=reason[:300]) diff --git a/cmapi/src/cmapi/core/tiers.py b/cmapi/src/cmapi/core/tiers.py index ec763a4e..b6d6f686 100644 --- a/cmapi/src/cmapi/core/tiers.py +++ b/cmapi/src/cmapi/core/tiers.py @@ -82,6 +82,30 @@ def qty(value: str | int | float) -> Decimal: raise ValueError(out_of_range) from None +# A quota's `cpu` and `memory` are the same resources as `requests.cpu` and `requests.memory` +# (https://kubernetes.io/docs/concepts/policy/resource-quotas/): the pod evaluator charges a pod's requests to both names, +# and quota admission refuses a pod that exceeds either hard value (kubernetes v1.34.0, pkg/quota/v1/evaluator/core/pods.go, +# podComputeUsageHelper; staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go, LessThanOrEqual). So a quota with both +# lets the namespace commit the smaller of the two, and that is what is counted, once. +REQUEST_KEYS = {"cpu": ("requests.cpu", "cpu"), "memory": ("requests.memory", "memory")} + + +def binding_hard(hard: Mapping[str, Any] | None) -> dict[str, str]: + """A quota's hard values with each short name (`cpu`, `memory`) folded into its long name, the smaller of the two: the + limit that admission enforces and the ledger counts (#393). The planner sizes a change from this, so a quota in Git that + bounds CPU by `cpu` alone, or by a `cpu` tighter than its `requests.cpu`, is not read as no bound (#710).""" + out = {k: str(v) for k, v in (hard or {}).items()} + for long, short in REQUEST_KEYS.values(): + if short in out: + out[long] = min(out.get(long, out[short]), out[short], key=qty) + return out + + +def _long_name(key: str) -> str: + """`requests.cpu` for `cpu` and `requests.memory` for `memory`: the name that binding_hard folds the short one into.""" + return REQUEST_KEYS[key][0] if key in REQUEST_KEYS else key + + def _off_step(value: Decimal, step: Decimal) -> bool: """Whether value is not a whole number of steps. Decimal's % stops with DivisionImpossible when the integer quotient has more digits than the context's precision, 28 by default, and a requested value can have more. Both come from qty, so @@ -711,6 +735,17 @@ def normalise(self, env: str, hard: Mapping[str, str]) -> tuple[str, dict[str, s raise TierError("tier-not-offered", f"Custom quotas are not offered in {env}") return custom, self.quota_for(env, custom, hard) + def lowered(self, current_hard: Mapping[str, str], new_hard: Mapping[str, str]) -> list[str]: + """The sizable keys whose bound a change lowers: the new quota holds the key, with a smaller value than Git's, or + Git's quota does not hold it. A key that Git does not bound has no limit, so its first bound is a lowering (an + adopted quota without requests.cpu, moved to a tier). A short name (`cpu`, `memory`) is read with its long one, + the smaller of the two (binding_hard). A change that removes a bound, keeps it or raises it lowers nothing. Only + a lowered key can newly fall below what the pods request, so only a change with one reads their use + (Pipeline.quota_used). This is for the use alone: compare's delta and percent still count an absent key as 0.""" + old, new = binding_hard(current_hard), binding_hard(new_hard) + return [k for k in self.sizable + if (key := _long_name(k)) in new and (key not in old or qty(new[key]) < qty(old[key]))] + def compare(self, env: str, current_tier: str | None, current_hard: Mapping[str, str], new_tier: str | None, new_hard: Mapping[str, str], used: Mapping[str, str] | None = None) -> QuotaChange: @@ -718,21 +753,27 @@ def compare(self, env: str, current_tier: str | None, current_hard: Mapping[str, and a key that a side does not hold is 0: a revert restores a folder as Git held it (Pipeline.restore_facts). used: what the namespace's pods request now, per sizable key (the live quota's status.used, Pipeline.quota_used); - None, or a key it does not hold, is a use that could not be read. A key whose new hard is below its use is + None, or a key it does not hold, is a use that could not be read. A lowered key whose new hard is below its use is below_used: Kubernetes keeps the pods that run and refuses new ones ("Neither contention nor changes to quota will affect already created resources", https://kubernetes.io/docs/concepts/policy/resource-quotas/). A key that the change lowers and whose use is unknown is unknown_lowered, and counts as below: an approval fact that cannot be read must - not open the gate it guards (#256, fail closed). A key that the change does not lower cannot newly fall below.""" + not open the gate it guards (#256, fail closed). A key that the change does not lower cannot newly fall below. A + key that Git's quota does not bound is lowered by its first bound (lowered).""" pct, delta, below, unknown = {}, {}, [], [] + lowered = self.lowered(current_hard, new_hard) + current_hard, new_hard = binding_hard(current_hard), binding_hard(new_hard) for k in self.sizable: - old, new = qty(current_hard.get(k, "0")), qty(new_hard.get(k, "0")) + key = _long_name(k) + old, new = qty(current_hard.get(key, "0")), qty(new_hard.get(key, "0")) delta[k] = new - old pct[k] = float((new - old) / old * 100) if old else (100.0 if new else 0.0) - if used is not None and k in used: - if new < qty(used[k]): - below.append(k) - elif new < old: + if k not in lowered: + continue + usage = used.get(key, used.get(k)) if used is not None else None + if usage is None: unknown.append(k) + elif new < qty(usage): + below.append(k) cur_c = self.file.tiers.get(current_tier, TierDef(order=0)).custom new_c = self.file.tiers.get(new_tier, TierDef(order=0)).custom if cur_c and new_c: diff --git a/cmapi/tests/core/test_quota_below_requested_256.py b/cmapi/tests/core/test_quota_below_requested_256.py index dab5eede..03490dfe 100644 --- a/cmapi/tests/core/test_quota_below_requested_256.py +++ b/cmapi/tests/core/test_quota_below_requested_256.py @@ -52,3 +52,101 @@ def test_a_raise_whose_use_is_unknown_is_not_below(cat): def test_the_same_quota_whose_use_is_unknown_is_not_below(cat): small = cat.quota_for("prod", "small") assert cat.compare("prod", "small", small, "small", small, None).facts()["quotaBelowRequested"] is False + + +@pytest.mark.parametrize("target", ["500m", "750m", None]) +def test_only_a_lowered_bound_can_be_below_requested(cat, target): + old = {"requests.cpu": "0.5"} + new = {"requests.cpu": target} if target is not None else {} + for used in ({"requests.cpu": "1"}, None): + change = cat.compare("dev", "small", old, "small", new, used) + assert change.facts()["quotaBelowRequested"] is False + + +def _decision(cat, thresholds, used, defaults=None): + """An rnd-style change that needs no approval and matches an auto-approval policy, lowered from 20 pods to 10.""" + from cmapi.core.approvals import ApprovalRules + + rules = ApprovalRules({"defaults": defaults or {}, "environments": {"dev": {"change": 0}}, "thresholds": thresholds, + "autoApproval": {"enabled": True, "policies": [{"name": "updates", + "match": {"actions": ["update"]}}]}}) + change = cat.compare("dev", "small", {"pods": "20"}, "small", {"pods": "10"}, used) + assert change.facts()["quotaBelowRequested"] is True + return rules.decide({**change.facts(), "action": "update", "environment": "dev", "plugin": "namespaces", + "capacity": "fits", "capacityFresh": True}) + + +# The use is known and above the target, or could not be read: one fact, one answer (fail closed is in the fact). +USES = [{"pods": "15"}, None] + + +@pytest.mark.parametrize("used", USES) +def test_a_file_without_the_rule_does_not_open_the_gate(cat, used): + """Before #256 the fact was always false, so a file without the threshold never answered it: one approver of + defaults.group, as for beyondTier, and no auto-approval.""" + decision = _decision(cat, [], used) + assert decision.auto is None and decision.auto_fallback == "rules-added-approvers" + assert [(s.group, s.count, s.reason) for s in decision.slots] == [("approver-platform", 1, "Quota below what pods request")] + assert "quota below what pods request, and no rule reads quotaBelowRequested: +1 approver-platform" in decision.reasons + other = _decision(cat, [], used, defaults={"group": "approver-sre"}) + assert [(s.group, s.count) for s in other.slots] == [("approver-sre", 1)] + # a rule that is false for this request reads nothing: the gate stays shut + prod_only = _decision(cat, [{"when": 'quotaBelowRequested and environment == "prod"', "add": 2}], used) + assert [(s.group, s.count) for s in prod_only.slots] == [("approver-platform", 1)] + + +@pytest.mark.parametrize("used", USES) +@pytest.mark.parametrize("threshold,slots,auto", [ + ({"when": "quotaBelowRequested", "add": 1}, [("approver-platform", 1)], None), # the shipped rule + ({"when": "quotaBelowRequested", "group": "approver-platform", "add": 2}, [("approver-platform", 2)], None), + ({"when": "quotaBelowRequested", "group": "approver-dev", "add": 1}, [("approver-dev", 1)], None), + ({"when": "quotaBelowRequested", "add": 0}, [], "auto:updates"), # "a rule that answers and adds no approver" +]) +def test_a_rule_that_reads_the_fact_is_the_sites_answer(cat, used, threshold, slots, auto): + """approval-rules.yaml is the site's policy: its rule stands with its own group and count, and nothing is added to it.""" + decision = _decision(cat, [threshold], used) + assert [(s.group, s.count) for s in decision.slots] == slots + assert decision.auto == auto + assert not any("no rule reads quotaBelowRequested" in line for line in decision.reasons) + + +@pytest.mark.parametrize("key,short,old,tighter,used", [ + ("requests.cpu", "cpu", "2", "500m", "750m"), + ("requests.memory", "memory", "4Gi", "1Gi", "1536Mi"), +]) +def test_tighter_alias_in_the_target_is_a_decrease(cat, key, short, old, tighter, used): + change = cat.compare("dev", "small", {key: old}, "small", {short: tighter, key: old}, {key: used}) + assert change.below_used == [key] + + +@pytest.mark.parametrize("old,new,expected", [ + ({"requests.cpu": "2", "pods": "20"}, {"requests.cpu": "1", "pods": "20"}, ["requests.cpu"]), + ({"requests.cpu": "2", "pods": "20"}, {"requests.cpu": "2", "pods": "30"}, []), # kept and raised + ({"requests.cpu": "2", "pods": "20"}, {"pods": "20"}, []), # a bound removed + ({}, {"requests.cpu": "1", "pods": "20"}, ["requests.cpu", "pods"]), # no bound in Git is no limit + ({"pods": "20"}, {"requests.cpu": "1", "pods": "20"}, ["requests.cpu"]), # an adopted quota gains a bound + ({"pods": "20"}, {"cpu": "1", "pods": "20"}, ["requests.cpu"]), # ... by its short name + ({"requests.memory": "4Gi"}, {"requests.memory": "4Gi", "memory": "1Gi"}, ["requests.memory"]), # a tighter short name + ({"cpu": "500m", "requests.cpu": "2"}, {"requests.cpu": "1"}, []), # the short name bound 500m +]) +def test_lowered_names_the_sizable_bounds_that_a_change_lowers(cat, old, new, expected): + """Only such a change reads the pods' use (Pipeline._use_if_lowered), and compare judges the same keys.""" + assert cat.lowered(old, new) == expected + change = cat.compare("dev", "small", old, "small", new, None) + assert change.unknown_lowered == expected and change.facts()["quotaBelowRequested"] is bool(expected) + + +@pytest.mark.parametrize("used,below,unknown", [ + ({"requests.cpu": "3", "pods": "5"}, ["requests.cpu"], []), # the pods request 3 cores: a first bound of 2 is below + ({"requests.cpu": "1500m", "pods": "5"}, [], []), # they fit under it + ({"pods": "5"}, [], ["requests.cpu"]), # a quota reports no use of a key it does not bound + (None, [], ["requests.cpu"]), +]) +def test_a_first_bound_on_a_key_that_git_left_unbounded_is_judged_against_the_use(cat, used, below, unknown): + """An adopted quota that bounds pods only, moved to a quota with requests.cpu: 2. No bound is no limit, not 0, so the + new bound can refuse new pods. The delta and the percent keep counting the absent key as 0.""" + change = cat.compare("dev", "small", {"pods": "20"}, "small", {"requests.cpu": "2", "pods": "20"}, used) + assert (change.below_used, change.unknown_lowered) == (below, unknown) + assert change.facts()["quotaBelowRequested"] is bool(below or unknown) + assert change.delta["requests.cpu"] == 2 and change.increase_pct["requests.cpu"] == 100.0 + diff --git a/cmapi/tests/core/test_team_key_258.py b/cmapi/tests/core/test_team_key_258.py index c6e82c39..f5b42a04 100644 --- a/cmapi/tests/core/test_team_key_258.py +++ b/cmapi/tests/core/test_team_key_258.py @@ -71,3 +71,13 @@ def test_every_shipped_copy_names_a_declared_team_label(name): """A shipped file whose team label is not declared would give no namespace a team, and the allowance would apply to none.""" keys = MetadataKeys(shipped()[name]) assert keys.team_key in keys.rules["label"], (name, keys.team_key) + + +def test_company_create_schema_identifies_the_placement_team(company): + labels = MetadataKeys(company).keys_view()["labels"] + assert labels["x-cmapi-team-key"] == "company.net/mnemonic" + + +def test_additional_company_example_declares_its_effective_team_key(): + keys = MetadataKeys.load(EX / "cluster-configs/policies/metadata-keys.company-479.yaml") + assert keys.team_key in keys.rules["label"] diff --git a/cmapi/tests/service/test_expire_check_263.py b/cmapi/tests/service/test_expire_check_263.py index f0db07bd..0d07197c 100644 --- a/cmapi/tests/service/test_expire_check_263.py +++ b/cmapi/tests/service/test_expire_check_263.py @@ -230,6 +230,25 @@ def test_the_expired_namespace_policy_approves_and_the_prune_still_waits_for_an_ assert kube.get_object("Namespace", None, NAME) is not None, "no timer removes a namespace: the prune waits" +def test_the_expiry_delete_counts_against_the_teams_daily_allowance(world, monkeypatch, mail): + """PR #771 review, T1. docs/01, "Guards no policy can switch off": a matching request still goes to humans "when the + team's daily allowance is used"; expired-namespace is excepted from the guard on deletes only. Submit skipped the count + for every delete, so the policy approved a team's expiry deletes without limit.""" + from cmapi.core.db.repo import RequestRepo + + client, ctx, git, kube, validator, keys = world + d = _expiring_namespace(world, monkeypatch) # the create was auto-approved today: one of the team's allowance + with ctx.db.session() as s: + assert RequestRepo(s).auto_approvals_today("payments") == 1 + monkeypatch.setattr(ctx.cfg.approvals, "max_per_team", 1) + run_check(ctx, monkeypatch, d + timedelta(days=7)) + [row] = expiry_deletes(ctx) + assert row.team == "payments" + assert (row.requirement["auto"], row.requirement["autoFallback"]) == (None, "team-allowance"), row.requirement + assert row.status == "pending_approval" and [s["group"] for s in row.requirement["slots"]] == ["approver-platform"] + assert kube.get_object("Namespace", None, NAME) is not None + + def test_a_guard_holds_the_delete_and_opens_nothing(world, monkeypatch): """One notice only (noticesSentAtLeast2): held, listed in the log, tried the next day.""" client, ctx, git, kube, validator, keys = world diff --git a/cmapi/tests/service/test_review_771.py b/cmapi/tests/service/test_review_771.py new file mode 100644 index 00000000..b6a5b14b --- /dev/null +++ b/cmapi/tests/service/test_review_771.py @@ -0,0 +1,146 @@ +"""PR 771 decision boundaries that can be tested without a running cluster or database.""" +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from cmapi.capacity.usage import NoUsage +from cmapi.core.approvals import ApprovalRules +from cmapi.core.clients.kube import WatchCache +from cmapi.core.metadata import MetadataKeys +from cmapi.core.models import ExpirationRow, NamespaceCreate +from cmapi.core.pipeline import EXPIRY_REQUESTER, Pipeline, Plan, folder_etag +from cmapi.core.ports import CapacityResult +from conftest import EXAMPLES + + +@pytest.mark.parametrize("spec", [{"scopes": ["BestEffort"]}, + {"scopeSelector": {"matchExpressions": [{"scopeName": "Terminating", + "operator": "Exists"}]}}]) +def test_scoped_status_cannot_measure_an_unscoped_target(spec): + cache = WatchCache(Mock()) + for kind, meta, fields in [ + ("Namespace", {"name": "billing"}, {}), + ("ResourceQuota", {"name": "billing-quota", "namespace": "billing"}, + {"spec": spec, "status": {"used": {"requests.memory": "1Gi"}}}), + ]: + cache._event(kind, {"type": "ADDED", "object": {"metadata": meta, **fields}}) + pipeline = Pipeline.__new__(Pipeline) + pipeline.registry = Mock() + pipeline.registry.cache.return_value = cache + assert pipeline.quota_used("CRC", "billing", {"metadata": {"name": "billing-quota"}}) is None + + +def test_team_expiry_delete_counts_prior_auto_approvals(): + rules = ApprovalRules.load(EXAMPLES / "instances/nonprod/approval-rules.yaml") + rules.max_per_team = 1 + facts = dict(action="delete", environment="dev", plugin="namespaces", team="billing", reason="expired", + noticesSentAtLeast2=True, noOpenRequest=True, notProtected=True, noticesSent=2) + pipe = Pipeline.__new__(Pipeline) + pipe.cfg = SimpleNamespace(name="nonprod", allowed_environments={"dev"}, approvals=rules) + pipe.auto_paused = lambda session: False + plan = Plan("CRC", "ns", "dev", "delete", "namespaces", None, {}, {}, {}, rules.decide(facts), + CapacityResult("fits", True, None, {}), facts, Mock(), [], "head", reason="expired") + assert plan.requirement.auto == "auto:expired-namespace" + repo = Mock() + repo.auto_approvals_today.return_value = 1 + row = pipe.submit(EXPIRY_REQUESTER, plan, repo, Mock(), idempotency_key=None, body_fingerprint="test", + justification="expiry") + assert row.team == "billing" + assert row.requirement["autoFallback"] == "team-allowance" + assert row.requirement["auto"] is None + + +@pytest.mark.parametrize("model,field", [(NamespaceCreate, "placement_id"), (ExpirationRow, "team")]) +def test_public_team_field_names_the_configuration(model, field): + assert "teamKey" in model.model_fields[field].description + + +def test_legacy_team_value_counts_after_configuring_another_label(): + from sqlalchemy import create_engine, text + from sqlalchemy.orm import Session + + from cmapi.core.db.repo import RequestRepo + + keys = MetadataKeys.load(EXAMPLES / "cluster-configs/policies/metadata-keys.company.yaml") + # The pre-upgrade row's team came from cmapi.net/team. Exercise the repository query + # using the three columns it reads, including JSON ->> extraction, without a DB server. + with Session(create_engine("sqlite://")) as session: + session.execute(text("create table change_requests (team text, created_at timestamp, requirement json)")) + session.execute(text("insert into change_requests values (:team, CURRENT_TIMESTAMP, :req)"), + [{"team": "abc", "req": '{"auto":"auto:create"}'}, + {"team": "abc", "req": '{"auto":"none-required"}'}, + {"team": "other", "req": '{"auto":"auto:create"}'}]) + assert RequestRepo(session).auto_approvals_today(keys.team_of({"company.net/mnemonic": "abc"})) == 1 + + +def test_company_team_matches_placement_hold(): + from cmapi.core.errors import Problem + + keys = MetadataKeys.load(EXAMPLES / "cluster-configs/policies/metadata-keys.company.yaml") + pipe = Pipeline.__new__(Pipeline) + pipe.capacity = Mock() + pipe.capacity.placement.return_value = SimpleNamespace(cluster_id="CRC", env="dev", team="abc", cpu=2, memory=0) + body = {"placementId": "pl-test"} + team = keys.team_of({"cmapi.net/team": "old", "company.net/mnemonic": "abc"}) + assert pipe._placement(body, "create", "CRC", "dev", team, {"requests.cpu": "500m"}) == "pl-test" + with pytest.raises(Problem, match="another target"): + pipe._placement(body, "create", "CRC", "dev", "old", {}) + + +# ---- reviewer 2: the pods' use is read only for a change that lowers a bound (the PR head failed CI's service job here) +def _existing(tier: str): + """test_review_479_expiry's planner (stand-ins for Git, the cluster and the validator), with one namespace in Git.""" + from test_review_479_expiry import BODY, OLA, planner + from cmapi.core.pipeline import folder_etag + + pipe = planner() + first = pipe.plan_namespace(OLA, "CRC", {**BODY, "tier": tier}, action="create") + stored = {p: t for p, t in first.files.items() if t is not None} + pipe.git.read_folder.return_value = stored, "base" + pipe.usage = NoUsage() + return pipe, OLA, BODY["namespace"], folder_etag(stored) + + +@pytest.mark.parametrize("change", [{"labels": {"cmapi.net/cost-center": "cc-1234"}}, {"tier": "medium"}]) +def test_a_change_that_lowers_no_bound_does_not_read_the_pods_use(change): + """A label change and a raise cannot fall below the use. On the PR head each read the watch cache, logged + quota_used_unknown on a stale watch, and failed where the cluster is a stand-in (CI: test_review_479_expiry, 2 failed).""" + pipe, ola, ns, etag = _existing("small") + pipe.quota_used = Mock(side_effect=AssertionError("the use was read for a change that lowers no bound")) + plan = pipe.plan_namespace(ola, "CRC", {"namespace": ns, **change}, action="update", if_match=etag) + assert plan.facts["quotaBelowRequested"] is False + pipe.registry.cache.return_value.kind_stale.assert_not_called() + + +@pytest.mark.parametrize("used,below", [({"requests.cpu": "0", "requests.memory": "0", "pods": "0"}, False), + ({"requests.cpu": "12", "requests.memory": "0", "pods": "0"}, True), (None, True)]) +def test_a_change_that_lowers_a_bound_reads_the_pods_use_once(used, below): + pipe, ola, ns, etag = _existing("medium") + pipe.quota_used = Mock(return_value=used) + plan = pipe.plan_namespace(ola, "CRC", {"namespace": ns, "tier": "small"}, action="update", if_match=etag) + assert pipe.quota_used.call_count == 1 and pipe.quota_used.call_args.args[:2] == ("CRC", ns) + assert plan.facts["quotaBelowRequested"] is below and plan.facts["tierChange"] == "down" + + +@pytest.mark.parametrize("used,below", [({"pods": "3"}, True), (None, True), + ({"requests.cpu": "12", "requests.memory": "1Gi", "pods": "3"}, True), + ({"requests.cpu": "1", "requests.memory": "1Gi", "pods": "3"}, False)]) +def test_an_unbounded_quota_moved_to_a_tier_reads_the_pods_use(used, below): + """Git's quota bounds pods only, as an adopted one can. A change to small (8 cores) gives CPU and memory their first + bound: the use is read, 12 cores requested is below, and a use that the live quota does not report fails closed.""" + import yaml + + pipe, ola, ns, _ = _existing("small") + stored, base = pipe.git.read_folder.return_value + path = next(p for p, t in stored.items() if yaml.safe_load(t)["kind"] == "ResourceQuota") + quota = yaml.safe_load(stored[path]) + quota["spec"]["hard"] = {"pods": quota["spec"]["hard"]["pods"]} + stored = {**stored, path: yaml.safe_dump(quota)} + pipe.git.read_folder.return_value = stored, base + pipe.quota_used = Mock(return_value=used) + plan = pipe.plan_namespace(ola, "CRC", {"namespace": ns, "labels": {"cmapi.net/cost-center": "cc-1234"}}, + action="update", if_match=folder_etag(stored)) + assert pipe.quota_used.call_count == 1 + assert plan.facts["quotaBelowRequested"] is below + diff --git a/docs/02-technical-design-v2.md b/docs/02-technical-design-v2.md index d9d60484..39b7715e 100644 --- a/docs/02-technical-design-v2.md +++ b/docs/02-technical-design-v2.md @@ -1362,7 +1362,7 @@ At startup an invalid catalog stops cmapi with every problem listed. On reload c | Plan a create or tier change | resolve(env, tier), quota\_for(env, tier, quota, approved), limits\_for(env, tier, limitRange, hard, approved) | The full spec.hard and the full LimitRange values; each custom value is checked against the bounds and step. A value that Git already holds (approved) is not checked against the bounds again | | Beyond the tier | beyond(env, tier, hard, limit range), rendered\_overrides(quota object, the LimitRange objects) | Each overridable value that differs from the tier, for the facts beyondTier and beyondTierKeys; and the approved overrides of a namespace, read from the annotation cmapi.net/beyond-tier | | Capacity and placement | the resolved requests.cpu and requests.memory | The size reserved; an increase reserves only the delta | -| Approval rules | compare(env, old tier, old hard, new tier, new hard, used) | Facts tier, tierChange (up, down, same, to-custom, from-custom, custom), quotaIncreasePct and quotaBelowRequested. `used` is the live ResourceQuota's status.used from the watch cache (Pipeline.quota_used, #256); a key that the change lowers and whose use cannot be read counts as below (fail closed) | +| Approval rules | compare(env, old tier, old hard, new tier, new hard, used) | Facts tier, tierChange (up, down, same, to-custom, from-custom, custom), quotaIncreasePct and quotaBelowRequested. `used` is the live ResourceQuota's status.used from the watch cache (Pipeline.quota_used, #256); a lowered sizable bound counts as below when its namespace-wide use exceeds the target or is unknown (fail closed). The rules answer the fact: the threshold `quotaBelowRequested` of approval-rules.yaml, or, in a file where no true threshold reads it, one approver of `defaults.group` | | Render | render(namespace, cluster, instance, env, tier, request, quota, limits, approved) | The ResourceQuota and one LimitRange for each resource, called by core/render/manifests.py, which writes each to its own file. Each object names its own beyond-tier keys in cmapi.net/beyond-tier | | PATCH or PUT .../quota | normalise(env, hard) | The named tier when the values equal one exactly, otherwise custom | | Quota view | is\_outdated(env, tier, rendered hash) | State tier-outdated, a filter on GET /api/v1/quotas | diff --git a/docs/09-portal-ui-testing.md b/docs/09-portal-ui-testing.md index 8eb315c7..426d0e14 100644 --- a/docs/09-portal-ui-testing.md +++ b/docs/09-portal-ui-testing.md @@ -302,7 +302,7 @@ words of `core/metadata.py`, and refuses `expiresAt` where `x-cmapi-expiration` | Check | Command, in `cmapi-portal-ui/` | Result | |---|---|---| | The pure parts of the form | `node tests/api/direct.test.mjs` (479-P1, P2, P4, P6, P10 twice, P11, P12) | the name's ends and checks (63 characters is the limit, `abc--x-dev` is taken); a default copied and never sent until edited; every refusal word of an extra key and value; UTF-8 bytes; the expiry rules per environment from `enabled`, never from the name; no company domain or sample value in `src/portal` | -| Each keyword of the answer is read | `node tests/contract.test.mjs` | `x-cmapi-expiration`, `propertyNames` and its branches, `x-cmapi-other-keys`, `x-cmapi-namespace-suffix` and `x-cmapi-default-from` are read, on the three answers | +| Each keyword of the answer is read | `node tests/contract.test.mjs` | `x-cmapi-expiration`, `propertyNames` and its branches, `x-cmapi-other-keys`, `x-cmapi-team-key`, `x-cmapi-namespace-suffix` and `x-cmapi-default-from` are read, on the three answers; the form finds the team that placement ranks for by the answer's team label (`teamFieldOf`, #258) | | Each behaviour at 390, 820 and 1440 px in each theme | checks 479-P2, 479-P3-P5, 479-P6-P7, 479-P9-P11, 479-P12 (two), each on a fresh form six times | pass; no console error | | The page says what the mockup says, both ways | check 6, New namespace part, against `mockups/portal/new-namespace-479.html` | 82 strings of the mockup on the page; each one it does not show is listed with its reason; nothing invented outside the listed additions (MOCKUP-CONTRACT.md) | | Layout and axe | check 7 with two new views (`new-479-problems`, `new-479-checked`) | 6 views, 3 widths, 2 themes, no sideways scroll; 24 axe scans, no serious or critical finding | diff --git a/docs/14-authorization.md b/docs/14-authorization.md index a0d9d7bd..66e05526 100644 --- a/docs/14-authorization.md +++ b/docs/14-authorization.md @@ -200,7 +200,7 @@ The tests `test_environment_role_cannot_*` cover each route group (`test_review_ ### Step 5: who can approve -An approval has more checks than the permission (`approvals.py:337-364`). They are in this order: +An approval has more checks than the permission (`approvals.py:346-373`). They are in this order: | Check | Refusal | |---|---| @@ -283,7 +283,7 @@ When a person calls, cmapi records the request under the caller of the token. Th | Value | Where it comes from | Where it is kept | |---|---|---| -| `sub` | The claim `sub` (`claims.py:70`) | The database. Self-approval compares it (`approvals.py:355-356`) | +| `sub` | The claim `sub` (`claims.py:70`) | The database. Self-approval compares it (`approvals.py:364-365`) | | Username | The claim `preferred_username` (`claims.py:78`) | The database, and as a label of the namespace (`claims.py:3-5`) | | `email` | The claim `email` (`claims.py:74`) | The database | | `employee_id` | The claim `employee_id` (`claims.py:78`) | The database | @@ -298,7 +298,7 @@ A person calls as themselves. If a person sends `onBehalfOf`, cmapi refuses with A shared human account, for example `cmapi.requester`, that submits for many people is not in the design. A person cannot use `onBehalfOf` (`checks.py:74-78`), so a shared account would be recorded as the requester. It would have three effects: - Attribution is lost. Each request would carry the `sub` and the username of the shared account, and not those of the person. -- The self-approval check fails. The check compares `sub` values (`approvals.py:355-356`). The requester would carry the `sub` of the shared account. A person who submits through it and then approves with their own account has another `sub`, so the check would not refuse. +- The self-approval check fails. The check compares `sub` values (`approvals.py:364-365`). The requester would carry the `sub` of the shared account. A person who submits through it and then approves with their own account has another `sub`, so the check would not refuse. - The employee ID record is lost. The token of the shared account has one `employee_id`, or none, and a person's write needs one when the instance requires it (`checks.py:79-81`). A tool that must act for people has its own path: see the next section. @@ -321,7 +321,7 @@ A tool signs in with the client credentials grant. It is a service client, or an | The tool sends `onBehalfOf`: a username or an employee ID | cmapi looks the value up in the directory. The person must be enabled, or the answer is 422 `unknown-user`. The person is recorded as the requester and the tool as the caller. The request is recorded as automated | `checks.py:89-95` | | A person sends `onBehalfOf` | 422 `on-behalf-of-not-allowed` | `checks.py:74-78`; `problem_docs.py:104` | -Self-approval uses the requester and the submitter. The ledger refuses the requester as approver: `requester_sub` is the `sub` of the named person (`checks.py:49-53`, `pipeline.py:866`, `approvals.py:355-356`). It also refuses the submitter, which is the `sub` of the tool, unless the approval rule has `selfApproval: true` (`cmapi/src/cmapi/core/db/repo.py:247-249`, `approvals.py:353-354`). The record keeps the submitter in `submittedBySub`, and the response leaves it out (`checks.py:59-64`, `views.py:25-27`). +Self-approval uses the requester and the submitter. The ledger refuses the requester as approver: `requester_sub` is the `sub` of the named person (`checks.py:49-53`, `pipeline.py:868`, `approvals.py:364-365`). It also refuses the submitter, which is the `sub` of the tool, unless the approval rule has `selfApproval: true` (`cmapi/src/cmapi/core/db/repo.py:247-249`, `approvals.py:362-363`). The record keeps the submitter in `submittedBySub`, and the response leaves it out (`checks.py:59-64`, `views.py:25-27`). With `onBehalfOf`, cmapi trusts the tool to name the person. The directory proves that the person exists and is enabled. It does not prove that the person signed in. @@ -370,7 +370,7 @@ The code `forbidden` has two more causes. Each is a refusal of the code, not of | A caller cancels a request that is not theirs and does not hold `namespaces:protect` in its environment | "Only the requester or an operator can cancel" | `cmapi/src/cmapi/core/lifecycle.py:125`, `cmapi/src/cmapi/routers/requests.py:211` | | A write sets or removes an operator-only label or annotation (`cmapi.net/protected`, `do-not-delete`) and the caller does not hold `namespaces:protect` in the environment | "Needs namespaces:protect in . Keys: ." (the cluster's environment, #532) | `cmapi/src/cmapi/core/metadata.py:1434` | -The ledger also refuses a relay client without `approvals:relay` with this code ("Relay client lacks approvals:relay", `cmapi/src/cmapi/core/approvals.py:347`), but no route can reach it: the approve route in `routers/requests.py` passes no relay to `ApprovalLedger.approve` (see "What is not built"). +The ledger also refuses a relay client without `approvals:relay` with this code ("Relay client lacks approvals:relay", `cmapi/src/cmapi/core/approvals.py:356`), but no route can reach it: the approve route in `routers/requests.py` passes no relay to `ApprovalLedger.approve` (see "What is not built"). A sample 403, taken from a run of the service suite's app on 2026-11-13. A caller with the role `cmapi-viewer` sent `POST /api/v1/admin/auto-approval:pause`: @@ -394,7 +394,7 @@ A sample 403, taken from a run of the service suite's app on 2026-11-13. A calle |---|---| | Routes for quotas, service accounts, grants, configuration, cluster onboarding, reload, events and audit export | Not built. Their permissions exist in `authz.py`, and no route uses them | | `adoption:write`: the scan of a cluster and the unmanaged-namespaces report (#252's admin operations) | Not built. The adoption of one namespace is self-service: its three routes need `namespaces:write` in the cluster's environment, and the approval rules gate it (#739, the owner's decision of 2026-11-26 on #26). The routes declare and enforce the same permission (`cmapi/src/cmapi/plugins/adoption/router.py`, `ADOPT_PERMISSION`) | -| The approval relay for email, ServiceNow and chat (`approvals:relay`) | The check exists in `approvals.py:344-347`. No route accepts a relayed approval | +| The approval relay for email, ServiceNow and chat (`approvals:relay`) | The check exists in `approvals.py:353-356`. No route accepts a relayed approval | | A scope by team or by namespace name | Not designed. A role with `namespaces:create` can ask for each name that is not reserved (`authz.py:8-10`) | ## Proof diff --git a/docs/16-data-model.md b/docs/16-data-model.md index e38f12d4..36b07546 100644 --- a/docs/16-data-model.md +++ b/docs/16-data-model.md @@ -101,7 +101,7 @@ One row is one write to one namespace. The row is the only record of a request: | `status` | One of 15 states (`S` in `core/lifecycle.py`). See "The states" below | `RequestRepo.insert` and `RequestRepo.move`, from the table in `core/lifecycle.py` | | `reason` | A short code for the cause of a request: `expiration:extend` for an expiry extension, and `revert` for a revert request. Null for a plain write. The design has `expired` for the delete that the daily expiry check opens, and a rule of `approval-rules.yaml` reads it. The check is not built, and no code sets `expired` today | `Pipeline.submit` | | `justification` | The text that the requester wrote | `Pipeline.submit` | -| `team` | The value of the label `cmapi.net/team` at plan time. The daily allowance of auto-approvals counts requests for this value (`RequestRepo.auto_approvals_today`) | `Pipeline.submit` | +| `team` | The value of the team label at plan time: the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default (#258). The daily allowance of auto-approvals counts requests for this value (`RequestRepo.auto_approvals_today`) | `Pipeline.submit` | | `plan` | The stored plan, as JSON. See "The JSON columns" below | `Plan.stored` (`core/pipeline.py`) | | `plan_hash` | SHA-256 of the rendered files. The worker checks that the files of the pull request still have this hash before it merges | `Pipeline.submit` | | `base_sha` | The Git commit that the plan read, shown as `baseSha` in the request view. No code compares it. `open_pr` compares the folder as Git holds it now with `plan.prev`, and a difference moves the request to `superseded` (`jobs/open_pr.py`) | `Pipeline.submit` | diff --git a/docs/18-configuration.md b/docs/18-configuration.md index 26f1060c..e6f28901 100644 --- a/docs/18-configuration.md +++ b/docs/18-configuration.md @@ -437,7 +437,7 @@ The rules for the labels and the annotations that a requester sets on a namespac | `adoptionLabels` | mapping of key to `{recognise: [values]}` | `{}` | Labels that mark a namespace that another tool made. A requester cannot set them: the class of such a key is `reserved`. Today cmapi reads only the keys, for that class. The adoption (story #26) reads the values: a namespace that carries one is listed as `recognised` among the candidates, and the plan reports it as `adoption-label` | | `sensitiveKeys` | list of keys | `[]` | A change of the value of one of these keys adds the fact `sensitiveKeyChanged`, once per request: a value that Git holds changes or goes, or a change of an existing namespace adds a required or extra key (#481). The first value of a create, and the first set of an operator-only key, are not a change. The shipped files list `cmapi.net/protected` and `do-not-delete`: protecting a namespace needs no extra approval, and removing the protection adds one approver-platform approval (#366) | | `emailDomains` | list of domains | `[]` | The mail domains for a key with `format: email-in-domains`. A key of that format needs at least one domain | -| `teamKey` | a label key | `cmapi.net/team` | The label that names a namespace's team (#258). Placement (`POST /api/v1/capacity:place`, whose `team` the create's label must match), the approval fact `team`, the daily allowance `maxPerTeamPerDay`, the team's rate-limit bucket, `change_requests.team` and the `team` of the namespace, quota and expiration lists read it. A key that the file names here must be a label that `requiredLabels` or `extraLabels.keys` declares, or the file is refused (`teamKey: is not a label that requiredLabels or extraLabels.keys declares`): a key read on no namespace would leave the allowance applying to none, silently. Without the stanza it is `cmapi.net/team`, declared or not, as before the stanza. The company example names `company.net/mnemonic` | +| `teamKey` | a label key | `cmapi.net/team` | The label that names a namespace's team (#258). A client that places before it creates, as the portal does, reads a key other than `cmapi.net/team` from `labels.x-cmapi-team-key` of `GET /api/v1/metadata-keys`, and sends that label's value as the placement's `team`. Placement (`POST /api/v1/capacity:place`, whose `team` the create's label must match), the approval fact `team`, the daily allowance `maxPerTeamPerDay`, the team's rate-limit bucket, `change_requests.team` and the `team` of the namespace, quota and expiration lists read it. A key that the file names here must be a label that `requiredLabels` or `extraLabels.keys` declares, or the file is refused (`teamKey: is not a label that requiredLabels or extraLabels.keys declares`): a key read on no namespace would leave the allowance applying to none, silently. Without the stanza it is `cmapi.net/team`, declared or not, as before the stanza. The company example names `company.net/mnemonic` | | `liveOnlyKeys` | list of key globs | `[kubernetes.io/metadata.name, "openshift.io/*", "argocd.argoproj.io/*", app.kubernetes.io/instance]` | Keys that the cluster or its controllers write on a live namespace and Git never holds. `GET .../namespaces/{ns}` compares each governed, extra and operator-only key of Git with the live namespace (`sync`, #481) and leaves these out, so they are never drift. `*` matches as in `fnmatch`. Without the stanza, the default applies; an empty list compares every such key. System and reserved keys are never compared | Where `emailDomains` is set: in each deployment's metadata configuration. On CRC it is `deploy/manifests/environments/crc/20-config.yaml`, key `emailDomains`; on kind it is the same key in `deploy/manifests/environments/kind/20-config.yaml`. The examples are `examples/cluster-configs/policies/metadata-keys.yaml` (`[ephico2real.com]`, a placeholder) and the company profile `metadata-keys.company.yaml` (`[company.net]`). To change it on CRC, edit that key, apply the ConfigMap, then `oc rollout restart deploy/cmapi-api deploy/cmapi-worker -n cmapi`. The domain is checked for format only: cmapi never looks a DL up. @@ -638,6 +638,7 @@ What the schema says, for each map: | `description`, `example` | `description` (with the rule in words) and `examples`. Each declared key also has `x-cmapi-rule`: the rule in the words that a refusal's `detail` uses (`missing_required_key`), so a client says what the API says | | `operatorOnly` | A property with `x-cmapi-operator-only: true` | | Every declared and operator-only key | `x-cmapi-edit: {mode, reason, sensitive}`: how the key may change on an existing namespace (#481). `mode` is `fixed` (a `namespacePrefix` or `namespaceSuffix` key), `automatic` (`value: {from: ...}`), `required`, or `optional` (an extra key, and an operator-only key for a caller with `namespaces:protect`); `reason` is the words a person sees, such as "Part of the namespace's fixed name."; `sensitive` is true for a key of `sensitiveKeys`, whose change adds one approval. The same on a create and a change: `MetadataKeys.edit_rule` decides it from the file, in the order of the #481 design, section 3 | +| `teamKey` | `x-cmapi-team-key` on the labels map of a create, when the key is not `cmapi.net/team`: the label whose value is the `team` of `POST /api/v1/capacity:place` (#258). Left out for `cmapi.net/team`, so an answer without it reads as before the stanza | | `allowOther` | `propertyNames`: a declared key, or a key under an allowed prefix that is not a system key, an adoption label, a key of the other kind or under a reserved prefix. `additionalProperties`: the value rule of those keys. `x-cmapi-other-keys`: the prefixes, limits and any sensitive additional keys | The same two maps are served on their own by `GET /api/v1/metadata-keys` (#336), with the permission `objects:read`, also when `docs.enabled` is false: `{"labels": ..., "annotations": ..., "x-cmapi-expiration": ...}`, the first two exactly the objects of `NamespaceCreate` above without their `title`, `description` and `examples` (a service test holds the two equal on the reference and the company file), and the third the `x-cmapi-expiration` of `NamespaceCreate.expiresAt` (`expiration.yaml` below, #479), so the `ETag` changes when a rule in the answer does (`maxExtensionDays` is not in it: `GET /api/v1/expirations` serves it). The portal's New namespace form builds its fields from it. The first request builds the answer and caches it for the loaded files, which a change restarts the pods to load. It has a strong `ETag` over its bytes and `Cache-Control: private, no-cache`. `If-Match` is read first (#590): `If-Match: *` passes, and any other value must list the `ETag`, by the strong comparison, or the answer is `412`. Then a matching `If-None-Match` answers `304`. @@ -791,7 +792,7 @@ A requirement is a list of slots, one for each approving group. The ledger fills | `thresholds[].reason` | text | The `when` text | Text in the `reasons` of the request | | `protected.labels` | list of `key=value` | `[]` | A namespace whose labels in Git match one of these is protected: a delete request is refused (`namespace-protected`), also the delete after it expires. A request may set such a label only to the listed value, or remove it with `null` (`invalid_value` otherwise). `GET` on a namespace gives `protected` and `protectedBy` from them (#366). List only operator-only keys here, or a requester can protect a namespace | | `autoApproval.enabled` | boolean | `false` | The master switch for auto-approval | -| `autoApproval.maxPerTeamPerDay` | integer | `20` | The most auto-approvals for one team in a day (UTC). cmapi counts at submit, for a request with a team. `0` stops each auto-approval, also of a request with no team | +| `autoApproval.maxPerTeamPerDay` | integer | `20` | The most auto-approvals for one team in a day (UTC). cmapi counts at submit, for a request with a team, the delete that `expired-namespace` approves included. `0` stops each auto-approval, also of a request with no team | | `autoApproval.policies[]` | list | `[]` | The policies. See below | ### The facts @@ -803,7 +804,7 @@ A `when` line reads these facts. The names are fixed in the code. An unknown nam | `plugin`, `action`, `environment`, `namespace`, `clusterId`, `reason`, `team`, `tier` | The request | `core/pipeline.py` | | `tierChange` | `up`, `down`, `same`, `to-custom`, `from-custom` or `custom`. Set for a change of an existing namespace only | `TierCatalog.compare` | | `quotaIncreasePct` | The largest increase of a sizable key, in percent. Set for a change of an existing namespace only | `QuotaChange.quota_increase_pct` | -| `quotaBelowRequested` | On a change of an existing namespace's quota (a plan, or a revert): a sizable key's new hard value is below what the pods request now, so Kubernetes would refuse new pods (#256). The use is the `status.used` of the live ResourceQuota that Git's quota is, from the cluster's watch cache. A key that the change lowers and whose use cannot be read counts as below (fail closed): the watch has not listed, is stale (no good read for 30 minutes) or is refused (401, 403), or the live namespace has no such quota. A namespace that the watch does not hold has no pods. A key that the change does not lower is not below for want of a read. The planner logs `quota_used_unknown` with the reason | `Pipeline.quota_used`, `TierCatalog.compare` | +| `quotaBelowRequested` | On a change of an existing namespace's quota (a plan, or a revert): the change lowers a sizable key's hard value below what the pods request now, so Kubernetes would refuse new pods (#256). The use is the `status.used` of the live ResourceQuota that Git's quota is, from the cluster's watch cache. A key that the change lowers and whose use cannot be read counts as below (fail closed): the watch has not listed, is stale (no good read for 30 minutes) or is refused (401, 403), or the live namespace has no matching unscoped quota or usable value for that key. A namespace that the watch does not hold has no pods. A key that Git's quota does not bound has no limit, so its first bound lowers it: an adopted quota without `requests.cpu`, moved to a tier. Its use is rarely readable, since a live quota reports `status.used` only for the keys it bounds, so such a change usually counts as below. Removing a bound or keeping or raising its value does not trigger this fact. The shipped rule adds one approver of `defaults.group` (approver-platform). When no true threshold reads the fact, cmapi adds that approver itself, with the reason "Quota below what pods request": the fact was always false before #256, so a file without the rule never answered it, and docs/01 says "A decrease below what pods already request is refused unless approver-platform approve". A rule that reads the fact is the site's answer and stands, with its group and its count, also `add: 0`, and also for a use that could not be read (`test_a_rule_that_reads_the_fact_is_the_sites_answer`, `cmapi/tests/core/test_quota_below_requested_256.py`). The use is read only for a change that lowers a sizable bound: a label change or a raise reads no watch. The planner logs `quota_used_unknown` when it cannot use the quota object | `Pipeline.quota_used`, `TierCatalog.lowered`, `TierCatalog.compare` | | `requestToPeakRatio` | On a change of an existing namespace's quota, with `usage` `ok`: the largest planned hard limit over the namespace's 14-day peak, of a resource the change raises (#310). Absent otherwise, so a rule that reads it adds nothing | `plan_usage`, `capacity/usage.py` | | `usage` | On a change of an existing namespace's quota: `ok`, `insufficient-data` (no usage source, or under 80% of the window's samples) or `unavailable` (Thanos did not answer, or the cluster's import check found the reader without its own Thanos grants, #724). The shipped rule adds approver-platform on `usage == "unavailable"`. If the active policy has no matching usage threshold that adds that group, the planner supplies one platform slot (#310) | `plan_usage`, `capacity/usage.py` | | `capacity`, `capacityFresh` | `fits`, `warn`, `exceeded` or `unknown`, and whether the data is fresh. `unknown`, not fresh, when the cluster has neither `simulatedCapacity` nor fresh counted node allocatable, no watch cache, ResourceQuotas not listed yet, ResourceQuota reads refused (401 or 403), or a ResourceQuota watch with no good read for 30 minutes (#393). What is committed comes from the cluster's quota ledger: per namespace the smallest unscoped managed quota, scoped quotas left out (#302). The check adds the capacity that open requests hold (`capacity_reservations`, #62): each request with an increase holds it from submit until it leaves the holding states, and a hold stops counting once the ledger shows its quota. Submit checks again under the cluster's lock and takes the hold in the same transaction, so a request that fit when planned but not beside a hold taken since is refused (`exceeded`) or decided on the new answer; the last `:approve` and a `:retry` from `failed` check again and answer 422 `capacity-exceeded` when the request no longer fits | `core/capacity_backend.py`, `core/capacity_ledger.py` | diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index a970f313..8a89f086 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -23,7 +23,7 @@ Status: read from `main` at `afd1206` on 2026-11-23. Each row was read from the | `instance.yaml` | The file with the key `instance`: name, allowed environments, token issuer and audience, Git repository, identity, CORS, problem base URL, docs and policy settings. | [18-configuration.md](18-configuration.md) | | `tiers.yaml` | The tier catalog: the quota and limits of each tier in each environment. | [18-configuration.md](18-configuration.md) | | `metadata-keys.yaml` | The file of the label and annotation keys: the system keys, the keys a requester sets, `operatorOnly`, `sensitiveKeys`, `liveOnlyKeys`, and `emailDomains`. | [18-configuration.md](18-configuration.md), [metadata-keys.yaml](../examples/cluster-configs/policies/metadata-keys.yaml) | -| `teamKey`, team label | The label of `metadata-keys.yaml` that names a namespace's team (#258): placement, the approval fact `team`, the daily allowance `maxPerTeamPerDay`, the team's rate-limit bucket and `change_requests.team` read it. `cmapi.net/team` when the file has none; a declared label otherwise. The company example names `company.net/mnemonic`. | [18-configuration.md](18-configuration.md), [core/metadata.py](../cmapi/src/cmapi/core/metadata.py) | +| `teamKey`, team label | The label of `metadata-keys.yaml` that names a namespace's team (#258): placement, the approval fact `team`, the daily allowance `maxPerTeamPerDay`, the team's rate-limit bucket and `change_requests.team` read it. `cmapi.net/team` when the file has none; a declared label otherwise. `GET /api/v1/metadata-keys` names a key other than `cmapi.net/team` in `labels.x-cmapi-team-key`, which the portal's New namespace form places by. The company example names `company.net/mnemonic`. | [18-configuration.md](18-configuration.md), [core/metadata.py](../cmapi/src/cmapi/core/metadata.py) | | `approval-rules.yaml` | The file that decides, from the facts of a request, how many approvals it needs and from which groups, and which auto-approval policies apply. | [18-configuration.md](18-configuration.md) | | `authz-roles.yaml` | The file that maps each role to its permissions and, optionally, to the environments where it applies. | [core/authz.py](../cmapi/src/cmapi/core/authz.py), [18-configuration.md](18-configuration.md) | | `clusters.yaml`, `capacity.yaml` | `clusters.yaml` lists the clusters (`environment`, `writes`, `delivery`, `clusterTokens` and more). `capacity.yaml` holds the overcommit, the warn and critical commitment targets and the KPI thresholds. | [18-configuration.md](18-configuration.md) | @@ -111,7 +111,7 @@ Status: read from `main` at `afd1206` on 2026-11-23. Each row was read from the | `base_sha` (`baseSha`) | The Git commit that the plan was made against. | [core/models.py](../cmapi/src/cmapi/core/models.py) | | `request_events` | The table of one state change or note of a request, in order. `GET /api/v1/requests/{request_id}/events` reads it. Migration 0007 makes its time the insertion time. | [16-data-model.md](16-data-model.md) | | Approval | One approval of one request by one person, in `approvals`. A person counts once (migration 0002). Requesters cannot approve their own request (409 `self-approval`). | [16-data-model.md](16-data-model.md), [core/docs.py](../cmapi/src/cmapi/core/docs.py) | -| `quotaBelowRequested` | The approval fact of a quota change whose new hard value of a sizable key is below what the namespace's pods request now (the live ResourceQuota's `status.used`, #256). A lowered key whose use cannot be read counts as below (fail closed). | [18-configuration.md](18-configuration.md), [core/tiers.py](../cmapi/src/cmapi/core/tiers.py) | +| `quotaBelowRequested` | The approval fact of a quota change that lowers the hard value of a sizable key below what the namespace's pods request now (the live ResourceQuota's `status.used`, #256). A lowered key whose use cannot be read counts as below (fail closed). | [18-configuration.md](18-configuration.md), [core/tiers.py](../cmapi/src/cmapi/core/tiers.py) | | Auto-approval | An `auto:` rule of `approval-rules.yaml` that approves a plan with no person. A Kyverno warning keeps it from applying. `approvals:pause` stops it. | [18-configuration.md](18-configuration.md), [core/lifecycle.py](../cmapi/src/cmapi/core/lifecycle.py) | | `:cancel`, `:approve`, `:reject`, `:retry`, `:revert` | The verbs on `/api/v1/requests/{request_id}`, each with its permission (`requests:cancel`, `requests:approve`, `requests:reject`, `requests:retry`; `:revert` also needs `requests:retry`). | [14-authorization.md](14-authorization.md), [core/lifecycle.py](../cmapi/src/cmapi/core/lifecycle.py) | | In sync, Pending, Drift, Unknown | The state of a namespace in the portal and in the API field `state`. `pending`: an open request holds the namespace, also after the merge and before the cluster has it. `drift`: no request is open and a governed, extra or operator-only key differs between Git and the cluster, or the cluster does not have the namespace. `in-sync`: they are the same. `unknown`: cmapi cannot compare. | [schema.generated.ts](../cmapi-portal-ui/src/api/schema.generated.ts), [NamespacesTab.tsx](../cmapi-portal-ui/src/portal/NamespacesTab.tsx) | diff --git a/docs/citations.lock.json b/docs/citations.lock.json index 87fa178f..757217a4 100644 --- a/docs/citations.lock.json +++ b/docs/citations.lock.json @@ -1,5 +1,5 @@ { - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|337-364": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|346-373": [ " def approve(self, approver: Identity, *, permitted: bool | None = None, relay: Identity | None = None,", " relay_permitted: bool | None = None, comment: str = \"\") -> bool:", " \"\"\"approver is the eligible person; relay is the channel client (approvals:relay) if any.", @@ -29,20 +29,20 @@ " return self.met", "" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|344-347": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|353-356": [ " if relay is not None:", " ok = relay_permitted if relay_permitted is not None else \"approvals:relay\" in builtin_permissions(relay)", " if not ok:", " raise Problem.forbidden(\"Relay client lacks approvals:relay\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|347-347": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|356-356": [ " raise Problem.forbidden(\"Relay client lacks approvals:relay\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|353-354": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|362-363": [ " if approver.sub in self.client_owner_subs or approver.sub == self.operation_starter_sub:", " raise Problem.conflict(\"self-approval\", \"The operation starter or client owner cannot approve\")" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|355-356": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|364-365": [ " if approver.sub == self.requester_sub and not self.requirement.self_approval:", " raise Problem.conflict(\"self-approval\", \"Requesters cannot approve their own request here\")" ], @@ -519,7 +519,7 @@ "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|708-708": [ " self.cfg.roles.require(who, ADOPT_PERMISSION, env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|866-866": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|868-868": [ " requirement=requirement_to_json(req), requester=plan.requester.record(), requester_sub=plan.requester.sub," ], "docs/14-authorization.md|cmapi/src/cmapi/core/problem_docs.py|104-104": [ diff --git a/docs/reviews/2026-12-01-issue-256-258/README.md b/docs/reviews/2026-12-01-issue-256-258/README.md new file mode 100644 index 00000000..6930da62 --- /dev/null +++ b/docs/reviews/2026-12-01-issue-256-258/README.md @@ -0,0 +1,23 @@ +# PR #771 review: #256 (quotaBelowRequested reads live use) and #258 (teamKey) + +Who did what: +- Implementer: Opus 5.5 at high. +- Reviewer 1: Codex (gpt-6.2-astra, xhigh). Its [report](reviewer-1-codex.md) has 8 findings. +- Reviewer 2: Fable. [report](reviewer-2-fable.md), with an addendum. The applied [final.diff](final.diff) was made against the pristine head `cff8b36c`. +- Coordinator: Opus 5.5. It read the production hunks line by line, added one finding (below), and confirmed the applied tree is byte-identical to reviewer 2's tested `verify-b/`. + +| Finding | Ruling | +|---|---| +| Q1 to Q3 (only a lowered bound can be below the use; short-name aliases; a scoped quota cannot measure the use) | Accepted | +| Q4: an unknown or below decrease must need a person | Amended. One approver of `defaults.group` is added only when no rule reads `quotaBelowRequested`. A site rule, `add: 0` included, stands (#211, and docs/18's "a rule that answers and adds no approver") | +| T1: deletes skip the team's daily allowance at submit | Accepted. It predates the PR; no record gives a reason for it | +| T2 | Rejected: main's behaviour, kept on purpose in #719/#720. Filed #777 (Low) | +| T3: the company portal cannot place | Amended: an additive `x-cmapi-team-key`, and `teamFieldOf`. Codex's Submit rework was rejected; filed #778 (Low) | +| T4 | Accepted | +| R2-1: the PR read pod use on every change, which failed CI (`test_review_479_expiry.py`) | Fixed: the use is read only when a sizable bound is lowered | +| Coordinator: a bound added where Git held none was not "lowered" | Fixed by reviewer 2: an unbounded key counts as lowered. Its use is normally unknown, so it fails closed: a first quota on a running namespace gets an approver | + +Tests, one file at a time on the Mac: +- After: core `test_quota_below_requested_256` 33 passed (the coordinator re-ran it), `test_review_771` 16, `test_review_479_expiry` 9, `test_catalog_drift_710` 8, `test_revert_sizing` 9, service `test_quota_below_requested_256` 5. The first round also passed `test_expire_check_263` (24), the metadata and approvals files and the Node-only portal checks. +- Before: core quota 13 failed, `test_review_771` 7 failed, `test_review_479_expiry` 2 failed. +- Not run: the portal browser suites (no node_modules locally), CRC and kind. CI is the gate. diff --git a/docs/reviews/2026-12-01-issue-256-258/final.diff b/docs/reviews/2026-12-01-issue-256-258/final.diff new file mode 100644 index 00000000..7159de9e --- /dev/null +++ b/docs/reviews/2026-12-01-issue-256-258/final.diff @@ -0,0 +1,946 @@ +diff --git a/cmapi-portal-ui/src/api/schema.generated.ts b/cmapi-portal-ui/src/api/schema.generated.ts +index 3de44ef..7e361fb 100644 +--- a/cmapi-portal-ui/src/api/schema.generated.ts ++++ b/cmapi-portal-ui/src/api/schema.generated.ts +@@ -2620,7 +2620,7 @@ export interface components { + state: "permanent" | "active" | "expiring" | "grace" | "pending_delete"; + /** + * Team +- * @description Team (`cmapi.net/team`) ++ * @description Team from the label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default) + * @example payments + */ + team: string | null; +@@ -3381,7 +3381,7 @@ export interface components { + onBehalfOf?: string | null; + /** + * Placementid +- * @description The `placementId` of POST /api/v1/capacity:place: its hold becomes this request's own. The placement must be active and made for the path's cluster, its environment and the `cmapi.net/team` label sent here ++ * @description The `placementId` of POST /api/v1/capacity:place: its hold becomes this request's own. The placement must be active and made for the path's cluster, its environment and the team label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default) + * @example null + */ + placementId?: string | null; +diff --git a/cmapi-portal-ui/src/portal/NewNamespaceTab.tsx b/cmapi-portal-ui/src/portal/NewNamespaceTab.tsx +index 722716a..dc205d1 100644 +--- a/cmapi-portal-ui/src/portal/NewNamespaceTab.tsx ++++ b/cmapi-portal-ui/src/portal/NewNamespaceTab.tsx +@@ -33,7 +33,7 @@ import { isoDay } from "./format"; + import { Field, fieldName, MetadataSection } from "./MetadataFields"; + import { + bodyOf, checkAll, checkExtras, checkName, defaultSource, endValue, errorsByField, expiryInfo, expiryRulesOf, joinName, nameEnds, nameSuggestion, +- shownValues, valueKey ++ shownValues, teamFieldOf, valueKey + } from "./metadataForm"; + import type { ExpiryInfo, ExtraCheck, ExtraRow, Kind, MetaField, MetaForm, Source } from "./metadataForm"; + import { NamespaceNameField } from "./NamespaceNameField"; +@@ -81,7 +81,6 @@ const CHECK_AFTER_MS = 150; + /** How long the team, tier and region stay still before the Placement preview ranks them: each ranking spends the caller's + * :place bucket (10 a minute), so typing a team name does not rank each prefix. */ + const RANK_AFTER_MS = 600; +-const TEAM_KEY = "cmapi.net/team"; + const LABEL_VALUE = /^[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$/; + const GI = 2 ** 30; + +@@ -314,7 +313,8 @@ export function NewNamespaceTab({ config, open }: TabProps) { + const activeRegion = inEnv.some((c) => c.labels.region === region) ? region : ANY_REGION; + const instance = me.state === "ok" ? me.data.instance : ""; + // The team the namespace is for, as the form shows it: placement ranks for it, and the create must carry the same label. +- const teamField = form?.fields.find((f) => f.kind === "label" && f.key === TEAM_KEY) ?? null; ++ // Its key is the instance's team label (metadata-keys.yaml teamKey, #258), which the answer of GET /api/v1/metadata-keys names. ++ const teamField = form ? teamFieldOf(form) : null; + const team = form && teamField ? shownValues(form, typed, { namespace: "", environment: env, cluster: "", instance })[valueKey(teamField)] ?? "" : ""; + // A label value (PlacementRequest.team), or the preview waits: the form's own check names what is wrong with it. An instance + // whose keys have no team label places with no team. +diff --git a/cmapi-portal-ui/src/portal/metadataForm.ts b/cmapi-portal-ui/src/portal/metadataForm.ts +index 364829a..dc10728 100644 +--- a/cmapi-portal-ui/src/portal/metadataForm.ts ++++ b/cmapi-portal-ui/src/portal/metadataForm.ts +@@ -88,6 +88,9 @@ export interface ExpiryRules { + + /** What the form reads from one answer of GET /api/v1/metadata-keys. */ + export interface MetaForm { ++ /** The label that names a namespace's team (metadata-keys.yaml teamKey, #258): labels.x-cmapi-team-key, which the answer ++ * leaves out when it is cmapi.net/team. POST /api/v1/capacity:place takes its value as `team`. */ ++ teamKey: string; + /** Inputs, then read-only fields, then optional inputs, for each kind; operator-only keys are not offered. */ + fields: MetaField[]; + /** A label value's syntax (labels.additionalProperties): Kubernetes' IsValidLabelValue, which cmapi checks first. */ +@@ -124,7 +127,7 @@ type Json = Record; + export const KEYWORDS = { + /** The members of the answer itself. */ + answer: { read: ["labels", "annotations", "x-cmapi-expiration"], ignored: {} }, +- map: { read: ["type", "properties", "required", "additionalProperties", "propertyNames", "x-cmapi-other-keys"], ignored: {} }, ++ map: { read: ["type", "properties", "required", "additionalProperties", "propertyNames", "x-cmapi-other-keys", "x-cmapi-team-key"], ignored: {} }, + property: { + read: ["type", "pattern", "allOf", "maxLength", "minLength", "enum", "title", "description", "examples", "readOnly", "x-cmapi-rule", + "x-cmapi-derived-from", "x-cmapi-format", "x-cmapi-namespace-prefix", "x-cmapi-namespace-suffix", "x-cmapi-default-from", +@@ -295,7 +298,13 @@ export function fieldsOf(view: unknown): MetaForm { + ]; + ordered.forEach((f, i) => fields.push({ ...f, id: `ns-${kind}-${i}` })); + } +- return { fields, labelValue, operatorOnlyLabels, operatorOnly, otherKeys, expiration: expirationOf(view), edits }; ++ const teamKey = isObject(view.labels) ? textOf(view.labels["x-cmapi-team-key"]) : null; ++ return { fields, teamKey: teamKey ?? "cmapi.net/team", labelValue, operatorOnlyLabels, operatorOnly, otherKeys, expiration: expirationOf(view), edits }; ++} ++ ++/** The field of the team label, whose value placement ranks for and the create must carry; null when the form offers none. */ ++export function teamFieldOf(form: MetaForm): MetaField | null { ++ return form.fields.find((f) => f.kind === "label" && f.key === form.teamKey) ?? null; + } + + /** The key of a field's value in the form's state: a key can be a label and an annotation, each with its own value. */ +diff --git a/cmapi-portal-ui/tests/api/metadata-keys.company.json b/cmapi-portal-ui/tests/api/metadata-keys.company.json +index 07f9216..7c796ad 100644 +--- a/cmapi-portal-ui/tests/api/metadata-keys.company.json ++++ b/cmapi-portal-ui/tests/api/metadata-keys.company.json +@@ -116,6 +116,7 @@ + } + } + }, ++ "x-cmapi-team-key": "company.net/mnemonic", + "required": [ + "name", + "company.net/app-environment", +diff --git a/cmapi-portal-ui/tests/api/standin.mjs b/cmapi-portal-ui/tests/api/standin.mjs +index 8c2cf8f..e4ba927 100644 +--- a/cmapi-portal-ui/tests/api/standin.mjs ++++ b/cmapi-portal-ui/tests/api/standin.mjs +@@ -820,7 +820,7 @@ export function missingKeysOf(keys, maps, sources) { + /** NamespaceView of a record: the list's (no Git, no etag) or the detail's (router.py _namespace_view and get_namespace). */ + export function namespaceViewOf(keys, rec, withGit, environment = rec.env) { + const live = rec.live ?? { labels: {}, annotations: {} }; +- return { clusterId: rec.clusterId, name: rec.name, env: live.labels["cmapi.net/env"] ?? null, team: live.labels["cmapi.net/team"] ?? null, tier: live.labels["cmapi.net/tier"] ?? null, ++ return { clusterId: rec.clusterId, name: rec.name, env: live.labels["cmapi.net/env"] ?? null, team: live.labels[keys.labels["x-cmapi-team-key"] ?? "cmapi.net/team"] ?? null, tier: live.labels["cmapi.net/tier"] ?? null, + labels: live.labels, annotations: live.annotations, managed: live.labels["cmapi.net/managed"] === "true", expiresAt: live.annotations["cmapi.net/expires-at"] ?? null, + etag: withGit ? recordEtag(rec) : null, openRequest: rec.openRequest?.requestId ?? null, mnemonic: prefixOf(keys, rec.live), + git: withGit ? { ...rec.git, edits: gitEditsOf(keys, rec.git, environment), +@@ -1172,7 +1172,7 @@ export function apiHandler({ issuer, portalOrigin }) { + const p = state.placements.get(body.placementId); + if (!p || p.used) return problem(res, refuse(422, "placement-not-found", `No active placement ${body.placementId}: it expired, was used by another create, or never existed. Place again.`), cors); + // The team that the namespace will carry: the request's, or the one cmapi fills in (a default), as facts["team"]. +- if (p.clusterId !== clusterId || p.env !== env || p.team !== (made.filled.label["cmapi.net/team"] ?? null)) { ++ if (p.clusterId !== clusterId || p.env !== env || p.team !== (made.filled.label[state.metadataKeys.labels["x-cmapi-team-key"] ?? "cmapi.net/team"] ?? null)) { + return problem(res, refuse(422, "placement-mismatch", `Placement ${body.placementId} was made for another target`), cors); + } + } +diff --git a/cmapi-portal-ui/tests/contract.test.mjs b/cmapi-portal-ui/tests/contract.test.mjs +index 9517cd3..f05acfb 100644 +--- a/cmapi-portal-ui/tests/contract.test.mjs ++++ b/cmapi-portal-ui/tests/contract.test.mjs +@@ -30,7 +30,7 @@ console.log("ok - contract"); + // #336: the New namespace form evaluates or shows each keyword that GET /api/v1/metadata-keys sends, or lists it as + // ignored with its reason (src/portal/metadataForm.ts, KEYWORDS). A keyword in neither list fails here: the generator + // (MetadataKeys.json_schema) gained a rule that the form would silently check less than cmapi does. +-const { KEYWORDS } = await import("../src/portal/metadataForm.ts"); ++const { fieldsOf, KEYWORDS, teamFieldOf } = await import("../src/portal/metadataForm.ts"); + const samples = JSON.parse(readFileSync(join(app, "..", "cmapi", "src", "cmapi", "contract", "samples.json"), "utf8")); + const answers = { reference: samples.operations.core_metadata_keys.response.body, + company: JSON.parse(readFileSync(join(app, "tests", "api", "metadata-keys.company.json"), "utf8")), +@@ -64,3 +64,17 @@ for (const [name, answer] of Object.entries(answers)) { + } + assert.deepEqual(unknown, [], "keywords of GET /api/v1/metadata-keys that the form neither evaluates nor lists as ignored"); + console.log("ok - the New namespace form reads each keyword of GET /api/v1/metadata-keys or lists it as ignored"); ++ ++// #258: the New namespace form places for the value of the instance's team label, which the answer names when it is not ++// cmapi.net/team. A form that looked for cmapi.net/team on the company answer placed with no team, and the create, whose ++// team is the mnemonic, was refused (422 placement-mismatch). ++for (const [name, key] of [["reference", "cmapi.net/team"], ["company", "company.net/mnemonic"], ["company-479", "cmapi.net/team"]]) { ++ const form = fieldsOf(answers[name]); ++ assert.equal(form.teamKey, key, `${name}: the team label`); ++ const field = teamFieldOf(form); ++ assert.deepEqual(field && [field.kind, field.key, field.required, field.derivedFrom], ["label", key, true, null], `${name}: its field`); ++} ++// An answer with no field of its team label places with no team (PlacementRequest.team: "Left out on an instance whose ++// metadata keys have no team label"). ++assert.equal(teamFieldOf({ ...fieldsOf(answers.company), teamKey: "cmapi.net/team" }), null); ++console.log("ok - the New namespace form finds the team that placement ranks for by the answer's team label"); +diff --git a/cmapi/contract/openapi.json b/cmapi/contract/openapi.json +index 943b974..bee4afe 100644 +--- a/cmapi/contract/openapi.json ++++ b/cmapi/contract/openapi.json +@@ -3067,7 +3067,7 @@ + "type": "null" + } + ], +- "description": "Team (`cmapi.net/team`)", ++ "description": "Team from the label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default)", + "examples": [ + "payments" + ], +@@ -4701,7 +4701,7 @@ + "type": "null" + } + ], +- "description": "The `placementId` of POST /api/v1/capacity:place: its hold becomes this request's own. The placement must be active and made for the path's cluster, its environment and the `cmapi.net/team` label sent here", ++ "description": "The `placementId` of POST /api/v1/capacity:place: its hold becomes this request's own. The placement must be active and made for the path's cluster, its environment and the team label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default)", + "examples": [ + null + ], +diff --git a/cmapi/src/cmapi/core/approvals.py b/cmapi/src/cmapi/core/approvals.py +index bbaf57a..21b156e 100644 +--- a/cmapi/src/cmapi/core/approvals.py ++++ b/cmapi/src/cmapi/core/approvals.py +@@ -141,7 +141,9 @@ class ApprovalRules: + + A request beyond its tier always gets an answer from a rule. When no threshold that reads a beyond-tier fact is true, + one approver of defaults.group is added: an instance that removes the rule does not open the gate by accident. A +- rule that means no extra approval says so with `add: 0`. ++ rule that means no extra approval says so with `add: 0`. A quota lowered below what the pods request, or lowered ++ while their use cannot be read (quotaBelowRequested, #256), gets its answer the same way: docs/01, "A decrease ++ below what pods already request is refused unless approver-platform approve". + """ + out = [] + for expr, t in self.thresholds: +@@ -155,6 +157,13 @@ class ApprovalRules: + # A site may still mount the policy shipped before live usage existed. + out.append((Slot("approver-platform", 1, "Live usage unavailable"), + "live usage unavailable: +1 approver-platform", frozenset({"usage"}))) ++ if facts.get("quotaBelowRequested") and not any("quotaBelowRequested" in names for _, _, names in out): ++ # The fact was always false before #256, so a file without the rule never answered it. A file that answers it, ++ # with any group or with `add: 0`, is the site's policy and stands, also for a use that could not be read. ++ g = self.defaults["group"] ++ out.append((Slot(g, 1, "Quota below what pods request"), ++ f"quota below what pods request, and no rule reads quotaBelowRequested: +1 {g}", ++ frozenset({"quotaBelowRequested"}))) + if facts.get("beyondTier") and not any(names & BEYOND_FACTS for _, _, names in out): + g = self.defaults["group"] + out.append((Slot(g, 1, "Value beyond the tier"), f"beyond the tier, and no rule reads beyondTier: +1 {g}", +diff --git a/cmapi/src/cmapi/core/capacity_ledger.py b/cmapi/src/cmapi/core/capacity_ledger.py +index b521d1e..51c1f84 100644 +--- a/cmapi/src/cmapi/core/capacity_ledger.py ++++ b/cmapi/src/cmapi/core/capacity_ledger.py +@@ -24,15 +24,9 @@ from dataclasses import dataclass, field + from decimal import Context, Decimal + from typing import Any, Iterable, Mapping + +-from cmapi.core.tiers import qty ++from cmapi.core.tiers import REQUEST_KEYS, binding_hard as binding_hard, qty + + RESOURCES = ("cpu", "memory") +-# A quota's `cpu` and `memory` are the same resources as `requests.cpu` and `requests.memory` +-# (https://kubernetes.io/docs/concepts/policy/resource-quotas/): the pod evaluator charges a pod's requests to both names, +-# and quota admission refuses a pod that exceeds either hard value (kubernetes v1.34.0, pkg/quota/v1/evaluator/core/pods.go, +-# podComputeUsageHelper; staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go, LessThanOrEqual). So a quota with both +-# lets the namespace commit the smaller of the two, and that is what is counted, once. +-REQUEST_KEYS = {"cpu": ("requests.cpu", "cpu"), "memory": ("requests.memory", "memory")} + MANAGED = "cmapi.net/managed" + + +@@ -87,17 +81,6 @@ def _bound(hard: Mapping[str, Any], used: Mapping[str, Any], resource: str) -> B + return Bound(value, None) + + +-def binding_hard(hard: Mapping[str, Any] | None) -> dict[str, str]: +- """A quota's hard values with each short name (`cpu`, `memory`) folded into its long name, the smaller of the two: the +- limit that admission enforces and the ledger counts (#393). The planner sizes a change from this, so a quota in Git that +- bounds CPU by `cpu` alone, or by a `cpu` tighter than its `requests.cpu`, is not read as no bound (#710).""" +- out = {k: str(v) for k, v in (hard or {}).items()} +- for long, short in REQUEST_KEYS.values(): +- if short in out: +- out[long] = min(out.get(long, out[short]), out[short], key=qty) +- return out +- +- + def quota_facts(obj: Mapping[str, Any]) -> QuotaFacts | None: + """The facts of a quota that cmapi manages, or None for any other quota.""" + meta = obj.get("metadata") or {} +diff --git a/cmapi/src/cmapi/core/metadata.py b/cmapi/src/cmapi/core/metadata.py +index 7bafbd5..e731992 100644 +--- a/cmapi/src/cmapi/core/metadata.py ++++ b/cmapi/src/cmapi/core/metadata.py +@@ -1608,6 +1608,8 @@ class MetadataKeys: + # A character is one to four bytes in UTF-8, so a bound on bytes is at least this bound on characters. + extra["maxLength"] = other.max_value_bytes + schema: dict[str, Any] = {"type": "object", "properties": properties} ++ if kind == "label" and not patch and self.team_key != DEFAULT_TEAM_KEY: ++ schema["x-cmapi-team-key"] = self.team_key + # A filled-in key is required too (#479, A1): a client sends its value or leaves it out, and cmapi fills it in. + required = [key for key, rule in rules.items() if rule.required] + if required and not patch: +diff --git a/cmapi/src/cmapi/core/models.py b/cmapi/src/cmapi/core/models.py +index 2829304..5ca33fd 100644 +--- a/cmapi/src/cmapi/core/models.py ++++ b/cmapi/src/cmapi/core/models.py +@@ -415,7 +415,8 @@ class NamespaceCreate(RequestBody): + placement_id: str | None = Field(default=None, description="The `placementId` of POST /api/v1/capacity:place: its hold " + "becomes this request's own. The placement must be active and " + "made for the path's cluster, its environment and the " +- "`cmapi.net/team` label sent here", examples=[None]) ++ "team label named by metadata-keys.yaml `teamKey` " ++ "(`cmapi.net/team` by default)", examples=[None]) + on_behalf_of: str | None = Field(default=None, description="Username or employee ID, for services and automation", examples=[None]) + justification: str | None = Field(default=None, description="Why the namespace is needed", examples=["Payments service dev namespace"]) + +@@ -754,7 +755,8 @@ class ExpirationRow(Api): + name: str = Field(description="Namespace", examples=["sprint-dev"]) + cluster_id: str = Field(description="Cluster", examples=["CRC"]) + env: str | None = Field(description="Environment (`cmapi.net/env`)", examples=["dev"]) +- team: str | None = Field(description="Team (`cmapi.net/team`)", examples=["payments"]) ++ team: str | None = Field(description="Team from the label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by " ++ "default)", examples=["payments"]) + app: str | None = Field(default=None, description="`cmapi.net/app`", examples=[None]) + created: date | None = Field(description="The day the namespace was created on the cluster (its creationTimestamp), UTC", + examples=["2026-10-01"]) +diff --git a/cmapi/src/cmapi/core/pipeline.py b/cmapi/src/cmapi/core/pipeline.py +index 1c8b6dc..ad9b6e4 100644 +--- a/cmapi/src/cmapi/core/pipeline.py ++++ b/cmapi/src/cmapi/core/pipeline.py +@@ -25,7 +25,7 @@ from cmapi.core.adoption import (ADOPT_PERMISSION, INSTANCE_LABEL, SYNC_OPTIONS_ + snapshot_hash, standing, unmanaged_phrase) + from cmapi.core.approvals import BEYOND_FACTS, ApprovalLedger, Requirement + from cmapi.core.capacity_backend import CapacityHold, SimulatedCapacity, capacity_exceeded +-from cmapi.core.capacity_ledger import REQUEST_KEYS, binding_hard, nano_units, quota_facts, totals_of ++from cmapi.core.capacity_ledger import REQUEST_KEYS, binding_hard, is_scoped, nano_units, quota_facts, totals_of + from cmapi.core.clients.kube import BadResponse, ClusterUnreachable, KubeError + from cmapi.core.config import InstanceConfig, environment_not_served + from cmapi.core.db.models import ChangeRequestRow +@@ -472,7 +472,7 @@ class Pipeline: + # quotaIncreasePct over what Git holds; none held is a write from nothing, 100% on each key (compare). tierChange + # is from the tier that Git's Namespace names; one that names none and is not moved is rendered on `tier`. + facts.update(self.cfg.tiers.compare(env, old_tier if old_tier or moved else tier, old_hard, tier, hard, +- self.quota_used(cluster_id, ns, old_rq)).facts()) ++ self._use_if_lowered(cluster_id, ns, old_rq, old_hard, hard)).facts()) + # Beyond the tier: each overridable value that differs from the tier and from the value that Git holds. A value that + # was approved before is not beyond the tier again. + beyond = {k: v for k, v in self.cfg.tiers.beyond(env, tier, hard, limit_range).items() +@@ -834,7 +834,9 @@ class Pipeline: + def submit(self, who: Identity, plan: Plan, repo: RequestRepo, jobs: JobRepo, *, idempotency_key: str | None, + body_fingerprint: str, justification: str | None) -> ChangeRequestRow: + rid = repo.next_id() # takes the day's advisory lock: submits are serial from here to the commit +- decide_again = plan.action != "delete" and bool(plan.facts.get("team")) ++ # A delete too: the expired-namespace policy approves one, and the team's daily allowance is a guard that no policy ++ # switches off (docs/01). Any other delete falls back on the guard "delete" first, as when it was planned. ++ decide_again = bool(plan.facts.get("team")) + if plan.hold is not None: + # The cluster as it is now, under its lock, with every hold taken since the plan (#62): what the rules decide on. + # A request that no longer fits is refused here and nothing is recorded. +@@ -930,8 +932,8 @@ class Pipeline: + existing = namespace_doc(current) is not None + exposure_base = old_hard if existing or tier not in offered else offered[tier].quota + # A create has no quota change: a planned one carries no tierChange or quotaIncreasePct, and neither does its restore. +- facts = {**(tiers.compare(env, old_tier, old_hard, tier, hard, self.quota_used(cluster_id, ns, old_rq)).facts() +- if existing else {}), ++ facts = {**(tiers.compare(env, old_tier, old_hard, tier, hard, ++ self._use_if_lowered(cluster_id, ns, old_rq, old_hard, hard)).facts() if existing else {}), + "capacity": cap.status, "capacityFresh": cap.fresh, "beyondTier": bool(beyond), "beyondTierKeys": sorted(beyond), + # A folder that Git no longer holds is written again as a create: exposure over what the tier gives, and the + # metadata of a new namespace (the first cmapi.net/team is no change of it). +@@ -984,6 +986,8 @@ class Pipeline: + live = cache.get("ResourceQuota", ns, name) if isinstance(name, str) else None + if live is None: + return self._use_unknown(cluster_id, ns, f"the live namespace has no ResourceQuota {name}") ++ if is_scoped(live.get("spec") or {}): ++ return self._use_unknown(cluster_id, ns, f"ResourceQuota {name} measures only its scope") + raw = (live.get("status") or {}).get("used") or {} + used = {k: str(v) for k, v in raw.items() if nano_units(v) is not None} + for long, short in REQUEST_KEYS.values(): +@@ -991,6 +995,12 @@ class Pipeline: + used[long] = used[short] + return used + ++ def _use_if_lowered(self, cluster_id: str, ns: str, quota: Mapping[str, Any] | None, old_hard: Mapping[str, str], ++ hard: Mapping[str, str]) -> dict[str, str] | None: ++ """quota_used for a change that lowers a sizable bound, None for any other: a change of a label, a raise or a quota ++ kept as it is cannot fall below the use, so it reads no watch and logs no quota_used_unknown (TierCatalog.lowered).""" ++ return self.quota_used(cluster_id, ns, quota) if self.cfg.tiers.lowered(old_hard, hard) else None ++ + @staticmethod + def _use_unknown(cluster_id: str, ns: str, reason: str) -> None: + log.info("quota_used_unknown", cluster_id=cluster_id, namespace=ns, reason=reason[:300]) +diff --git a/cmapi/src/cmapi/core/tiers.py b/cmapi/src/cmapi/core/tiers.py +index ec763a4..b6d6f68 100644 +--- a/cmapi/src/cmapi/core/tiers.py ++++ b/cmapi/src/cmapi/core/tiers.py +@@ -82,6 +82,30 @@ def qty(value: str | int | float) -> Decimal: + raise ValueError(out_of_range) from None + + ++# A quota's `cpu` and `memory` are the same resources as `requests.cpu` and `requests.memory` ++# (https://kubernetes.io/docs/concepts/policy/resource-quotas/): the pod evaluator charges a pod's requests to both names, ++# and quota admission refuses a pod that exceeds either hard value (kubernetes v1.34.0, pkg/quota/v1/evaluator/core/pods.go, ++# podComputeUsageHelper; staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go, LessThanOrEqual). So a quota with both ++# lets the namespace commit the smaller of the two, and that is what is counted, once. ++REQUEST_KEYS = {"cpu": ("requests.cpu", "cpu"), "memory": ("requests.memory", "memory")} ++ ++ ++def binding_hard(hard: Mapping[str, Any] | None) -> dict[str, str]: ++ """A quota's hard values with each short name (`cpu`, `memory`) folded into its long name, the smaller of the two: the ++ limit that admission enforces and the ledger counts (#393). The planner sizes a change from this, so a quota in Git that ++ bounds CPU by `cpu` alone, or by a `cpu` tighter than its `requests.cpu`, is not read as no bound (#710).""" ++ out = {k: str(v) for k, v in (hard or {}).items()} ++ for long, short in REQUEST_KEYS.values(): ++ if short in out: ++ out[long] = min(out.get(long, out[short]), out[short], key=qty) ++ return out ++ ++ ++def _long_name(key: str) -> str: ++ """`requests.cpu` for `cpu` and `requests.memory` for `memory`: the name that binding_hard folds the short one into.""" ++ return REQUEST_KEYS[key][0] if key in REQUEST_KEYS else key ++ ++ + def _off_step(value: Decimal, step: Decimal) -> bool: + """Whether value is not a whole number of steps. Decimal's % stops with DivisionImpossible when the integer quotient has + more digits than the context's precision, 28 by default, and a requested value can have more. Both come from qty, so +@@ -711,6 +735,17 @@ class TierCatalog: + raise TierError("tier-not-offered", f"Custom quotas are not offered in {env}") + return custom, self.quota_for(env, custom, hard) + ++ def lowered(self, current_hard: Mapping[str, str], new_hard: Mapping[str, str]) -> list[str]: ++ """The sizable keys whose bound a change lowers: the new quota holds the key, with a smaller value than Git's, or ++ Git's quota does not hold it. A key that Git does not bound has no limit, so its first bound is a lowering (an ++ adopted quota without requests.cpu, moved to a tier). A short name (`cpu`, `memory`) is read with its long one, ++ the smaller of the two (binding_hard). A change that removes a bound, keeps it or raises it lowers nothing. Only ++ a lowered key can newly fall below what the pods request, so only a change with one reads their use ++ (Pipeline.quota_used). This is for the use alone: compare's delta and percent still count an absent key as 0.""" ++ old, new = binding_hard(current_hard), binding_hard(new_hard) ++ return [k for k in self.sizable ++ if (key := _long_name(k)) in new and (key not in old or qty(new[key]) < qty(old[key]))] ++ + def compare(self, env: str, current_tier: str | None, current_hard: Mapping[str, str], + new_tier: str | None, new_hard: Mapping[str, str], + used: Mapping[str, str] | None = None) -> QuotaChange: +@@ -718,21 +753,27 @@ class TierCatalog: + and a key that a side does not hold is 0: a revert restores a folder as Git held it (Pipeline.restore_facts). + + used: what the namespace's pods request now, per sizable key (the live quota's status.used, Pipeline.quota_used); +- None, or a key it does not hold, is a use that could not be read. A key whose new hard is below its use is ++ None, or a key it does not hold, is a use that could not be read. A lowered key whose new hard is below its use is + below_used: Kubernetes keeps the pods that run and refuses new ones ("Neither contention nor changes to quota will + affect already created resources", https://kubernetes.io/docs/concepts/policy/resource-quotas/). A key that the change + lowers and whose use is unknown is unknown_lowered, and counts as below: an approval fact that cannot be read must +- not open the gate it guards (#256, fail closed). A key that the change does not lower cannot newly fall below.""" ++ not open the gate it guards (#256, fail closed). A key that the change does not lower cannot newly fall below. A ++ key that Git's quota does not bound is lowered by its first bound (lowered).""" + pct, delta, below, unknown = {}, {}, [], [] ++ lowered = self.lowered(current_hard, new_hard) ++ current_hard, new_hard = binding_hard(current_hard), binding_hard(new_hard) + for k in self.sizable: +- old, new = qty(current_hard.get(k, "0")), qty(new_hard.get(k, "0")) ++ key = _long_name(k) ++ old, new = qty(current_hard.get(key, "0")), qty(new_hard.get(key, "0")) + delta[k] = new - old + pct[k] = float((new - old) / old * 100) if old else (100.0 if new else 0.0) +- if used is not None and k in used: +- if new < qty(used[k]): +- below.append(k) +- elif new < old: ++ if k not in lowered: ++ continue ++ usage = used.get(key, used.get(k)) if used is not None else None ++ if usage is None: + unknown.append(k) ++ elif new < qty(usage): ++ below.append(k) + cur_c = self.file.tiers.get(current_tier, TierDef(order=0)).custom + new_c = self.file.tiers.get(new_tier, TierDef(order=0)).custom + if cur_c and new_c: +diff --git a/cmapi/tests/core/test_quota_below_requested_256.py b/cmapi/tests/core/test_quota_below_requested_256.py +index dab5eed..03490df 100644 +--- a/cmapi/tests/core/test_quota_below_requested_256.py ++++ b/cmapi/tests/core/test_quota_below_requested_256.py +@@ -52,3 +52,101 @@ def test_a_raise_whose_use_is_unknown_is_not_below(cat): + def test_the_same_quota_whose_use_is_unknown_is_not_below(cat): + small = cat.quota_for("prod", "small") + assert cat.compare("prod", "small", small, "small", small, None).facts()["quotaBelowRequested"] is False ++ ++ ++@pytest.mark.parametrize("target", ["500m", "750m", None]) ++def test_only_a_lowered_bound_can_be_below_requested(cat, target): ++ old = {"requests.cpu": "0.5"} ++ new = {"requests.cpu": target} if target is not None else {} ++ for used in ({"requests.cpu": "1"}, None): ++ change = cat.compare("dev", "small", old, "small", new, used) ++ assert change.facts()["quotaBelowRequested"] is False ++ ++ ++def _decision(cat, thresholds, used, defaults=None): ++ """An rnd-style change that needs no approval and matches an auto-approval policy, lowered from 20 pods to 10.""" ++ from cmapi.core.approvals import ApprovalRules ++ ++ rules = ApprovalRules({"defaults": defaults or {}, "environments": {"dev": {"change": 0}}, "thresholds": thresholds, ++ "autoApproval": {"enabled": True, "policies": [{"name": "updates", ++ "match": {"actions": ["update"]}}]}}) ++ change = cat.compare("dev", "small", {"pods": "20"}, "small", {"pods": "10"}, used) ++ assert change.facts()["quotaBelowRequested"] is True ++ return rules.decide({**change.facts(), "action": "update", "environment": "dev", "plugin": "namespaces", ++ "capacity": "fits", "capacityFresh": True}) ++ ++ ++# The use is known and above the target, or could not be read: one fact, one answer (fail closed is in the fact). ++USES = [{"pods": "15"}, None] ++ ++ ++@pytest.mark.parametrize("used", USES) ++def test_a_file_without_the_rule_does_not_open_the_gate(cat, used): ++ """Before #256 the fact was always false, so a file without the threshold never answered it: one approver of ++ defaults.group, as for beyondTier, and no auto-approval.""" ++ decision = _decision(cat, [], used) ++ assert decision.auto is None and decision.auto_fallback == "rules-added-approvers" ++ assert [(s.group, s.count, s.reason) for s in decision.slots] == [("approver-platform", 1, "Quota below what pods request")] ++ assert "quota below what pods request, and no rule reads quotaBelowRequested: +1 approver-platform" in decision.reasons ++ other = _decision(cat, [], used, defaults={"group": "approver-sre"}) ++ assert [(s.group, s.count) for s in other.slots] == [("approver-sre", 1)] ++ # a rule that is false for this request reads nothing: the gate stays shut ++ prod_only = _decision(cat, [{"when": 'quotaBelowRequested and environment == "prod"', "add": 2}], used) ++ assert [(s.group, s.count) for s in prod_only.slots] == [("approver-platform", 1)] ++ ++ ++@pytest.mark.parametrize("used", USES) ++@pytest.mark.parametrize("threshold,slots,auto", [ ++ ({"when": "quotaBelowRequested", "add": 1}, [("approver-platform", 1)], None), # the shipped rule ++ ({"when": "quotaBelowRequested", "group": "approver-platform", "add": 2}, [("approver-platform", 2)], None), ++ ({"when": "quotaBelowRequested", "group": "approver-dev", "add": 1}, [("approver-dev", 1)], None), ++ ({"when": "quotaBelowRequested", "add": 0}, [], "auto:updates"), # "a rule that answers and adds no approver" ++]) ++def test_a_rule_that_reads_the_fact_is_the_sites_answer(cat, used, threshold, slots, auto): ++ """approval-rules.yaml is the site's policy: its rule stands with its own group and count, and nothing is added to it.""" ++ decision = _decision(cat, [threshold], used) ++ assert [(s.group, s.count) for s in decision.slots] == slots ++ assert decision.auto == auto ++ assert not any("no rule reads quotaBelowRequested" in line for line in decision.reasons) ++ ++ ++@pytest.mark.parametrize("key,short,old,tighter,used", [ ++ ("requests.cpu", "cpu", "2", "500m", "750m"), ++ ("requests.memory", "memory", "4Gi", "1Gi", "1536Mi"), ++]) ++def test_tighter_alias_in_the_target_is_a_decrease(cat, key, short, old, tighter, used): ++ change = cat.compare("dev", "small", {key: old}, "small", {short: tighter, key: old}, {key: used}) ++ assert change.below_used == [key] ++ ++ ++@pytest.mark.parametrize("old,new,expected", [ ++ ({"requests.cpu": "2", "pods": "20"}, {"requests.cpu": "1", "pods": "20"}, ["requests.cpu"]), ++ ({"requests.cpu": "2", "pods": "20"}, {"requests.cpu": "2", "pods": "30"}, []), # kept and raised ++ ({"requests.cpu": "2", "pods": "20"}, {"pods": "20"}, []), # a bound removed ++ ({}, {"requests.cpu": "1", "pods": "20"}, ["requests.cpu", "pods"]), # no bound in Git is no limit ++ ({"pods": "20"}, {"requests.cpu": "1", "pods": "20"}, ["requests.cpu"]), # an adopted quota gains a bound ++ ({"pods": "20"}, {"cpu": "1", "pods": "20"}, ["requests.cpu"]), # ... by its short name ++ ({"requests.memory": "4Gi"}, {"requests.memory": "4Gi", "memory": "1Gi"}, ["requests.memory"]), # a tighter short name ++ ({"cpu": "500m", "requests.cpu": "2"}, {"requests.cpu": "1"}, []), # the short name bound 500m ++]) ++def test_lowered_names_the_sizable_bounds_that_a_change_lowers(cat, old, new, expected): ++ """Only such a change reads the pods' use (Pipeline._use_if_lowered), and compare judges the same keys.""" ++ assert cat.lowered(old, new) == expected ++ change = cat.compare("dev", "small", old, "small", new, None) ++ assert change.unknown_lowered == expected and change.facts()["quotaBelowRequested"] is bool(expected) ++ ++ ++@pytest.mark.parametrize("used,below,unknown", [ ++ ({"requests.cpu": "3", "pods": "5"}, ["requests.cpu"], []), # the pods request 3 cores: a first bound of 2 is below ++ ({"requests.cpu": "1500m", "pods": "5"}, [], []), # they fit under it ++ ({"pods": "5"}, [], ["requests.cpu"]), # a quota reports no use of a key it does not bound ++ (None, [], ["requests.cpu"]), ++]) ++def test_a_first_bound_on_a_key_that_git_left_unbounded_is_judged_against_the_use(cat, used, below, unknown): ++ """An adopted quota that bounds pods only, moved to a quota with requests.cpu: 2. No bound is no limit, not 0, so the ++ new bound can refuse new pods. The delta and the percent keep counting the absent key as 0.""" ++ change = cat.compare("dev", "small", {"pods": "20"}, "small", {"requests.cpu": "2", "pods": "20"}, used) ++ assert (change.below_used, change.unknown_lowered) == (below, unknown) ++ assert change.facts()["quotaBelowRequested"] is bool(below or unknown) ++ assert change.delta["requests.cpu"] == 2 and change.increase_pct["requests.cpu"] == 100.0 ++ +diff --git a/cmapi/tests/core/test_team_key_258.py b/cmapi/tests/core/test_team_key_258.py +index c6e82c3..f5b42a0 100644 +--- a/cmapi/tests/core/test_team_key_258.py ++++ b/cmapi/tests/core/test_team_key_258.py +@@ -71,3 +71,13 @@ def test_every_shipped_copy_names_a_declared_team_label(name): + """A shipped file whose team label is not declared would give no namespace a team, and the allowance would apply to none.""" + keys = MetadataKeys(shipped()[name]) + assert keys.team_key in keys.rules["label"], (name, keys.team_key) ++ ++ ++def test_company_create_schema_identifies_the_placement_team(company): ++ labels = MetadataKeys(company).keys_view()["labels"] ++ assert labels["x-cmapi-team-key"] == "company.net/mnemonic" ++ ++ ++def test_additional_company_example_declares_its_effective_team_key(): ++ keys = MetadataKeys.load(EX / "cluster-configs/policies/metadata-keys.company-479.yaml") ++ assert keys.team_key in keys.rules["label"] +diff --git a/cmapi/tests/service/test_expire_check_263.py b/cmapi/tests/service/test_expire_check_263.py +index f0db07b..0d07197 100644 +--- a/cmapi/tests/service/test_expire_check_263.py ++++ b/cmapi/tests/service/test_expire_check_263.py +@@ -230,6 +230,25 @@ def test_the_expired_namespace_policy_approves_and_the_prune_still_waits_for_an_ + assert kube.get_object("Namespace", None, NAME) is not None, "no timer removes a namespace: the prune waits" + + ++def test_the_expiry_delete_counts_against_the_teams_daily_allowance(world, monkeypatch, mail): ++ """PR #771 review, T1. docs/01, "Guards no policy can switch off": a matching request still goes to humans "when the ++ team's daily allowance is used"; expired-namespace is excepted from the guard on deletes only. Submit skipped the count ++ for every delete, so the policy approved a team's expiry deletes without limit.""" ++ from cmapi.core.db.repo import RequestRepo ++ ++ client, ctx, git, kube, validator, keys = world ++ d = _expiring_namespace(world, monkeypatch) # the create was auto-approved today: one of the team's allowance ++ with ctx.db.session() as s: ++ assert RequestRepo(s).auto_approvals_today("payments") == 1 ++ monkeypatch.setattr(ctx.cfg.approvals, "max_per_team", 1) ++ run_check(ctx, monkeypatch, d + timedelta(days=7)) ++ [row] = expiry_deletes(ctx) ++ assert row.team == "payments" ++ assert (row.requirement["auto"], row.requirement["autoFallback"]) == (None, "team-allowance"), row.requirement ++ assert row.status == "pending_approval" and [s["group"] for s in row.requirement["slots"]] == ["approver-platform"] ++ assert kube.get_object("Namespace", None, NAME) is not None ++ ++ + def test_a_guard_holds_the_delete_and_opens_nothing(world, monkeypatch): + """One notice only (noticesSentAtLeast2): held, listed in the log, tried the next day.""" + client, ctx, git, kube, validator, keys = world +diff --git a/cmapi/tests/service/test_review_771.py b/cmapi/tests/service/test_review_771.py +new file mode 100644 +index 0000000..b6a5b14 +--- /dev/null ++++ b/cmapi/tests/service/test_review_771.py +@@ -0,0 +1,146 @@ ++"""PR 771 decision boundaries that can be tested without a running cluster or database.""" ++from types import SimpleNamespace ++from unittest.mock import Mock ++ ++import pytest ++ ++from cmapi.capacity.usage import NoUsage ++from cmapi.core.approvals import ApprovalRules ++from cmapi.core.clients.kube import WatchCache ++from cmapi.core.metadata import MetadataKeys ++from cmapi.core.models import ExpirationRow, NamespaceCreate ++from cmapi.core.pipeline import EXPIRY_REQUESTER, Pipeline, Plan, folder_etag ++from cmapi.core.ports import CapacityResult ++from conftest import EXAMPLES ++ ++ ++@pytest.mark.parametrize("spec", [{"scopes": ["BestEffort"]}, ++ {"scopeSelector": {"matchExpressions": [{"scopeName": "Terminating", ++ "operator": "Exists"}]}}]) ++def test_scoped_status_cannot_measure_an_unscoped_target(spec): ++ cache = WatchCache(Mock()) ++ for kind, meta, fields in [ ++ ("Namespace", {"name": "billing"}, {}), ++ ("ResourceQuota", {"name": "billing-quota", "namespace": "billing"}, ++ {"spec": spec, "status": {"used": {"requests.memory": "1Gi"}}}), ++ ]: ++ cache._event(kind, {"type": "ADDED", "object": {"metadata": meta, **fields}}) ++ pipeline = Pipeline.__new__(Pipeline) ++ pipeline.registry = Mock() ++ pipeline.registry.cache.return_value = cache ++ assert pipeline.quota_used("CRC", "billing", {"metadata": {"name": "billing-quota"}}) is None ++ ++ ++def test_team_expiry_delete_counts_prior_auto_approvals(): ++ rules = ApprovalRules.load(EXAMPLES / "instances/nonprod/approval-rules.yaml") ++ rules.max_per_team = 1 ++ facts = dict(action="delete", environment="dev", plugin="namespaces", team="billing", reason="expired", ++ noticesSentAtLeast2=True, noOpenRequest=True, notProtected=True, noticesSent=2) ++ pipe = Pipeline.__new__(Pipeline) ++ pipe.cfg = SimpleNamespace(name="nonprod", allowed_environments={"dev"}, approvals=rules) ++ pipe.auto_paused = lambda session: False ++ plan = Plan("CRC", "ns", "dev", "delete", "namespaces", None, {}, {}, {}, rules.decide(facts), ++ CapacityResult("fits", True, None, {}), facts, Mock(), [], "head", reason="expired") ++ assert plan.requirement.auto == "auto:expired-namespace" ++ repo = Mock() ++ repo.auto_approvals_today.return_value = 1 ++ row = pipe.submit(EXPIRY_REQUESTER, plan, repo, Mock(), idempotency_key=None, body_fingerprint="test", ++ justification="expiry") ++ assert row.team == "billing" ++ assert row.requirement["autoFallback"] == "team-allowance" ++ assert row.requirement["auto"] is None ++ ++ ++@pytest.mark.parametrize("model,field", [(NamespaceCreate, "placement_id"), (ExpirationRow, "team")]) ++def test_public_team_field_names_the_configuration(model, field): ++ assert "teamKey" in model.model_fields[field].description ++ ++ ++def test_legacy_team_value_counts_after_configuring_another_label(): ++ from sqlalchemy import create_engine, text ++ from sqlalchemy.orm import Session ++ ++ from cmapi.core.db.repo import RequestRepo ++ ++ keys = MetadataKeys.load(EXAMPLES / "cluster-configs/policies/metadata-keys.company.yaml") ++ # The pre-upgrade row's team came from cmapi.net/team. Exercise the repository query ++ # using the three columns it reads, including JSON ->> extraction, without a DB server. ++ with Session(create_engine("sqlite://")) as session: ++ session.execute(text("create table change_requests (team text, created_at timestamp, requirement json)")) ++ session.execute(text("insert into change_requests values (:team, CURRENT_TIMESTAMP, :req)"), ++ [{"team": "abc", "req": '{"auto":"auto:create"}'}, ++ {"team": "abc", "req": '{"auto":"none-required"}'}, ++ {"team": "other", "req": '{"auto":"auto:create"}'}]) ++ assert RequestRepo(session).auto_approvals_today(keys.team_of({"company.net/mnemonic": "abc"})) == 1 ++ ++ ++def test_company_team_matches_placement_hold(): ++ from cmapi.core.errors import Problem ++ ++ keys = MetadataKeys.load(EXAMPLES / "cluster-configs/policies/metadata-keys.company.yaml") ++ pipe = Pipeline.__new__(Pipeline) ++ pipe.capacity = Mock() ++ pipe.capacity.placement.return_value = SimpleNamespace(cluster_id="CRC", env="dev", team="abc", cpu=2, memory=0) ++ body = {"placementId": "pl-test"} ++ team = keys.team_of({"cmapi.net/team": "old", "company.net/mnemonic": "abc"}) ++ assert pipe._placement(body, "create", "CRC", "dev", team, {"requests.cpu": "500m"}) == "pl-test" ++ with pytest.raises(Problem, match="another target"): ++ pipe._placement(body, "create", "CRC", "dev", "old", {}) ++ ++ ++# ---- reviewer 2: the pods' use is read only for a change that lowers a bound (the PR head failed CI's service job here) ++def _existing(tier: str): ++ """test_review_479_expiry's planner (stand-ins for Git, the cluster and the validator), with one namespace in Git.""" ++ from test_review_479_expiry import BODY, OLA, planner ++ from cmapi.core.pipeline import folder_etag ++ ++ pipe = planner() ++ first = pipe.plan_namespace(OLA, "CRC", {**BODY, "tier": tier}, action="create") ++ stored = {p: t for p, t in first.files.items() if t is not None} ++ pipe.git.read_folder.return_value = stored, "base" ++ pipe.usage = NoUsage() ++ return pipe, OLA, BODY["namespace"], folder_etag(stored) ++ ++ ++@pytest.mark.parametrize("change", [{"labels": {"cmapi.net/cost-center": "cc-1234"}}, {"tier": "medium"}]) ++def test_a_change_that_lowers_no_bound_does_not_read_the_pods_use(change): ++ """A label change and a raise cannot fall below the use. On the PR head each read the watch cache, logged ++ quota_used_unknown on a stale watch, and failed where the cluster is a stand-in (CI: test_review_479_expiry, 2 failed).""" ++ pipe, ola, ns, etag = _existing("small") ++ pipe.quota_used = Mock(side_effect=AssertionError("the use was read for a change that lowers no bound")) ++ plan = pipe.plan_namespace(ola, "CRC", {"namespace": ns, **change}, action="update", if_match=etag) ++ assert plan.facts["quotaBelowRequested"] is False ++ pipe.registry.cache.return_value.kind_stale.assert_not_called() ++ ++ ++@pytest.mark.parametrize("used,below", [({"requests.cpu": "0", "requests.memory": "0", "pods": "0"}, False), ++ ({"requests.cpu": "12", "requests.memory": "0", "pods": "0"}, True), (None, True)]) ++def test_a_change_that_lowers_a_bound_reads_the_pods_use_once(used, below): ++ pipe, ola, ns, etag = _existing("medium") ++ pipe.quota_used = Mock(return_value=used) ++ plan = pipe.plan_namespace(ola, "CRC", {"namespace": ns, "tier": "small"}, action="update", if_match=etag) ++ assert pipe.quota_used.call_count == 1 and pipe.quota_used.call_args.args[:2] == ("CRC", ns) ++ assert plan.facts["quotaBelowRequested"] is below and plan.facts["tierChange"] == "down" ++ ++ ++@pytest.mark.parametrize("used,below", [({"pods": "3"}, True), (None, True), ++ ({"requests.cpu": "12", "requests.memory": "1Gi", "pods": "3"}, True), ++ ({"requests.cpu": "1", "requests.memory": "1Gi", "pods": "3"}, False)]) ++def test_an_unbounded_quota_moved_to_a_tier_reads_the_pods_use(used, below): ++ """Git's quota bounds pods only, as an adopted one can. A change to small (8 cores) gives CPU and memory their first ++ bound: the use is read, 12 cores requested is below, and a use that the live quota does not report fails closed.""" ++ import yaml ++ ++ pipe, ola, ns, _ = _existing("small") ++ stored, base = pipe.git.read_folder.return_value ++ path = next(p for p, t in stored.items() if yaml.safe_load(t)["kind"] == "ResourceQuota") ++ quota = yaml.safe_load(stored[path]) ++ quota["spec"]["hard"] = {"pods": quota["spec"]["hard"]["pods"]} ++ stored = {**stored, path: yaml.safe_dump(quota)} ++ pipe.git.read_folder.return_value = stored, base ++ pipe.quota_used = Mock(return_value=used) ++ plan = pipe.plan_namespace(ola, "CRC", {"namespace": ns, "labels": {"cmapi.net/cost-center": "cc-1234"}}, ++ action="update", if_match=folder_etag(stored)) ++ assert pipe.quota_used.call_count == 1 ++ assert plan.facts["quotaBelowRequested"] is below ++ +diff --git a/docs/02-technical-design-v2.md b/docs/02-technical-design-v2.md +index d9d6048..39b7715 100644 +--- a/docs/02-technical-design-v2.md ++++ b/docs/02-technical-design-v2.md +@@ -1362,7 +1362,7 @@ At startup an invalid catalog stops cmapi with every problem listed. On reload c + | Plan a create or tier change | resolve(env, tier), quota\_for(env, tier, quota, approved), limits\_for(env, tier, limitRange, hard, approved) | The full spec.hard and the full LimitRange values; each custom value is checked against the bounds and step. A value that Git already holds (approved) is not checked against the bounds again | + | Beyond the tier | beyond(env, tier, hard, limit range), rendered\_overrides(quota object, the LimitRange objects) | Each overridable value that differs from the tier, for the facts beyondTier and beyondTierKeys; and the approved overrides of a namespace, read from the annotation cmapi.net/beyond-tier | + | Capacity and placement | the resolved requests.cpu and requests.memory | The size reserved; an increase reserves only the delta | +-| Approval rules | compare(env, old tier, old hard, new tier, new hard, used) | Facts tier, tierChange (up, down, same, to-custom, from-custom, custom), quotaIncreasePct and quotaBelowRequested. `used` is the live ResourceQuota's status.used from the watch cache (Pipeline.quota_used, #256); a key that the change lowers and whose use cannot be read counts as below (fail closed) | ++| Approval rules | compare(env, old tier, old hard, new tier, new hard, used) | Facts tier, tierChange (up, down, same, to-custom, from-custom, custom), quotaIncreasePct and quotaBelowRequested. `used` is the live ResourceQuota's status.used from the watch cache (Pipeline.quota_used, #256); a lowered sizable bound counts as below when its namespace-wide use exceeds the target or is unknown (fail closed). The rules answer the fact: the threshold `quotaBelowRequested` of approval-rules.yaml, or, in a file where no true threshold reads it, one approver of `defaults.group` | + | Render | render(namespace, cluster, instance, env, tier, request, quota, limits, approved) | The ResourceQuota and one LimitRange for each resource, called by core/render/manifests.py, which writes each to its own file. Each object names its own beyond-tier keys in cmapi.net/beyond-tier | + | PATCH or PUT .../quota | normalise(env, hard) | The named tier when the values equal one exactly, otherwise custom | + | Quota view | is\_outdated(env, tier, rendered hash) | State tier-outdated, a filter on GET /api/v1/quotas | +diff --git a/docs/09-portal-ui-testing.md b/docs/09-portal-ui-testing.md +index 8eb315c..426d0e1 100644 +--- a/docs/09-portal-ui-testing.md ++++ b/docs/09-portal-ui-testing.md +@@ -302,7 +302,7 @@ words of `core/metadata.py`, and refuses `expiresAt` where `x-cmapi-expiration` + | Check | Command, in `cmapi-portal-ui/` | Result | + |---|---|---| + | The pure parts of the form | `node tests/api/direct.test.mjs` (479-P1, P2, P4, P6, P10 twice, P11, P12) | the name's ends and checks (63 characters is the limit, `abc--x-dev` is taken); a default copied and never sent until edited; every refusal word of an extra key and value; UTF-8 bytes; the expiry rules per environment from `enabled`, never from the name; no company domain or sample value in `src/portal` | +-| Each keyword of the answer is read | `node tests/contract.test.mjs` | `x-cmapi-expiration`, `propertyNames` and its branches, `x-cmapi-other-keys`, `x-cmapi-namespace-suffix` and `x-cmapi-default-from` are read, on the three answers | ++| Each keyword of the answer is read | `node tests/contract.test.mjs` | `x-cmapi-expiration`, `propertyNames` and its branches, `x-cmapi-other-keys`, `x-cmapi-team-key`, `x-cmapi-namespace-suffix` and `x-cmapi-default-from` are read, on the three answers; the form finds the team that placement ranks for by the answer's team label (`teamFieldOf`, #258) | + | Each behaviour at 390, 820 and 1440 px in each theme | checks 479-P2, 479-P3-P5, 479-P6-P7, 479-P9-P11, 479-P12 (two), each on a fresh form six times | pass; no console error | + | The page says what the mockup says, both ways | check 6, New namespace part, against `mockups/portal/new-namespace-479.html` | 82 strings of the mockup on the page; each one it does not show is listed with its reason; nothing invented outside the listed additions (MOCKUP-CONTRACT.md) | + | Layout and axe | check 7 with two new views (`new-479-problems`, `new-479-checked`) | 6 views, 3 widths, 2 themes, no sideways scroll; 24 axe scans, no serious or critical finding | +diff --git a/docs/14-authorization.md b/docs/14-authorization.md +index a0d9d7b..66e0552 100644 +--- a/docs/14-authorization.md ++++ b/docs/14-authorization.md +@@ -200,7 +200,7 @@ The tests `test_environment_role_cannot_*` cover each route group (`test_review_ + + ### Step 5: who can approve + +-An approval has more checks than the permission (`approvals.py:337-364`). They are in this order: ++An approval has more checks than the permission (`approvals.py:346-373`). They are in this order: + + | Check | Refusal | + |---|---| +@@ -283,7 +283,7 @@ When a person calls, cmapi records the request under the caller of the token. Th + + | Value | Where it comes from | Where it is kept | + |---|---|---| +-| `sub` | The claim `sub` (`claims.py:70`) | The database. Self-approval compares it (`approvals.py:355-356`) | ++| `sub` | The claim `sub` (`claims.py:70`) | The database. Self-approval compares it (`approvals.py:364-365`) | + | Username | The claim `preferred_username` (`claims.py:78`) | The database, and as a label of the namespace (`claims.py:3-5`) | + | `email` | The claim `email` (`claims.py:74`) | The database | + | `employee_id` | The claim `employee_id` (`claims.py:78`) | The database | +@@ -298,7 +298,7 @@ A person calls as themselves. If a person sends `onBehalfOf`, cmapi refuses with + A shared human account, for example `cmapi.requester`, that submits for many people is not in the design. A person cannot use `onBehalfOf` (`checks.py:74-78`), so a shared account would be recorded as the requester. It would have three effects: + + - Attribution is lost. Each request would carry the `sub` and the username of the shared account, and not those of the person. +-- The self-approval check fails. The check compares `sub` values (`approvals.py:355-356`). The requester would carry the `sub` of the shared account. A person who submits through it and then approves with their own account has another `sub`, so the check would not refuse. ++- The self-approval check fails. The check compares `sub` values (`approvals.py:364-365`). The requester would carry the `sub` of the shared account. A person who submits through it and then approves with their own account has another `sub`, so the check would not refuse. + - The employee ID record is lost. The token of the shared account has one `employee_id`, or none, and a person's write needs one when the instance requires it (`checks.py:79-81`). + + A tool that must act for people has its own path: see the next section. +@@ -321,7 +321,7 @@ A tool signs in with the client credentials grant. It is a service client, or an + | The tool sends `onBehalfOf`: a username or an employee ID | cmapi looks the value up in the directory. The person must be enabled, or the answer is 422 `unknown-user`. The person is recorded as the requester and the tool as the caller. The request is recorded as automated | `checks.py:89-95` | + | A person sends `onBehalfOf` | 422 `on-behalf-of-not-allowed` | `checks.py:74-78`; `problem_docs.py:104` | + +-Self-approval uses the requester and the submitter. The ledger refuses the requester as approver: `requester_sub` is the `sub` of the named person (`checks.py:49-53`, `pipeline.py:866`, `approvals.py:355-356`). It also refuses the submitter, which is the `sub` of the tool, unless the approval rule has `selfApproval: true` (`cmapi/src/cmapi/core/db/repo.py:247-249`, `approvals.py:353-354`). The record keeps the submitter in `submittedBySub`, and the response leaves it out (`checks.py:59-64`, `views.py:25-27`). ++Self-approval uses the requester and the submitter. The ledger refuses the requester as approver: `requester_sub` is the `sub` of the named person (`checks.py:49-53`, `pipeline.py:868`, `approvals.py:364-365`). It also refuses the submitter, which is the `sub` of the tool, unless the approval rule has `selfApproval: true` (`cmapi/src/cmapi/core/db/repo.py:247-249`, `approvals.py:362-363`). The record keeps the submitter in `submittedBySub`, and the response leaves it out (`checks.py:59-64`, `views.py:25-27`). + + With `onBehalfOf`, cmapi trusts the tool to name the person. The directory proves that the person exists and is enabled. It does not prove that the person signed in. + +@@ -370,7 +370,7 @@ The code `forbidden` has two more causes. Each is a refusal of the code, not of + | A caller cancels a request that is not theirs and does not hold `namespaces:protect` in its environment | "Only the requester or an operator can cancel" | `cmapi/src/cmapi/core/lifecycle.py:125`, `cmapi/src/cmapi/routers/requests.py:211` | + | A write sets or removes an operator-only label or annotation (`cmapi.net/protected`, `do-not-delete`) and the caller does not hold `namespaces:protect` in the environment | "Needs namespaces:protect in . Keys: ." (the cluster's environment, #532) | `cmapi/src/cmapi/core/metadata.py:1434` | + +-The ledger also refuses a relay client without `approvals:relay` with this code ("Relay client lacks approvals:relay", `cmapi/src/cmapi/core/approvals.py:347`), but no route can reach it: the approve route in `routers/requests.py` passes no relay to `ApprovalLedger.approve` (see "What is not built"). ++The ledger also refuses a relay client without `approvals:relay` with this code ("Relay client lacks approvals:relay", `cmapi/src/cmapi/core/approvals.py:356`), but no route can reach it: the approve route in `routers/requests.py` passes no relay to `ApprovalLedger.approve` (see "What is not built"). + + A sample 403, taken from a run of the service suite's app on 2026-11-13. A caller with the role `cmapi-viewer` sent `POST /api/v1/admin/auto-approval:pause`: + +@@ -394,7 +394,7 @@ A sample 403, taken from a run of the service suite's app on 2026-11-13. A calle + |---|---| + | Routes for quotas, service accounts, grants, configuration, cluster onboarding, reload, events and audit export | Not built. Their permissions exist in `authz.py`, and no route uses them | + | `adoption:write`: the scan of a cluster and the unmanaged-namespaces report (#252's admin operations) | Not built. The adoption of one namespace is self-service: its three routes need `namespaces:write` in the cluster's environment, and the approval rules gate it (#739, the owner's decision of 2026-11-26 on #26). The routes declare and enforce the same permission (`cmapi/src/cmapi/plugins/adoption/router.py`, `ADOPT_PERMISSION`) | +-| The approval relay for email, ServiceNow and chat (`approvals:relay`) | The check exists in `approvals.py:344-347`. No route accepts a relayed approval | ++| The approval relay for email, ServiceNow and chat (`approvals:relay`) | The check exists in `approvals.py:353-356`. No route accepts a relayed approval | + | A scope by team or by namespace name | Not designed. A role with `namespaces:create` can ask for each name that is not reserved (`authz.py:8-10`) | + + ## Proof +diff --git a/docs/16-data-model.md b/docs/16-data-model.md +index e38f12d..36b0754 100644 +--- a/docs/16-data-model.md ++++ b/docs/16-data-model.md +@@ -101,7 +101,7 @@ One row is one write to one namespace. The row is the only record of a request: + | `status` | One of 15 states (`S` in `core/lifecycle.py`). See "The states" below | `RequestRepo.insert` and `RequestRepo.move`, from the table in `core/lifecycle.py` | + | `reason` | A short code for the cause of a request: `expiration:extend` for an expiry extension, and `revert` for a revert request. Null for a plain write. The design has `expired` for the delete that the daily expiry check opens, and a rule of `approval-rules.yaml` reads it. The check is not built, and no code sets `expired` today | `Pipeline.submit` | + | `justification` | The text that the requester wrote | `Pipeline.submit` | +-| `team` | The value of the label `cmapi.net/team` at plan time. The daily allowance of auto-approvals counts requests for this value (`RequestRepo.auto_approvals_today`) | `Pipeline.submit` | ++| `team` | The value of the team label at plan time: the label that metadata-keys.yaml names in `teamKey`, `cmapi.net/team` by default (#258). The daily allowance of auto-approvals counts requests for this value (`RequestRepo.auto_approvals_today`) | `Pipeline.submit` | + | `plan` | The stored plan, as JSON. See "The JSON columns" below | `Plan.stored` (`core/pipeline.py`) | + | `plan_hash` | SHA-256 of the rendered files. The worker checks that the files of the pull request still have this hash before it merges | `Pipeline.submit` | + | `base_sha` | The Git commit that the plan read, shown as `baseSha` in the request view. No code compares it. `open_pr` compares the folder as Git holds it now with `plan.prev`, and a difference moves the request to `superseded` (`jobs/open_pr.py`) | `Pipeline.submit` | +diff --git a/docs/18-configuration.md b/docs/18-configuration.md +index 26f1060..e6f2890 100644 +--- a/docs/18-configuration.md ++++ b/docs/18-configuration.md +@@ -437,7 +437,7 @@ The rules for the labels and the annotations that a requester sets on a namespac + | `adoptionLabels` | mapping of key to `{recognise: [values]}` | `{}` | Labels that mark a namespace that another tool made. A requester cannot set them: the class of such a key is `reserved`. Today cmapi reads only the keys, for that class. The adoption (story #26) reads the values: a namespace that carries one is listed as `recognised` among the candidates, and the plan reports it as `adoption-label` | + | `sensitiveKeys` | list of keys | `[]` | A change of the value of one of these keys adds the fact `sensitiveKeyChanged`, once per request: a value that Git holds changes or goes, or a change of an existing namespace adds a required or extra key (#481). The first value of a create, and the first set of an operator-only key, are not a change. The shipped files list `cmapi.net/protected` and `do-not-delete`: protecting a namespace needs no extra approval, and removing the protection adds one approver-platform approval (#366) | + | `emailDomains` | list of domains | `[]` | The mail domains for a key with `format: email-in-domains`. A key of that format needs at least one domain | +-| `teamKey` | a label key | `cmapi.net/team` | The label that names a namespace's team (#258). Placement (`POST /api/v1/capacity:place`, whose `team` the create's label must match), the approval fact `team`, the daily allowance `maxPerTeamPerDay`, the team's rate-limit bucket, `change_requests.team` and the `team` of the namespace, quota and expiration lists read it. A key that the file names here must be a label that `requiredLabels` or `extraLabels.keys` declares, or the file is refused (`teamKey: is not a label that requiredLabels or extraLabels.keys declares`): a key read on no namespace would leave the allowance applying to none, silently. Without the stanza it is `cmapi.net/team`, declared or not, as before the stanza. The company example names `company.net/mnemonic` | ++| `teamKey` | a label key | `cmapi.net/team` | The label that names a namespace's team (#258). A client that places before it creates, as the portal does, reads a key other than `cmapi.net/team` from `labels.x-cmapi-team-key` of `GET /api/v1/metadata-keys`, and sends that label's value as the placement's `team`. Placement (`POST /api/v1/capacity:place`, whose `team` the create's label must match), the approval fact `team`, the daily allowance `maxPerTeamPerDay`, the team's rate-limit bucket, `change_requests.team` and the `team` of the namespace, quota and expiration lists read it. A key that the file names here must be a label that `requiredLabels` or `extraLabels.keys` declares, or the file is refused (`teamKey: is not a label that requiredLabels or extraLabels.keys declares`): a key read on no namespace would leave the allowance applying to none, silently. Without the stanza it is `cmapi.net/team`, declared or not, as before the stanza. The company example names `company.net/mnemonic` | + | `liveOnlyKeys` | list of key globs | `[kubernetes.io/metadata.name, "openshift.io/*", "argocd.argoproj.io/*", app.kubernetes.io/instance]` | Keys that the cluster or its controllers write on a live namespace and Git never holds. `GET .../namespaces/{ns}` compares each governed, extra and operator-only key of Git with the live namespace (`sync`, #481) and leaves these out, so they are never drift. `*` matches as in `fnmatch`. Without the stanza, the default applies; an empty list compares every such key. System and reserved keys are never compared | + + Where `emailDomains` is set: in each deployment's metadata configuration. On CRC it is `deploy/manifests/environments/crc/20-config.yaml`, key `emailDomains`; on kind it is the same key in `deploy/manifests/environments/kind/20-config.yaml`. The examples are `examples/cluster-configs/policies/metadata-keys.yaml` (`[ephico2real.com]`, a placeholder) and the company profile `metadata-keys.company.yaml` (`[company.net]`). To change it on CRC, edit that key, apply the ConfigMap, then `oc rollout restart deploy/cmapi-api deploy/cmapi-worker -n cmapi`. The domain is checked for format only: cmapi never looks a DL up. +@@ -638,6 +638,7 @@ What the schema says, for each map: + | `description`, `example` | `description` (with the rule in words) and `examples`. Each declared key also has `x-cmapi-rule`: the rule in the words that a refusal's `detail` uses (`missing_required_key`), so a client says what the API says | + | `operatorOnly` | A property with `x-cmapi-operator-only: true` | + | Every declared and operator-only key | `x-cmapi-edit: {mode, reason, sensitive}`: how the key may change on an existing namespace (#481). `mode` is `fixed` (a `namespacePrefix` or `namespaceSuffix` key), `automatic` (`value: {from: ...}`), `required`, or `optional` (an extra key, and an operator-only key for a caller with `namespaces:protect`); `reason` is the words a person sees, such as "Part of the namespace's fixed name."; `sensitive` is true for a key of `sensitiveKeys`, whose change adds one approval. The same on a create and a change: `MetadataKeys.edit_rule` decides it from the file, in the order of the #481 design, section 3 | ++| `teamKey` | `x-cmapi-team-key` on the labels map of a create, when the key is not `cmapi.net/team`: the label whose value is the `team` of `POST /api/v1/capacity:place` (#258). Left out for `cmapi.net/team`, so an answer without it reads as before the stanza | + | `allowOther` | `propertyNames`: a declared key, or a key under an allowed prefix that is not a system key, an adoption label, a key of the other kind or under a reserved prefix. `additionalProperties`: the value rule of those keys. `x-cmapi-other-keys`: the prefixes, limits and any sensitive additional keys | + + The same two maps are served on their own by `GET /api/v1/metadata-keys` (#336), with the permission `objects:read`, also when `docs.enabled` is false: `{"labels": ..., "annotations": ..., "x-cmapi-expiration": ...}`, the first two exactly the objects of `NamespaceCreate` above without their `title`, `description` and `examples` (a service test holds the two equal on the reference and the company file), and the third the `x-cmapi-expiration` of `NamespaceCreate.expiresAt` (`expiration.yaml` below, #479), so the `ETag` changes when a rule in the answer does (`maxExtensionDays` is not in it: `GET /api/v1/expirations` serves it). The portal's New namespace form builds its fields from it. The first request builds the answer and caches it for the loaded files, which a change restarts the pods to load. It has a strong `ETag` over its bytes and `Cache-Control: private, no-cache`. `If-Match` is read first (#590): `If-Match: *` passes, and any other value must list the `ETag`, by the strong comparison, or the answer is `412`. Then a matching `If-None-Match` answers `304`. +@@ -791,7 +792,7 @@ A requirement is a list of slots, one for each approving group. The ledger fills + | `thresholds[].reason` | text | The `when` text | Text in the `reasons` of the request | + | `protected.labels` | list of `key=value` | `[]` | A namespace whose labels in Git match one of these is protected: a delete request is refused (`namespace-protected`), also the delete after it expires. A request may set such a label only to the listed value, or remove it with `null` (`invalid_value` otherwise). `GET` on a namespace gives `protected` and `protectedBy` from them (#366). List only operator-only keys here, or a requester can protect a namespace | + | `autoApproval.enabled` | boolean | `false` | The master switch for auto-approval | +-| `autoApproval.maxPerTeamPerDay` | integer | `20` | The most auto-approvals for one team in a day (UTC). cmapi counts at submit, for a request with a team. `0` stops each auto-approval, also of a request with no team | ++| `autoApproval.maxPerTeamPerDay` | integer | `20` | The most auto-approvals for one team in a day (UTC). cmapi counts at submit, for a request with a team, the delete that `expired-namespace` approves included. `0` stops each auto-approval, also of a request with no team | + | `autoApproval.policies[]` | list | `[]` | The policies. See below | + + ### The facts +@@ -803,7 +804,7 @@ A `when` line reads these facts. The names are fixed in the code. An unknown nam + | `plugin`, `action`, `environment`, `namespace`, `clusterId`, `reason`, `team`, `tier` | The request | `core/pipeline.py` | + | `tierChange` | `up`, `down`, `same`, `to-custom`, `from-custom` or `custom`. Set for a change of an existing namespace only | `TierCatalog.compare` | + | `quotaIncreasePct` | The largest increase of a sizable key, in percent. Set for a change of an existing namespace only | `QuotaChange.quota_increase_pct` | +-| `quotaBelowRequested` | On a change of an existing namespace's quota (a plan, or a revert): a sizable key's new hard value is below what the pods request now, so Kubernetes would refuse new pods (#256). The use is the `status.used` of the live ResourceQuota that Git's quota is, from the cluster's watch cache. A key that the change lowers and whose use cannot be read counts as below (fail closed): the watch has not listed, is stale (no good read for 30 minutes) or is refused (401, 403), or the live namespace has no such quota. A namespace that the watch does not hold has no pods. A key that the change does not lower is not below for want of a read. The planner logs `quota_used_unknown` with the reason | `Pipeline.quota_used`, `TierCatalog.compare` | ++| `quotaBelowRequested` | On a change of an existing namespace's quota (a plan, or a revert): the change lowers a sizable key's hard value below what the pods request now, so Kubernetes would refuse new pods (#256). The use is the `status.used` of the live ResourceQuota that Git's quota is, from the cluster's watch cache. A key that the change lowers and whose use cannot be read counts as below (fail closed): the watch has not listed, is stale (no good read for 30 minutes) or is refused (401, 403), or the live namespace has no matching unscoped quota or usable value for that key. A namespace that the watch does not hold has no pods. A key that Git's quota does not bound has no limit, so its first bound lowers it: an adopted quota without `requests.cpu`, moved to a tier. Its use is rarely readable, since a live quota reports `status.used` only for the keys it bounds, so such a change usually counts as below. Removing a bound or keeping or raising its value does not trigger this fact. The shipped rule adds one approver of `defaults.group` (approver-platform). When no true threshold reads the fact, cmapi adds that approver itself, with the reason "Quota below what pods request": the fact was always false before #256, so a file without the rule never answered it, and docs/01 says "A decrease below what pods already request is refused unless approver-platform approve". A rule that reads the fact is the site's answer and stands, with its group and its count, also `add: 0`, and also for a use that could not be read (`test_a_rule_that_reads_the_fact_is_the_sites_answer`, `cmapi/tests/core/test_quota_below_requested_256.py`). The use is read only for a change that lowers a sizable bound: a label change or a raise reads no watch. The planner logs `quota_used_unknown` when it cannot use the quota object | `Pipeline.quota_used`, `TierCatalog.lowered`, `TierCatalog.compare` | + | `requestToPeakRatio` | On a change of an existing namespace's quota, with `usage` `ok`: the largest planned hard limit over the namespace's 14-day peak, of a resource the change raises (#310). Absent otherwise, so a rule that reads it adds nothing | `plan_usage`, `capacity/usage.py` | + | `usage` | On a change of an existing namespace's quota: `ok`, `insufficient-data` (no usage source, or under 80% of the window's samples) or `unavailable` (Thanos did not answer, or the cluster's import check found the reader without its own Thanos grants, #724). The shipped rule adds approver-platform on `usage == "unavailable"`. If the active policy has no matching usage threshold that adds that group, the planner supplies one platform slot (#310) | `plan_usage`, `capacity/usage.py` | + | `capacity`, `capacityFresh` | `fits`, `warn`, `exceeded` or `unknown`, and whether the data is fresh. `unknown`, not fresh, when the cluster has neither `simulatedCapacity` nor fresh counted node allocatable, no watch cache, ResourceQuotas not listed yet, ResourceQuota reads refused (401 or 403), or a ResourceQuota watch with no good read for 30 minutes (#393). What is committed comes from the cluster's quota ledger: per namespace the smallest unscoped managed quota, scoped quotas left out (#302). The check adds the capacity that open requests hold (`capacity_reservations`, #62): each request with an increase holds it from submit until it leaves the holding states, and a hold stops counting once the ledger shows its quota. Submit checks again under the cluster's lock and takes the hold in the same transaction, so a request that fit when planned but not beside a hold taken since is refused (`exceeded`) or decided on the new answer; the last `:approve` and a `:retry` from `failed` check again and answer 422 `capacity-exceeded` when the request no longer fits | `core/capacity_backend.py`, `core/capacity_ledger.py` | +diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md +index a970f31..8a89f08 100644 +--- a/docs/GLOSSARY.md ++++ b/docs/GLOSSARY.md +@@ -23,7 +23,7 @@ Status: read from `main` at `afd1206` on 2026-11-23. Each row was read from the + | `instance.yaml` | The file with the key `instance`: name, allowed environments, token issuer and audience, Git repository, identity, CORS, problem base URL, docs and policy settings. | [18-configuration.md](18-configuration.md) | + | `tiers.yaml` | The tier catalog: the quota and limits of each tier in each environment. | [18-configuration.md](18-configuration.md) | + | `metadata-keys.yaml` | The file of the label and annotation keys: the system keys, the keys a requester sets, `operatorOnly`, `sensitiveKeys`, `liveOnlyKeys`, and `emailDomains`. | [18-configuration.md](18-configuration.md), [metadata-keys.yaml](../examples/cluster-configs/policies/metadata-keys.yaml) | +-| `teamKey`, team label | The label of `metadata-keys.yaml` that names a namespace's team (#258): placement, the approval fact `team`, the daily allowance `maxPerTeamPerDay`, the team's rate-limit bucket and `change_requests.team` read it. `cmapi.net/team` when the file has none; a declared label otherwise. The company example names `company.net/mnemonic`. | [18-configuration.md](18-configuration.md), [core/metadata.py](../cmapi/src/cmapi/core/metadata.py) | ++| `teamKey`, team label | The label of `metadata-keys.yaml` that names a namespace's team (#258): placement, the approval fact `team`, the daily allowance `maxPerTeamPerDay`, the team's rate-limit bucket and `change_requests.team` read it. `cmapi.net/team` when the file has none; a declared label otherwise. `GET /api/v1/metadata-keys` names a key other than `cmapi.net/team` in `labels.x-cmapi-team-key`, which the portal's New namespace form places by. The company example names `company.net/mnemonic`. | [18-configuration.md](18-configuration.md), [core/metadata.py](../cmapi/src/cmapi/core/metadata.py) | + | `approval-rules.yaml` | The file that decides, from the facts of a request, how many approvals it needs and from which groups, and which auto-approval policies apply. | [18-configuration.md](18-configuration.md) | + | `authz-roles.yaml` | The file that maps each role to its permissions and, optionally, to the environments where it applies. | [core/authz.py](../cmapi/src/cmapi/core/authz.py), [18-configuration.md](18-configuration.md) | + | `clusters.yaml`, `capacity.yaml` | `clusters.yaml` lists the clusters (`environment`, `writes`, `delivery`, `clusterTokens` and more). `capacity.yaml` holds the overcommit, the warn and critical commitment targets and the KPI thresholds. | [18-configuration.md](18-configuration.md) | +@@ -111,7 +111,7 @@ Status: read from `main` at `afd1206` on 2026-11-23. Each row was read from the + | `base_sha` (`baseSha`) | The Git commit that the plan was made against. | [core/models.py](../cmapi/src/cmapi/core/models.py) | + | `request_events` | The table of one state change or note of a request, in order. `GET /api/v1/requests/{request_id}/events` reads it. Migration 0007 makes its time the insertion time. | [16-data-model.md](16-data-model.md) | + | Approval | One approval of one request by one person, in `approvals`. A person counts once (migration 0002). Requesters cannot approve their own request (409 `self-approval`). | [16-data-model.md](16-data-model.md), [core/docs.py](../cmapi/src/cmapi/core/docs.py) | +-| `quotaBelowRequested` | The approval fact of a quota change whose new hard value of a sizable key is below what the namespace's pods request now (the live ResourceQuota's `status.used`, #256). A lowered key whose use cannot be read counts as below (fail closed). | [18-configuration.md](18-configuration.md), [core/tiers.py](../cmapi/src/cmapi/core/tiers.py) | ++| `quotaBelowRequested` | The approval fact of a quota change that lowers the hard value of a sizable key below what the namespace's pods request now (the live ResourceQuota's `status.used`, #256). A lowered key whose use cannot be read counts as below (fail closed). | [18-configuration.md](18-configuration.md), [core/tiers.py](../cmapi/src/cmapi/core/tiers.py) | + | Auto-approval | An `auto:` rule of `approval-rules.yaml` that approves a plan with no person. A Kyverno warning keeps it from applying. `approvals:pause` stops it. | [18-configuration.md](18-configuration.md), [core/lifecycle.py](../cmapi/src/cmapi/core/lifecycle.py) | + | `:cancel`, `:approve`, `:reject`, `:retry`, `:revert` | The verbs on `/api/v1/requests/{request_id}`, each with its permission (`requests:cancel`, `requests:approve`, `requests:reject`, `requests:retry`; `:revert` also needs `requests:retry`). | [14-authorization.md](14-authorization.md), [core/lifecycle.py](../cmapi/src/cmapi/core/lifecycle.py) | + | In sync, Pending, Drift, Unknown | The state of a namespace in the portal and in the API field `state`. `pending`: an open request holds the namespace, also after the merge and before the cluster has it. `drift`: no request is open and a governed, extra or operator-only key differs between Git and the cluster, or the cluster does not have the namespace. `in-sync`: they are the same. `unknown`: cmapi cannot compare. | [schema.generated.ts](../cmapi-portal-ui/src/api/schema.generated.ts), [NamespacesTab.tsx](../cmapi-portal-ui/src/portal/NamespacesTab.tsx) | +diff --git a/docs/citations.lock.json b/docs/citations.lock.json +index 87fa178..757217a 100644 +--- a/docs/citations.lock.json ++++ b/docs/citations.lock.json +@@ -1,5 +1,5 @@ + { +- "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|337-364": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|346-373": [ + " def approve(self, approver: Identity, *, permitted: bool | None = None, relay: Identity | None = None,", + " relay_permitted: bool | None = None, comment: str = \"\") -> bool:", + " \"\"\"approver is the eligible person; relay is the channel client (approvals:relay) if any.", +@@ -29,20 +29,20 @@ + " return self.met", + "" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|344-347": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|353-356": [ + " if relay is not None:", + " ok = relay_permitted if relay_permitted is not None else \"approvals:relay\" in builtin_permissions(relay)", + " if not ok:", + " raise Problem.forbidden(\"Relay client lacks approvals:relay\")" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|347-347": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|356-356": [ + " raise Problem.forbidden(\"Relay client lacks approvals:relay\")" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|353-354": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|362-363": [ + " if approver.sub in self.client_owner_subs or approver.sub == self.operation_starter_sub:", + " raise Problem.conflict(\"self-approval\", \"The operation starter or client owner cannot approve\")" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|355-356": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|364-365": [ + " if approver.sub == self.requester_sub and not self.requirement.self_approval:", + " raise Problem.conflict(\"self-approval\", \"Requesters cannot approve their own request here\")" + ], +@@ -519,7 +519,7 @@ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|708-708": [ + " self.cfg.roles.require(who, ADOPT_PERMISSION, env)" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|866-866": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|868-868": [ + " requirement=requirement_to_json(req), requester=plan.requester.record(), requester_sub=plan.requester.sub," + ], + "docs/14-authorization.md|cmapi/src/cmapi/core/problem_docs.py|104-104": [ diff --git a/docs/reviews/2026-12-01-issue-256-258/reviewer-1-codex.md b/docs/reviews/2026-12-01-issue-256-258/reviewer-1-codex.md new file mode 100644 index 00000000..a38bb464 --- /dev/null +++ b/docs/reviews/2026-12-01-issue-256-258/reviewer-1-codex.md @@ -0,0 +1,769 @@ +# Review of cmapi PR 771 + +**Request changes on both #256 and #258.** On the supplied head `cff8b36c`, a decrease can miss platform approval, an expiry delete can exceed the team's daily allowance, and the company portal can reserve a placement that its own create cannot claim. The proposed patch fixes eight findings. All 200 targeted Python tests passed after the fixes. PostgreSQL integration and live cluster behavior remain unverified here. + +Locations below refer to the **original PR head**, relative to `export/`. The full fixes and regression tests are in the [unified patch](codex-fix.diff) and reproduced in the appendix. The patch applies on top of the PR, whose base is `0030e34`. + +## Kubernetes semantics used in this review + +- The API defines `status.used` as “the current observed total usage of the resource in the namespace.” The comparable target is the proposed `spec.hard` value for that resource. The API defines quota scopes as filters over tracked objects. A scoped observation therefore cannot establish namespace-wide usage. Read 2026-12-01. [ResourceQuota API](https://kubernetes.io/docs/reference/kubernetes-api/core/resource-quota-v1/) +- Kubernetes lists `cpu` as “Same as `requests.cpu`” and gives the corresponding rule for memory. Requests, limits and object counts have distinct meanings. CPU quota usage is the sum of requests of non-terminal pods for a requests quota. It does not measure CPU consumption from metrics. Reducing a quota can prevent subsequent admission while running workloads remain. Read 2026-12-01. [Resource Quotas](https://kubernetes.io/docs/concepts/policy/resource-quotas/) +- “Quantity is a fixed-point representation of a number.” `qty()` converts both operands into Decimal base units. Thus `500m` and `0.5` compare equal, and `1536Mi` exceeds `1Gi`. The regressions exercise both CPU and binary memory quantities. Read 2026-12-01. [Quantity API](https://kubernetes.io/docs/reference/kubernetes-api/definitions/quantity-resource/) + +## Findings + +| ID and severity | PR-head file and line | Failure and fix | Regression and observed result | +| --- | --- | --- | --- | +| Q1 · Medium | `cmapi/src/cmapi/core/tiers.py:728–735` | With an old limit of 500m and observed requests of 1 CPU, keeping 500m or raising it to 750m still sets the fact. A revert removing the key also treats absence as a hard zero. Restrict the below-usage check to a bound present in the target that actually decreases. Preserve the existing delta and percentage accounting. | `test_only_a_lowered_bound_can_be_below_requested` failed for all three targets on the PR and passed for all three after the fix. | +| Q2 · High | `cmapi/src/cmapi/core/pipeline.py:441–445,474`, `cmapi/src/cmapi/core/tiers.py:728` | Git holds 2 CPU. The new tier keeps `requests.cpu: 2` and also writes `cpu: 500m`. With 750m requested, the effective bound falls below usage. The normal planner passes raw target hard values to compare. The smaller alias was already computed for placement and was lost for approval. Normalize both sides in the shared comparison with the existing binding-hard logic. | `test_tighter_alias_in_the_target_is_a_decrease` returned an empty list before for both CPU and memory. Both now identify the lowered resource. | +| Q3 · High | `cmapi/src/cmapi/core/pipeline.py:983–988` | A lone adopted ResourceQuota can be scoped. A tier change can replace it with an unscoped rendering. Its scoped use can fit under the lowered target while total namespace use exceeds it, even with a fully current cache. Recognize both Kubernetes scope forms with the ledger's existing predicate and treat the observation as unknown. A lowered key then follows the approval path. | Both cases of `test_scoped_status_cannot_measure_an_unscoped_target` returned a partial 1Gi observation before. Both return unknown after. | +| Q4 · High | `cmapi/src/cmapi/core/approvals.py:148–164,209–226` | Setting the fact alone does not require a person. With the quota threshold omitted or set to add zero, a site policy can approve an unknown decrease. With no matching policy and zero base slots, the engine can return `none-required`. Enforce a positive platform slot when the fact is true, preserving any configured positive platform threshold for it. | `test_unknown_decrease_requires_platform_approval_with_site_rules` returned `auto:updates` for the omitted and zero thresholds before. Both now require one platform approval. The two-platform-slot control stays at two. | +| T1 · High | `cmapi/src/cmapi/core/pipeline.py:837,851` | Submit skips the daily count on deletes. The shipped `expired-namespace` policy can consequently open another automatically approved delete for a team that has used its allowance. Prune confirmation is a later step. Re-evaluate team decisions under the submit lock for deletes too. | `test_team_expiry_delete_counts_prior_auto_approvals` recorded no fallback before. With one prior auto-approval and a cap of one, it now records `team-allowance` and requires approval. | +| T2 · Medium | `cmapi/src/cmapi/jobs/open_pr.py:115` | A revert restoring a Namespace without the configured label inherits the original request's team. For example, reverting the first assignment of a team leaves the restored object teamless but writes that team into the new request. Read the team from the chosen Namespace document for all revert actions. Existing historical rows need no change. | `test_revert_to_namespace_without_team_clears_the_requests_team` saw `abc` before and `None` after. | +| T3 · High | `cmapi-portal-ui/src/portal/NewNamespaceTab.tsx:84,317–323,503`, `cmapi/src/cmapi/core/metadata.py:1576–1580` | The company form sends its mnemonic on create, but the portal still looks up the literal default when placing. Its hold has no team and the API rejects the subsequent claim. Publish a custom team key on the create label schema, consume it when previewing, and use the dry run's resolved label when taking the hold. Optional or derived labels can be absent at preview time. The portal retains the legacy default for older servers. | `test_company_create_schema_identifies_the_placement_team` failed with a missing schema key before. The form contract assertion also failed before. Both pass for the amended contract, with coverage for the default and company schema. The placement test confirms the API accepts the company team and refuses a different one. | +| T4 · Low | `cmapi/src/cmapi/core/models.py:418,757` | The create input's placement description and the expiration output's team description still identify the literal default as the key. Both errors propagate into the generated client and contract. Correct the model descriptions and regenerate both artifacts. | Both cases of `test_public_team_field_names_the_configuration` failed before and passed after. The reference OpenAPI and portal type generation checks pass. | + +For Q4 I interpreted the brief's “never auto-approve” and the platform-approval requirement in docs/01 as a minimum for all configurations. This is a policy change for a site that deliberately disabled the threshold. Q3 conservatively treats a scoped live observation as unknown even when a restore keeps the same scope. + +## What the PR gets right + +- **Planning and revert.** `core/pipeline.py:468–475` passes the selected Git quota to the watch lookup on an existing namespace. Label-only rerenders that pick up catalog drift and explicit tier changes share this path. `restore_facts:899–901,933–934` compares the current and restored Git objects and passes usage for an existing namespace. Reverting a delete into an absent Git folder follows create semantics. Reverting a create follows delete semantics. A normal create skips compare. Adoption snapshots the existing quota specs, and a metadata change that keeps the quota objects emits neutral facts. A later change that replaces an adopted quota uses the normal planner. +- **Watch and quantities.** The main cache retains the ResourceQuota object including status. It looks up the quota selected from Git by namespace and name. The lookup tests both watch kinds for an initial list, age and 401/403, and treats a missing live quota in a known namespace as unknown. A missing or unparsable individual quantity stays absent and a lowered key then counts as unknown. The object-level log does not cover every absent per-key observation. An absent namespace in a fresh cache supplies zero. With the shipped catalogs the fact covers the sizable request-CPU, request-memory and pod-count keys. It does not cover every hard resource such as PVC storage. That scope matches docs/18 and the glossary. +- **Residual cache risk.** Yes, the advisory read can yield a wrong automatic decision. The cache can still be within its 30-minute freshness window while a pod or namespace event is in flight, or the quota controller's status can lag. If a low observation fits the target, a zero-approval environment or matching policy can proceed. Submit rechecks capacity and team allowance but does not re-read quota usage. The explicitly stale-watch path marks usage unknown. Neither an unknown read on a pure raise nor ordinary create triggers the quota fact. Independent capacity, usage and validation checks still apply. +- **Shipped rules.** The reference, Helm and instance `approval-rules.yaml` files carry a positive quota threshold. In that configuration a true fact adds a platform slot. `ApprovalRules._auto` rejects policy auto-approval when rules added approvers, including after an environment's base requirement was waived. The configurable-rule exception on the original head is Q4. +- **Backend team readers.** The whole `cmapi/src` literal search found no remaining executable label lookup fixed to the old team key. `core/metadata.py:675–694` defaults an omitted stanza to the old key, even if undeclared. An explicit key must be a declared label. Required and named extra labels work. Annotation-only, undeclared and malformed keys are rejected. Remaining exact-name literals include the default, examples, descriptions and comments. The separately named team-DL annotation is a different input. +- **Storage, counts and placement.** The value in `change_requests.team` is the team name. `core/db/repo.py:144–148` matches that value, UTC day and a stored `auto:%` decision. A row written under the old key counts if its value matches the new label value. A historical null or renamed value does not acquire a new identity on upgrade. The daily ID lock serializes counting and insertion. The old-row regression executes the repository query against local SQLite with matching, other-team and non-policy rows. The backend checks the final merged team against the placement hold at `core/pipeline.py:445,505–511`. The atomic claim at `core/db/repo.py:468–476` retains the hold's team. Capacity's namespace count uses the configured key. The namespaces, quotas and expirations views read it, and the write rate limiter consumes the plan's team. +- **Configuration and generated files.** The reference and chart declare `cmapi.net/team`; the company example declares `company.net/mnemonic`. The Helm schema accepts an omitted key and validates the shape of an explicit one. Cross-field declaration validation belongs to the loader. The additional company-479 example declares the effective default and is covered explicitly in the patch. The PR's reference contract and generated portal types were in sync before the fixes, including the two stale descriptions. The revised docs/02, docs/18 and glossary describe the corrected decision; the reference contract, company form fixture, generated types, API examples and relocated source citations check clean. + +## Reproduction and verification + +Commands below run from `export/cmapi/` unless otherwise indicated. Supply the test database URL from the brief through the environment. The service's PostgreSQL-backed company-flow test stopped during fixture setup with `Operation not permitted` on 127.0.0.1:55432. Its assertions did not run. The 92 passing service-file tests below are database-independent checks, including Helm rendering. No full suite or live cluster was run. + +```sh +CORE=/Users/olasumbo/gitRepos/workbench/cmapi/venv-ref/bin/python +SERVICE=/Users/olasumbo/gitRepos/workbench/cmapi/wt-655-outputs/venv-merged/bin/python + +PYTHONPATH=src:tests/core "$CORE" -m pytest -q -W ignore -p no:cacheprovider \ + tests/core/test_quota_below_requested_256.py tests/core/test_team_key_258.py \ + tests/core/test_approvals.py tests/core/test_render_listquery_config.py \ + tests/core/test_metadata_form_336.py +# 108 passed + +PYTHONPATH=src:tests/service "$SERVICE" -m pytest -q -W ignore -p no:cacheprovider \ + tests/service/test_review_771.py tests/service/test_helm_metadata_values.py \ + tests/service/test_openapi_render_337.py::test_the_packaged_reference_instance_renders_the_committed_contract +# 92 passed + +PYTHONPATH=src:tests/service "$SERVICE" -m pytest -q -W ignore -p no:cacheprovider \ + tests/service/test_team_key_258.py +# PostgreSQL connection refused by sandbox before the test body +``` + +To reproduce the pre-fix assertions, copy the changed tests from the patch onto the supplied head without its implementation changes and use the same pytest commands. Q1, Q2 and Q4 failed in the core quota file; Q3, T1, T2 and T4 failed in the database-independent service file. T3 failed in both the Python company-schema test and the Node form-contract check. Existing controls, including a positive configured quota threshold, continued to pass. + +From `export/cmapi-portal-ui/`, `node_modules/.bin/tsc --noEmit`, `node tests/contract.test.mjs` and `node scripts/api-types.mjs --check` passed. From `export/`, `python3 scripts/api-examples-doc.py --check` passed and `python3 scripts/doc-citations.py --check` reported zero problems. The citation checker used a temporary Git index because the export is a plain copy. The patch passed `git apply --check` and applied on a clean copy of the original affected files. The browser flow and live quota-controller timing were assessed from source. + +The available TokenSave index served a different checkout and reported a detached-HEAD fallback with 30 stale files. The export has no index. Source locations and decisions in this report were verified against the provided files. + +## Complete patch, including regression tests + +```diff +diff --git a/cmapi-portal-ui/src/api/schema.generated.ts b/cmapi-portal-ui/src/api/schema.generated.ts +index 3de44ef..7e361fb 100644 +--- a/cmapi-portal-ui/src/api/schema.generated.ts ++++ b/cmapi-portal-ui/src/api/schema.generated.ts +@@ -2620,7 +2620,7 @@ export interface components { + state: "permanent" | "active" | "expiring" | "grace" | "pending_delete"; + /** + * Team +- * @description Team (`cmapi.net/team`) ++ * @description Team from the label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default) + * @example payments + */ + team: string | null; +@@ -3381,7 +3381,7 @@ export interface components { + onBehalfOf?: string | null; + /** + * Placementid +- * @description The `placementId` of POST /api/v1/capacity:place: its hold becomes this request's own. The placement must be active and made for the path's cluster, its environment and the `cmapi.net/team` label sent here ++ * @description The `placementId` of POST /api/v1/capacity:place: its hold becomes this request's own. The placement must be active and made for the path's cluster, its environment and the team label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default) + * @example null + */ + placementId?: string | null; +diff --git a/cmapi-portal-ui/src/portal/NewNamespaceTab.tsx b/cmapi-portal-ui/src/portal/NewNamespaceTab.tsx +index 722716a..c92a8aa 100644 +--- a/cmapi-portal-ui/src/portal/NewNamespaceTab.tsx ++++ b/cmapi-portal-ui/src/portal/NewNamespaceTab.tsx +@@ -81,7 +81,6 @@ const CHECK_AFTER_MS = 150; + /** How long the team, tier and region stay still before the Placement preview ranks them: each ranking spends the caller's + * :place bucket (10 a minute), so typing a team name does not rank each prefix. */ + const RANK_AFTER_MS = 600; +-const TEAM_KEY = "cmapi.net/team"; + const LABEL_VALUE = /^[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$/; + const GI = 2 ** 30; + +@@ -314,13 +313,16 @@ export function NewNamespaceTab({ config, open }: TabProps) { + const activeRegion = inEnv.some((c) => c.labels.region === region) ? region : ANY_REGION; + const instance = me.state === "ok" ? me.data.instance : ""; + // The team the namespace is for, as the form shows it: placement ranks for it, and the create must carry the same label. +- const teamField = form?.fields.find((f) => f.kind === "label" && f.key === TEAM_KEY) ?? null; +- const team = form && teamField ? shownValues(form, typed, { namespace: "", environment: env, cluster: "", instance })[valueKey(teamField)] ?? "" : ""; ++ const teamField = form?.fields.find((f) => f.kind === "label" && f.key === form.teamKey) ?? null; ++ const previewTarget = { namespace: "", environment: env, cluster: "", instance }; ++ const team = form && teamField ? (teamField.derivedFrom ? previewTarget[teamField.derivedFrom] ++ : shownValues(form, typed, previewTarget)[valueKey(teamField)] ?? "") : ""; ++ const derivedTeam = form && teamField && (teamField.derivedFrom || defaultSource(form, teamField)?.derivedFrom); + // A label value (PlacementRequest.team), or the preview waits: the form's own check names what is wrong with it. An instance + // whose keys have no team label places with no team. +- const teamOk = teamField === null || LABEL_VALUE.test(team); ++ const teamOk = LABEL_VALUE.test(team) || (!team && (!teamField?.required || !!derivedTeam)); + const ask: PlacementRequest | null = form && env && teamOk && (current?.name ?? tier) +- ? { environment: env, ...(teamField ? { team } : {}), tier: current?.name ?? tier, constraints: activeRegion === ANY_REGION ? {} : { region: activeRegion } } : null; ++ ? { environment: env, ...(team ? { team } : {}), tier: current?.name ?? tier, constraints: activeRegion === ANY_REGION ? {} : { region: activeRegion } } : null; + const [settledAsk, settleAsk] = useSettled(ask, RANK_AFTER_MS); + const preview = usePlacementPreview(settledAsk); + // The planned cluster is the first of the ranking of the ask as it is now; a ranking of an older ask places nothing. +@@ -494,13 +496,15 @@ export function NewNamespaceTab({ config, open }: TabProps) { + */ + const onSubmit = (e: FormEvent) => { + e.preventDefault(); +- if (!canSubmit || !planned) return; +- const request = JSON.stringify(planned); ++ if (!canSubmit || !planned || !planOk) return; ++ // A label derived from the namespace or cluster becomes known after the dry run. ++ const ask = planOk.metadata ? { ...planned.ask, team: planOk.metadata.labels[form.teamKey]?.value } : planned.ask; ++ const request = JSON.stringify({ ...planned, ask }); + setSubmitted(JSON.stringify(planned.body)); + setMoved(null); + const last = held.current; + const reuse = last?.request === request && Date.parse(last.result.expiresAt ?? "") > Date.now() + 30_000 ? last.result : null; +- (reuse ? Promise.resolve(reuse) : placing.place(planned.ask)).then((placed) => { ++ (reuse ? Promise.resolve(reuse) : placing.place(ask)).then((placed) => { + held.current = { request, result: placed }; + if (placed.clusterId !== planned.cluster) { + setMoved(placed.clusterId); +diff --git a/cmapi-portal-ui/src/portal/metadataForm.ts b/cmapi-portal-ui/src/portal/metadataForm.ts +index 364829a..5bd0807 100644 +--- a/cmapi-portal-ui/src/portal/metadataForm.ts ++++ b/cmapi-portal-ui/src/portal/metadataForm.ts +@@ -88,6 +88,7 @@ export interface ExpiryRules { + + /** What the form reads from one answer of GET /api/v1/metadata-keys. */ + export interface MetaForm { ++ teamKey: string; + /** Inputs, then read-only fields, then optional inputs, for each kind; operator-only keys are not offered. */ + fields: MetaField[]; + /** A label value's syntax (labels.additionalProperties): Kubernetes' IsValidLabelValue, which cmapi checks first. */ +@@ -124,7 +125,7 @@ type Json = Record; + export const KEYWORDS = { + /** The members of the answer itself. */ + answer: { read: ["labels", "annotations", "x-cmapi-expiration"], ignored: {} }, +- map: { read: ["type", "properties", "required", "additionalProperties", "propertyNames", "x-cmapi-other-keys"], ignored: {} }, ++ map: { read: ["type", "properties", "required", "additionalProperties", "propertyNames", "x-cmapi-other-keys", "x-cmapi-team-key"], ignored: {} }, + property: { + read: ["type", "pattern", "allOf", "maxLength", "minLength", "enum", "title", "description", "examples", "readOnly", "x-cmapi-rule", + "x-cmapi-derived-from", "x-cmapi-format", "x-cmapi-namespace-prefix", "x-cmapi-namespace-suffix", "x-cmapi-default-from", +@@ -295,7 +296,8 @@ export function fieldsOf(view: unknown): MetaForm { + ]; + ordered.forEach((f, i) => fields.push({ ...f, id: `ns-${kind}-${i}` })); + } +- return { fields, labelValue, operatorOnlyLabels, operatorOnly, otherKeys, expiration: expirationOf(view), edits }; ++ const teamKey = isObject(view.labels) ? textOf(view.labels["x-cmapi-team-key"]) : null; ++ return { fields, teamKey: teamKey ?? "cmapi.net/team", labelValue, operatorOnlyLabels, operatorOnly, otherKeys, expiration: expirationOf(view), edits }; + } + + /** The key of a field's value in the form's state: a key can be a label and an annotation, each with its own value. */ +diff --git a/cmapi-portal-ui/tests/api/metadata-keys.company.json b/cmapi-portal-ui/tests/api/metadata-keys.company.json +index 07f9216..7c796ad 100644 +--- a/cmapi-portal-ui/tests/api/metadata-keys.company.json ++++ b/cmapi-portal-ui/tests/api/metadata-keys.company.json +@@ -116,6 +116,7 @@ + } + } + }, ++ "x-cmapi-team-key": "company.net/mnemonic", + "required": [ + "name", + "company.net/app-environment", +diff --git a/cmapi-portal-ui/tests/api/standin.mjs b/cmapi-portal-ui/tests/api/standin.mjs +index 8c2cf8f..e4ba927 100644 +--- a/cmapi-portal-ui/tests/api/standin.mjs ++++ b/cmapi-portal-ui/tests/api/standin.mjs +@@ -820,7 +820,7 @@ export function missingKeysOf(keys, maps, sources) { + /** NamespaceView of a record: the list's (no Git, no etag) or the detail's (router.py _namespace_view and get_namespace). */ + export function namespaceViewOf(keys, rec, withGit, environment = rec.env) { + const live = rec.live ?? { labels: {}, annotations: {} }; +- return { clusterId: rec.clusterId, name: rec.name, env: live.labels["cmapi.net/env"] ?? null, team: live.labels["cmapi.net/team"] ?? null, tier: live.labels["cmapi.net/tier"] ?? null, ++ return { clusterId: rec.clusterId, name: rec.name, env: live.labels["cmapi.net/env"] ?? null, team: live.labels[keys.labels["x-cmapi-team-key"] ?? "cmapi.net/team"] ?? null, tier: live.labels["cmapi.net/tier"] ?? null, + labels: live.labels, annotations: live.annotations, managed: live.labels["cmapi.net/managed"] === "true", expiresAt: live.annotations["cmapi.net/expires-at"] ?? null, + etag: withGit ? recordEtag(rec) : null, openRequest: rec.openRequest?.requestId ?? null, mnemonic: prefixOf(keys, rec.live), + git: withGit ? { ...rec.git, edits: gitEditsOf(keys, rec.git, environment), +@@ -1172,7 +1172,7 @@ export function apiHandler({ issuer, portalOrigin }) { + const p = state.placements.get(body.placementId); + if (!p || p.used) return problem(res, refuse(422, "placement-not-found", `No active placement ${body.placementId}: it expired, was used by another create, or never existed. Place again.`), cors); + // The team that the namespace will carry: the request's, or the one cmapi fills in (a default), as facts["team"]. +- if (p.clusterId !== clusterId || p.env !== env || p.team !== (made.filled.label["cmapi.net/team"] ?? null)) { ++ if (p.clusterId !== clusterId || p.env !== env || p.team !== (made.filled.label[state.metadataKeys.labels["x-cmapi-team-key"] ?? "cmapi.net/team"] ?? null)) { + return problem(res, refuse(422, "placement-mismatch", `Placement ${body.placementId} was made for another target`), cors); + } + } +diff --git a/cmapi-portal-ui/tests/contract.test.mjs b/cmapi-portal-ui/tests/contract.test.mjs +index 9517cd3..2ba2a77 100644 +--- a/cmapi-portal-ui/tests/contract.test.mjs ++++ b/cmapi-portal-ui/tests/contract.test.mjs +@@ -30,7 +30,7 @@ console.log("ok - contract"); + // #336: the New namespace form evaluates or shows each keyword that GET /api/v1/metadata-keys sends, or lists it as + // ignored with its reason (src/portal/metadataForm.ts, KEYWORDS). A keyword in neither list fails here: the generator + // (MetadataKeys.json_schema) gained a rule that the form would silently check less than cmapi does. +-const { KEYWORDS } = await import("../src/portal/metadataForm.ts"); ++const { fieldsOf, KEYWORDS } = await import("../src/portal/metadataForm.ts"); + const samples = JSON.parse(readFileSync(join(app, "..", "cmapi", "src", "cmapi", "contract", "samples.json"), "utf8")); + const answers = { reference: samples.operations.core_metadata_keys.response.body, + company: JSON.parse(readFileSync(join(app, "tests", "api", "metadata-keys.company.json"), "utf8")), +@@ -64,3 +64,6 @@ for (const [name, answer] of Object.entries(answers)) { + } + assert.deepEqual(unknown, [], "keywords of GET /api/v1/metadata-keys that the form neither evaluates nor lists as ignored"); + console.log("ok - the New namespace form reads each keyword of GET /api/v1/metadata-keys or lists it as ignored"); ++ ++assert.equal(fieldsOf(answers.reference).teamKey, "cmapi.net/team"); ++assert.equal(fieldsOf(answers.company).teamKey, "company.net/mnemonic"); +diff --git a/cmapi/contract/openapi.json b/cmapi/contract/openapi.json +index 943b974..bee4afe 100644 +--- a/cmapi/contract/openapi.json ++++ b/cmapi/contract/openapi.json +@@ -3067,7 +3067,7 @@ + "type": "null" + } + ], +- "description": "Team (`cmapi.net/team`)", ++ "description": "Team from the label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default)", + "examples": [ + "payments" + ], +@@ -4701,7 +4701,7 @@ + "type": "null" + } + ], +- "description": "The `placementId` of POST /api/v1/capacity:place: its hold becomes this request's own. The placement must be active and made for the path's cluster, its environment and the `cmapi.net/team` label sent here", ++ "description": "The `placementId` of POST /api/v1/capacity:place: its hold becomes this request's own. The placement must be active and made for the path's cluster, its environment and the team label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default)", + "examples": [ + null + ], +diff --git a/cmapi/src/cmapi/core/approvals.py b/cmapi/src/cmapi/core/approvals.py +index bbaf57a..7287586 100644 +--- a/cmapi/src/cmapi/core/approvals.py ++++ b/cmapi/src/cmapi/core/approvals.py +@@ -155,6 +155,12 @@ class ApprovalRules: + # A site may still mount the policy shipped before live usage existed. + out.append((Slot("approver-platform", 1, "Live usage unavailable"), + "live usage unavailable: +1 approver-platform", frozenset({"usage"}))) ++ if facts.get("quotaBelowRequested") and not any( ++ "quotaBelowRequested" in names and slot.group == "approver-platform" and slot.count > 0 ++ for slot, _, names in out ++ ): ++ out.append((Slot("approver-platform", 1, "Quota below requested"), ++ "quota below requested: +1 approver-platform", frozenset({"quotaBelowRequested"}))) + if facts.get("beyondTier") and not any(names & BEYOND_FACTS for _, _, names in out): + g = self.defaults["group"] + out.append((Slot(g, 1, "Value beyond the tier"), f"beyond the tier, and no rule reads beyondTier: +1 {g}", +diff --git a/cmapi/src/cmapi/core/capacity_ledger.py b/cmapi/src/cmapi/core/capacity_ledger.py +index b521d1e..51c1f84 100644 +--- a/cmapi/src/cmapi/core/capacity_ledger.py ++++ b/cmapi/src/cmapi/core/capacity_ledger.py +@@ -24,15 +24,9 @@ from dataclasses import dataclass, field + from decimal import Context, Decimal + from typing import Any, Iterable, Mapping + +-from cmapi.core.tiers import qty ++from cmapi.core.tiers import REQUEST_KEYS, binding_hard as binding_hard, qty + + RESOURCES = ("cpu", "memory") +-# A quota's `cpu` and `memory` are the same resources as `requests.cpu` and `requests.memory` +-# (https://kubernetes.io/docs/concepts/policy/resource-quotas/): the pod evaluator charges a pod's requests to both names, +-# and quota admission refuses a pod that exceeds either hard value (kubernetes v1.34.0, pkg/quota/v1/evaluator/core/pods.go, +-# podComputeUsageHelper; staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go, LessThanOrEqual). So a quota with both +-# lets the namespace commit the smaller of the two, and that is what is counted, once. +-REQUEST_KEYS = {"cpu": ("requests.cpu", "cpu"), "memory": ("requests.memory", "memory")} + MANAGED = "cmapi.net/managed" + + +@@ -87,17 +81,6 @@ def _bound(hard: Mapping[str, Any], used: Mapping[str, Any], resource: str) -> B + return Bound(value, None) + + +-def binding_hard(hard: Mapping[str, Any] | None) -> dict[str, str]: +- """A quota's hard values with each short name (`cpu`, `memory`) folded into its long name, the smaller of the two: the +- limit that admission enforces and the ledger counts (#393). The planner sizes a change from this, so a quota in Git that +- bounds CPU by `cpu` alone, or by a `cpu` tighter than its `requests.cpu`, is not read as no bound (#710).""" +- out = {k: str(v) for k, v in (hard or {}).items()} +- for long, short in REQUEST_KEYS.values(): +- if short in out: +- out[long] = min(out.get(long, out[short]), out[short], key=qty) +- return out +- +- + def quota_facts(obj: Mapping[str, Any]) -> QuotaFacts | None: + """The facts of a quota that cmapi manages, or None for any other quota.""" + meta = obj.get("metadata") or {} +diff --git a/cmapi/src/cmapi/core/metadata.py b/cmapi/src/cmapi/core/metadata.py +index 7bafbd5..e731992 100644 +--- a/cmapi/src/cmapi/core/metadata.py ++++ b/cmapi/src/cmapi/core/metadata.py +@@ -1608,6 +1608,8 @@ class MetadataKeys: + # A character is one to four bytes in UTF-8, so a bound on bytes is at least this bound on characters. + extra["maxLength"] = other.max_value_bytes + schema: dict[str, Any] = {"type": "object", "properties": properties} ++ if kind == "label" and not patch and self.team_key != DEFAULT_TEAM_KEY: ++ schema["x-cmapi-team-key"] = self.team_key + # A filled-in key is required too (#479, A1): a client sends its value or leaves it out, and cmapi fills it in. + required = [key for key, rule in rules.items() if rule.required] + if required and not patch: +diff --git a/cmapi/src/cmapi/core/models.py b/cmapi/src/cmapi/core/models.py +index 2829304..0b2d220 100644 +--- a/cmapi/src/cmapi/core/models.py ++++ b/cmapi/src/cmapi/core/models.py +@@ -415,7 +415,7 @@ class NamespaceCreate(RequestBody): + placement_id: str | None = Field(default=None, description="The `placementId` of POST /api/v1/capacity:place: its hold " + "becomes this request's own. The placement must be active and " + "made for the path's cluster, its environment and the " +- "`cmapi.net/team` label sent here", examples=[None]) ++ "team label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default)", examples=[None]) + on_behalf_of: str | None = Field(default=None, description="Username or employee ID, for services and automation", examples=[None]) + justification: str | None = Field(default=None, description="Why the namespace is needed", examples=["Payments service dev namespace"]) + +@@ -754,7 +754,7 @@ class ExpirationRow(Api): + name: str = Field(description="Namespace", examples=["sprint-dev"]) + cluster_id: str = Field(description="Cluster", examples=["CRC"]) + env: str | None = Field(description="Environment (`cmapi.net/env`)", examples=["dev"]) +- team: str | None = Field(description="Team (`cmapi.net/team`)", examples=["payments"]) ++ team: str | None = Field(description="Team from the label named by metadata-keys.yaml `teamKey` (`cmapi.net/team` by default)", examples=["payments"]) + app: str | None = Field(default=None, description="`cmapi.net/app`", examples=[None]) + created: date | None = Field(description="The day the namespace was created on the cluster (its creationTimestamp), UTC", + examples=["2026-10-01"]) +diff --git a/cmapi/src/cmapi/core/pipeline.py b/cmapi/src/cmapi/core/pipeline.py +index 1c8b6dc..75c9a80 100644 +--- a/cmapi/src/cmapi/core/pipeline.py ++++ b/cmapi/src/cmapi/core/pipeline.py +@@ -25,7 +25,7 @@ from cmapi.core.adoption import (ADOPT_PERMISSION, INSTANCE_LABEL, SYNC_OPTIONS_ + snapshot_hash, standing, unmanaged_phrase) + from cmapi.core.approvals import BEYOND_FACTS, ApprovalLedger, Requirement + from cmapi.core.capacity_backend import CapacityHold, SimulatedCapacity, capacity_exceeded +-from cmapi.core.capacity_ledger import REQUEST_KEYS, binding_hard, nano_units, quota_facts, totals_of ++from cmapi.core.capacity_ledger import REQUEST_KEYS, binding_hard, is_scoped, nano_units, quota_facts, totals_of + from cmapi.core.clients.kube import BadResponse, ClusterUnreachable, KubeError + from cmapi.core.config import InstanceConfig, environment_not_served + from cmapi.core.db.models import ChangeRequestRow +@@ -834,7 +834,7 @@ class Pipeline: + def submit(self, who: Identity, plan: Plan, repo: RequestRepo, jobs: JobRepo, *, idempotency_key: str | None, + body_fingerprint: str, justification: str | None) -> ChangeRequestRow: + rid = repo.next_id() # takes the day's advisory lock: submits are serial from here to the commit +- decide_again = plan.action != "delete" and bool(plan.facts.get("team")) ++ decide_again = bool(plan.facts.get("team")) + if plan.hold is not None: + # The cluster as it is now, under its lock, with every hold taken since the plan (#62): what the rules decide on. + # A request that no longer fits is refused here and nothing is recorded. +@@ -984,6 +984,8 @@ class Pipeline: + live = cache.get("ResourceQuota", ns, name) if isinstance(name, str) else None + if live is None: + return self._use_unknown(cluster_id, ns, f"the live namespace has no ResourceQuota {name}") ++ if is_scoped(live.get("spec") or {}): ++ return self._use_unknown(cluster_id, ns, f"ResourceQuota {name} measures only its scope") + raw = (live.get("status") or {}).get("used") or {} + used = {k: str(v) for k, v in raw.items() if nano_units(v) is not None} + for long, short in REQUEST_KEYS.values(): +diff --git a/cmapi/src/cmapi/core/tiers.py b/cmapi/src/cmapi/core/tiers.py +index ec763a4..519aef2 100644 +--- a/cmapi/src/cmapi/core/tiers.py ++++ b/cmapi/src/cmapi/core/tiers.py +@@ -82,6 +82,25 @@ def qty(value: str | int | float) -> Decimal: + raise ValueError(out_of_range) from None + + ++# A quota's `cpu` and `memory` are the same resources as `requests.cpu` and `requests.memory` ++# (https://kubernetes.io/docs/concepts/policy/resource-quotas/): the pod evaluator charges a pod's requests to both names, ++# and quota admission refuses a pod that exceeds either hard value (kubernetes v1.34.0, pkg/quota/v1/evaluator/core/pods.go, ++# podComputeUsageHelper; staging/src/k8s.io/apiserver/pkg/quota/v1/resources.go, LessThanOrEqual). So a quota with both ++# lets the namespace commit the smaller of the two, and that is what is counted, once. ++REQUEST_KEYS = {"cpu": ("requests.cpu", "cpu"), "memory": ("requests.memory", "memory")} ++ ++ ++def binding_hard(hard: Mapping[str, Any] | None) -> dict[str, str]: ++ """A quota's hard values with each short name (`cpu`, `memory`) folded into its long name, the smaller of the two: the ++ limit that admission enforces and the ledger counts (#393). The planner sizes a change from this, so a quota in Git that ++ bounds CPU by `cpu` alone, or by a `cpu` tighter than its `requests.cpu`, is not read as no bound (#710).""" ++ out = {k: str(v) for k, v in (hard or {}).items()} ++ for long, short in REQUEST_KEYS.values(): ++ if short in out: ++ out[long] = min(out.get(long, out[short]), out[short], key=qty) ++ return out ++ ++ + def _off_step(value: Decimal, step: Decimal) -> bool: + """Whether value is not a whole number of steps. Decimal's % stops with DivisionImpossible when the integer quotient has + more digits than the context's precision, 28 by default, and a requested value can have more. Both come from qty, so +@@ -718,21 +737,25 @@ class TierCatalog: + and a key that a side does not hold is 0: a revert restores a folder as Git held it (Pipeline.restore_facts). + + used: what the namespace's pods request now, per sizable key (the live quota's status.used, Pipeline.quota_used); +- None, or a key it does not hold, is a use that could not be read. A key whose new hard is below its use is ++ None, or a key it does not hold, is a use that could not be read. A lowered key whose new hard is below its use is + below_used: Kubernetes keeps the pods that run and refuses new ones ("Neither contention nor changes to quota will + affect already created resources", https://kubernetes.io/docs/concepts/policy/resource-quotas/). A key that the change + lowers and whose use is unknown is unknown_lowered, and counts as below: an approval fact that cannot be read must + not open the gate it guards (#256, fail closed). A key that the change does not lower cannot newly fall below.""" + pct, delta, below, unknown = {}, {}, [], [] ++ current_hard, new_hard = binding_hard(current_hard), binding_hard(new_hard) + for k in self.sizable: +- old, new = qty(current_hard.get(k, "0")), qty(new_hard.get(k, "0")) ++ key = REQUEST_KEYS[k][0] if k in REQUEST_KEYS else k ++ old, new = qty(current_hard.get(key, "0")), qty(new_hard.get(key, "0")) + delta[k] = new - old + pct[k] = float((new - old) / old * 100) if old else (100.0 if new else 0.0) +- if used is not None and k in used: +- if new < qty(used[k]): +- below.append(k) +- elif new < old: ++ if key not in new_hard or new >= old: ++ continue ++ usage = used.get(key, used.get(k)) if used is not None else None ++ if usage is None: + unknown.append(k) ++ elif new < qty(usage): ++ below.append(k) + cur_c = self.file.tiers.get(current_tier, TierDef(order=0)).custom + new_c = self.file.tiers.get(new_tier, TierDef(order=0)).custom + if cur_c and new_c: +diff --git a/cmapi/src/cmapi/jobs/open_pr.py b/cmapi/src/cmapi/jobs/open_pr.py +index af114ae..42723c2 100644 +--- a/cmapi/src/cmapi/jobs/open_pr.py ++++ b/cmapi/src/cmapi/jobs/open_pr.py +@@ -112,7 +112,7 @@ def open_revert(ctx: AppContext, s: Session, job: JobRow) -> None: + f"{row.request_id} was planned: plan the change again") + ctx.pipeline.check_plugin_offered("namespaces", row.env) + facts = {"plugin": "namespaces", "action": action, "environment": row.env, "namespace": row.namespace, +- "clusterId": row.cluster_id, "team": ctx.cfg.metadata.team_of(labels) or row.team, ++ "clusterId": row.cluster_id, "team": ctx.cfg.metadata.team_of(labels), + "clusterLabels": dict(policy.labels), "automated": True, "reason": "revert", + "capacity": "fits", "capacityFresh": True, "warnings": []} + cap, usage, beyond, hold = CapacityResult("fits", True, None, {"source": "revert"}), None, {}, None +diff --git a/cmapi/tests/core/test_quota_below_requested_256.py b/cmapi/tests/core/test_quota_below_requested_256.py +index dab5eed..7d691a8 100644 +--- a/cmapi/tests/core/test_quota_below_requested_256.py ++++ b/cmapi/tests/core/test_quota_below_requested_256.py +@@ -52,3 +52,38 @@ def test_a_raise_whose_use_is_unknown_is_not_below(cat): + def test_the_same_quota_whose_use_is_unknown_is_not_below(cat): + small = cat.quota_for("prod", "small") + assert cat.compare("prod", "small", small, "small", small, None).facts()["quotaBelowRequested"] is False ++ ++ ++@pytest.mark.parametrize("target", ["500m", "750m", None]) ++def test_only_a_lowered_bound_can_be_below_requested(cat, target): ++ old = {"requests.cpu": "0.5"} ++ new = {"requests.cpu": target} if target is not None else {} ++ for used in ({"requests.cpu": "1"}, None): ++ change = cat.compare("dev", "small", old, "small", new, used) ++ assert change.facts()["quotaBelowRequested"] is False ++ ++ ++@pytest.mark.parametrize("thresholds,expected", [ ++ ([], 1), ([{"when": "quotaBelowRequested", "add": 0}], 1), ++ ([{"when": "quotaBelowRequested", "group": "approver-platform", "add": 2}], 2), ++]) ++def test_unknown_decrease_requires_platform_approval_with_site_rules(cat, thresholds, expected): ++ from cmapi.core.approvals import ApprovalRules ++ ++ rules = ApprovalRules({"environments": {"dev": {"change": 0}}, "thresholds": thresholds, ++ "autoApproval": {"enabled": True, "policies": [{"name": "updates", ++ "match": {"actions": ["update"]}}]}}) ++ change = cat.compare("dev", "small", {"pods": "20"}, "small", {"pods": "10"}, None) ++ decision = rules.decide({**change.facts(), "action": "update", "environment": "dev", ++ "plugin": "namespaces", "capacity": "fits", "capacityFresh": True}) ++ assert decision.auto is None ++ assert [(s.group, s.count) for s in decision.slots] == [("approver-platform", expected)] ++ ++ ++@pytest.mark.parametrize("key,short,old,tighter,used", [ ++ ("requests.cpu", "cpu", "2", "500m", "750m"), ++ ("requests.memory", "memory", "4Gi", "1Gi", "1536Mi"), ++]) ++def test_tighter_alias_in_the_target_is_a_decrease(cat, key, short, old, tighter, used): ++ change = cat.compare("dev", "small", {key: old}, "small", {short: tighter, key: old}, {key: used}) ++ assert change.below_used == [key] +diff --git a/cmapi/tests/core/test_team_key_258.py b/cmapi/tests/core/test_team_key_258.py +index c6e82c3..f5b42a0 100644 +--- a/cmapi/tests/core/test_team_key_258.py ++++ b/cmapi/tests/core/test_team_key_258.py +@@ -71,3 +71,13 @@ def test_every_shipped_copy_names_a_declared_team_label(name): + """A shipped file whose team label is not declared would give no namespace a team, and the allowance would apply to none.""" + keys = MetadataKeys(shipped()[name]) + assert keys.team_key in keys.rules["label"], (name, keys.team_key) ++ ++ ++def test_company_create_schema_identifies_the_placement_team(company): ++ labels = MetadataKeys(company).keys_view()["labels"] ++ assert labels["x-cmapi-team-key"] == "company.net/mnemonic" ++ ++ ++def test_additional_company_example_declares_its_effective_team_key(): ++ keys = MetadataKeys.load(EX / "cluster-configs/policies/metadata-keys.company-479.yaml") ++ assert keys.team_key in keys.rules["label"] +diff --git a/cmapi/tests/service/test_review_771.py b/cmapi/tests/service/test_review_771.py +new file mode 100644 +index 0000000..2c2af27 +--- /dev/null ++++ b/cmapi/tests/service/test_review_771.py +@@ -0,0 +1,111 @@ ++"""PR 771 decision boundaries that can be tested without a running cluster or database.""" ++from types import SimpleNamespace ++from unittest.mock import Mock ++ ++import pytest ++ ++from cmapi.core.approvals import ApprovalRules ++from cmapi.core.clients.kube import WatchCache ++from cmapi.core.metadata import MetadataKeys ++from cmapi.core.models import ExpirationRow, NamespaceCreate ++from cmapi.core.pipeline import EXPIRY_REQUESTER, Pipeline, Plan ++from cmapi.core.ports import CapacityResult ++from conftest import EXAMPLES ++ ++ ++@pytest.mark.parametrize("spec", [{"scopes": ["BestEffort"]}, ++ {"scopeSelector": {"matchExpressions": [{"scopeName": "Terminating", ++ "operator": "Exists"}]}}]) ++def test_scoped_status_cannot_measure_an_unscoped_target(spec): ++ cache = WatchCache(Mock()) ++ for kind, meta, fields in [ ++ ("Namespace", {"name": "billing"}, {}), ++ ("ResourceQuota", {"name": "billing-quota", "namespace": "billing"}, ++ {"spec": spec, "status": {"used": {"requests.memory": "1Gi"}}}), ++ ]: ++ cache._event(kind, {"type": "ADDED", "object": {"metadata": meta, **fields}}) ++ pipeline = Pipeline.__new__(Pipeline) ++ pipeline.registry = Mock() ++ pipeline.registry.cache.return_value = cache ++ assert pipeline.quota_used("CRC", "billing", {"metadata": {"name": "billing-quota"}}) is None ++ ++ ++def test_team_expiry_delete_counts_prior_auto_approvals(): ++ rules = ApprovalRules.load(EXAMPLES / "instances/nonprod/approval-rules.yaml") ++ rules.max_per_team = 1 ++ facts = dict(action="delete", environment="dev", plugin="namespaces", team="billing", reason="expired", ++ noticesSentAtLeast2=True, noOpenRequest=True, notProtected=True, noticesSent=2) ++ pipe = Pipeline.__new__(Pipeline) ++ pipe.cfg = SimpleNamespace(name="nonprod", allowed_environments={"dev"}, approvals=rules) ++ pipe.auto_paused = lambda session: False ++ plan = Plan("CRC", "ns", "dev", "delete", "namespaces", None, {}, {}, {}, rules.decide(facts), ++ CapacityResult("fits", True, None, {}), facts, Mock(), [], "head", reason="expired") ++ assert plan.requirement.auto == "auto:expired-namespace" ++ repo = Mock() ++ repo.auto_approvals_today.return_value = 1 ++ row = pipe.submit(EXPIRY_REQUESTER, plan, repo, Mock(), idempotency_key=None, body_fingerprint="test", ++ justification="expiry") ++ assert row.team == "billing" ++ assert row.requirement["autoFallback"] == "team-allowance" ++ assert row.requirement["auto"] is None ++ ++ ++@pytest.mark.parametrize("model,field", [(NamespaceCreate, "placement_id"), (ExpirationRow, "team")]) ++def test_public_team_field_names_the_configuration(model, field): ++ assert "teamKey" in model.model_fields[field].description ++ ++ ++def test_revert_to_namespace_without_team_clears_the_requests_team(monkeypatch): ++ from importlib import import_module ++ open_pr = import_module("cmapi.jobs.open_pr") ++ ++ path = "clusters/CRC/namespaces/ns/namespace.yaml" ++ previous = {path: "kind: Namespace\nmetadata: {name: ns}\n"} ++ current = {path: "kind: Namespace\nmetadata: {name: ns, labels: {company.net/mnemonic: abc}}\n"} ++ row = SimpleNamespace(status="sync_failed", plugin="namespaces", plan={"prev": previous}, action="update", ++ cluster_id="CRC", namespace="ns", env="dev", team="abc", requester_sub="sub", ++ requester_username="ola", request_id="original") ++ ctx, repo = Mock(), Mock() ++ monkeypatch.setattr(open_pr, "RequestRepo", lambda s: repo) ++ monkeypatch.setattr(open_pr, "JobRepo", lambda s: Mock()) ++ repo.get.return_value = row ++ ctx.cfg.metadata = MetadataKeys.load(EXAMPLES / "cluster-configs/policies/metadata-keys.company.yaml") ++ ctx.git.read_folder.return_value = (current, "head") ++ ctx.pipeline.registry.writable.return_value.policy = SimpleNamespace(environment="dev", labels={}) ++ ctx.pipeline.restore_facts.return_value = (CapacityResult("fits", True, None, {}), {}, None, {}, None) ++ ctx.pipeline.validator.validate.return_value = [] ++ open_pr.open_revert(ctx, Mock(), SimpleNamespace(request_id="original", payload={})) ++ plan = ctx.pipeline.submit.call_args.args[1] ++ assert plan.facts["team"] is None ++ ++ ++def test_legacy_team_value_counts_after_configuring_another_label(): ++ from sqlalchemy import create_engine, text ++ from sqlalchemy.orm import Session ++ ++ from cmapi.core.db.repo import RequestRepo ++ ++ keys = MetadataKeys.load(EXAMPLES / "cluster-configs/policies/metadata-keys.company.yaml") ++ # The pre-upgrade row's team came from cmapi.net/team. Exercise the repository query ++ # using the three columns it reads, including JSON ->> extraction, without a DB server. ++ with Session(create_engine("sqlite://")) as session: ++ session.execute(text("create table change_requests (team text, created_at timestamp, requirement json)")) ++ session.execute(text("insert into change_requests values (:team, CURRENT_TIMESTAMP, :req)"), ++ [{"team": "abc", "req": '{"auto":"auto:create"}'}, ++ {"team": "abc", "req": '{"auto":"none-required"}'}, ++ {"team": "other", "req": '{"auto":"auto:create"}'}]) ++ assert RequestRepo(session).auto_approvals_today(keys.team_of({"company.net/mnemonic": "abc"})) == 1 ++ ++ ++def test_company_team_matches_placement_hold(): ++ from cmapi.core.errors import Problem ++ ++ keys = MetadataKeys.load(EXAMPLES / "cluster-configs/policies/metadata-keys.company.yaml") ++ pipe = Pipeline.__new__(Pipeline) ++ pipe.capacity = Mock() ++ pipe.capacity.placement.return_value = SimpleNamespace(cluster_id="CRC", env="dev", team="abc", cpu=2, memory=0) ++ body = {"placementId": "pl-test"} ++ team = keys.team_of({"cmapi.net/team": "old", "company.net/mnemonic": "abc"}) ++ assert pipe._placement(body, "create", "CRC", "dev", team, {"requests.cpu": "500m"}) == "pl-test" ++ with pytest.raises(Problem, match="another target"): ++ pipe._placement(body, "create", "CRC", "dev", "old", {}) +diff --git a/docs/02-technical-design-v2.md b/docs/02-technical-design-v2.md +index d9d6048..21bda1d 100644 +--- a/docs/02-technical-design-v2.md ++++ b/docs/02-technical-design-v2.md +@@ -1362,7 +1362,7 @@ At startup an invalid catalog stops cmapi with every problem listed. On reload c + | Plan a create or tier change | resolve(env, tier), quota\_for(env, tier, quota, approved), limits\_for(env, tier, limitRange, hard, approved) | The full spec.hard and the full LimitRange values; each custom value is checked against the bounds and step. A value that Git already holds (approved) is not checked against the bounds again | + | Beyond the tier | beyond(env, tier, hard, limit range), rendered\_overrides(quota object, the LimitRange objects) | Each overridable value that differs from the tier, for the facts beyondTier and beyondTierKeys; and the approved overrides of a namespace, read from the annotation cmapi.net/beyond-tier | + | Capacity and placement | the resolved requests.cpu and requests.memory | The size reserved; an increase reserves only the delta | +-| Approval rules | compare(env, old tier, old hard, new tier, new hard, used) | Facts tier, tierChange (up, down, same, to-custom, from-custom, custom), quotaIncreasePct and quotaBelowRequested. `used` is the live ResourceQuota's status.used from the watch cache (Pipeline.quota_used, #256); a key that the change lowers and whose use cannot be read counts as below (fail closed) | ++| Approval rules | compare(env, old tier, old hard, new tier, new hard, used) | Facts tier, tierChange (up, down, same, to-custom, from-custom, custom), quotaIncreasePct and quotaBelowRequested. `used` is the live ResourceQuota's status.used from the watch cache (Pipeline.quota_used, #256); a lowered sizable bound counts as below when its namespace-wide use exceeds the target or is unknown. This requires platform approval even without a configured threshold | + | Render | render(namespace, cluster, instance, env, tier, request, quota, limits, approved) | The ResourceQuota and one LimitRange for each resource, called by core/render/manifests.py, which writes each to its own file. Each object names its own beyond-tier keys in cmapi.net/beyond-tier | + | PATCH or PUT .../quota | normalise(env, hard) | The named tier when the values equal one exactly, otherwise custom | + | Quota view | is\_outdated(env, tier, rendered hash) | State tier-outdated, a filter on GET /api/v1/quotas | +diff --git a/docs/14-authorization.md b/docs/14-authorization.md +index a0d9d7b..8dd53f4 100644 +--- a/docs/14-authorization.md ++++ b/docs/14-authorization.md +@@ -200,7 +200,7 @@ The tests `test_environment_role_cannot_*` cover each route group (`test_review_ + + ### Step 5: who can approve + +-An approval has more checks than the permission (`approvals.py:337-364`). They are in this order: ++An approval has more checks than the permission (`approvals.py:343-370`). They are in this order: + + | Check | Refusal | + |---|---| +@@ -283,7 +283,7 @@ When a person calls, cmapi records the request under the caller of the token. Th + + | Value | Where it comes from | Where it is kept | + |---|---|---| +-| `sub` | The claim `sub` (`claims.py:70`) | The database. Self-approval compares it (`approvals.py:355-356`) | ++| `sub` | The claim `sub` (`claims.py:70`) | The database. Self-approval compares it (`approvals.py:361-362`) | + | Username | The claim `preferred_username` (`claims.py:78`) | The database, and as a label of the namespace (`claims.py:3-5`) | + | `email` | The claim `email` (`claims.py:74`) | The database | + | `employee_id` | The claim `employee_id` (`claims.py:78`) | The database | +@@ -298,7 +298,7 @@ A person calls as themselves. If a person sends `onBehalfOf`, cmapi refuses with + A shared human account, for example `cmapi.requester`, that submits for many people is not in the design. A person cannot use `onBehalfOf` (`checks.py:74-78`), so a shared account would be recorded as the requester. It would have three effects: + + - Attribution is lost. Each request would carry the `sub` and the username of the shared account, and not those of the person. +-- The self-approval check fails. The check compares `sub` values (`approvals.py:355-356`). The requester would carry the `sub` of the shared account. A person who submits through it and then approves with their own account has another `sub`, so the check would not refuse. ++- The self-approval check fails. The check compares `sub` values (`approvals.py:361-362`). The requester would carry the `sub` of the shared account. A person who submits through it and then approves with their own account has another `sub`, so the check would not refuse. + - The employee ID record is lost. The token of the shared account has one `employee_id`, or none, and a person's write needs one when the instance requires it (`checks.py:79-81`). + + A tool that must act for people has its own path: see the next section. +@@ -321,7 +321,7 @@ A tool signs in with the client credentials grant. It is a service client, or an + | The tool sends `onBehalfOf`: a username or an employee ID | cmapi looks the value up in the directory. The person must be enabled, or the answer is 422 `unknown-user`. The person is recorded as the requester and the tool as the caller. The request is recorded as automated | `checks.py:89-95` | + | A person sends `onBehalfOf` | 422 `on-behalf-of-not-allowed` | `checks.py:74-78`; `problem_docs.py:104` | + +-Self-approval uses the requester and the submitter. The ledger refuses the requester as approver: `requester_sub` is the `sub` of the named person (`checks.py:49-53`, `pipeline.py:866`, `approvals.py:355-356`). It also refuses the submitter, which is the `sub` of the tool, unless the approval rule has `selfApproval: true` (`cmapi/src/cmapi/core/db/repo.py:247-249`, `approvals.py:353-354`). The record keeps the submitter in `submittedBySub`, and the response leaves it out (`checks.py:59-64`, `views.py:25-27`). ++Self-approval uses the requester and the submitter. The ledger refuses the requester as approver: `requester_sub` is the `sub` of the named person (`checks.py:49-53`, `pipeline.py:866`, `approvals.py:361-362`). It also refuses the submitter, which is the `sub` of the tool, unless the approval rule has `selfApproval: true` (`cmapi/src/cmapi/core/db/repo.py:247-249`, `approvals.py:359-360`). The record keeps the submitter in `submittedBySub`, and the response leaves it out (`checks.py:59-64`, `views.py:25-27`). + + With `onBehalfOf`, cmapi trusts the tool to name the person. The directory proves that the person exists and is enabled. It does not prove that the person signed in. + +@@ -370,7 +370,7 @@ The code `forbidden` has two more causes. Each is a refusal of the code, not of + | A caller cancels a request that is not theirs and does not hold `namespaces:protect` in its environment | "Only the requester or an operator can cancel" | `cmapi/src/cmapi/core/lifecycle.py:125`, `cmapi/src/cmapi/routers/requests.py:211` | + | A write sets or removes an operator-only label or annotation (`cmapi.net/protected`, `do-not-delete`) and the caller does not hold `namespaces:protect` in the environment | "Needs namespaces:protect in . Keys: ." (the cluster's environment, #532) | `cmapi/src/cmapi/core/metadata.py:1434` | + +-The ledger also refuses a relay client without `approvals:relay` with this code ("Relay client lacks approvals:relay", `cmapi/src/cmapi/core/approvals.py:347`), but no route can reach it: the approve route in `routers/requests.py` passes no relay to `ApprovalLedger.approve` (see "What is not built"). ++The ledger also refuses a relay client without `approvals:relay` with this code ("Relay client lacks approvals:relay", `cmapi/src/cmapi/core/approvals.py:353`), but no route can reach it: the approve route in `routers/requests.py` passes no relay to `ApprovalLedger.approve` (see "What is not built"). + + A sample 403, taken from a run of the service suite's app on 2026-11-13. A caller with the role `cmapi-viewer` sent `POST /api/v1/admin/auto-approval:pause`: + +@@ -394,7 +394,7 @@ A sample 403, taken from a run of the service suite's app on 2026-11-13. A calle + |---|---| + | Routes for quotas, service accounts, grants, configuration, cluster onboarding, reload, events and audit export | Not built. Their permissions exist in `authz.py`, and no route uses them | + | `adoption:write`: the scan of a cluster and the unmanaged-namespaces report (#252's admin operations) | Not built. The adoption of one namespace is self-service: its three routes need `namespaces:write` in the cluster's environment, and the approval rules gate it (#739, the owner's decision of 2026-11-26 on #26). The routes declare and enforce the same permission (`cmapi/src/cmapi/plugins/adoption/router.py`, `ADOPT_PERMISSION`) | +-| The approval relay for email, ServiceNow and chat (`approvals:relay`) | The check exists in `approvals.py:344-347`. No route accepts a relayed approval | ++| The approval relay for email, ServiceNow and chat (`approvals:relay`) | The check exists in `approvals.py:350-353`. No route accepts a relayed approval | + | A scope by team or by namespace name | Not designed. A role with `namespaces:create` can ask for each name that is not reserved (`authz.py:8-10`) | + + ## Proof +diff --git a/docs/18-configuration.md b/docs/18-configuration.md +index 26f1060..ad1e814 100644 +--- a/docs/18-configuration.md ++++ b/docs/18-configuration.md +@@ -437,7 +437,7 @@ The rules for the labels and the annotations that a requester sets on a namespac + | `adoptionLabels` | mapping of key to `{recognise: [values]}` | `{}` | Labels that mark a namespace that another tool made. A requester cannot set them: the class of such a key is `reserved`. Today cmapi reads only the keys, for that class. The adoption (story #26) reads the values: a namespace that carries one is listed as `recognised` among the candidates, and the plan reports it as `adoption-label` | + | `sensitiveKeys` | list of keys | `[]` | A change of the value of one of these keys adds the fact `sensitiveKeyChanged`, once per request: a value that Git holds changes or goes, or a change of an existing namespace adds a required or extra key (#481). The first value of a create, and the first set of an operator-only key, are not a change. The shipped files list `cmapi.net/protected` and `do-not-delete`: protecting a namespace needs no extra approval, and removing the protection adds one approver-platform approval (#366) | + | `emailDomains` | list of domains | `[]` | The mail domains for a key with `format: email-in-domains`. A key of that format needs at least one domain | +-| `teamKey` | a label key | `cmapi.net/team` | The label that names a namespace's team (#258). Placement (`POST /api/v1/capacity:place`, whose `team` the create's label must match), the approval fact `team`, the daily allowance `maxPerTeamPerDay`, the team's rate-limit bucket, `change_requests.team` and the `team` of the namespace, quota and expiration lists read it. A key that the file names here must be a label that `requiredLabels` or `extraLabels.keys` declares, or the file is refused (`teamKey: is not a label that requiredLabels or extraLabels.keys declares`): a key read on no namespace would leave the allowance applying to none, silently. Without the stanza it is `cmapi.net/team`, declared or not, as before the stanza. The company example names `company.net/mnemonic` | ++| `teamKey` | a label key | `cmapi.net/team` | The label that names a namespace's team (#258). Placement clients read a custom key from `labels.x-cmapi-team-key` in `GET /api/v1/metadata-keys`. Placement (`POST /api/v1/capacity:place`, whose `team` the create's label must match), the approval fact `team`, the daily allowance `maxPerTeamPerDay`, the team's rate-limit bucket, `change_requests.team` and the `team` of the namespace, quota and expiration lists read it. A key that the file names here must be a label that `requiredLabels` or `extraLabels.keys` declares, or the file is refused (`teamKey: is not a label that requiredLabels or extraLabels.keys declares`): a key read on no namespace would leave the allowance applying to none, silently. Without the stanza it is `cmapi.net/team`, declared or not, as before the stanza. The company example names `company.net/mnemonic` | + | `liveOnlyKeys` | list of key globs | `[kubernetes.io/metadata.name, "openshift.io/*", "argocd.argoproj.io/*", app.kubernetes.io/instance]` | Keys that the cluster or its controllers write on a live namespace and Git never holds. `GET .../namespaces/{ns}` compares each governed, extra and operator-only key of Git with the live namespace (`sync`, #481) and leaves these out, so they are never drift. `*` matches as in `fnmatch`. Without the stanza, the default applies; an empty list compares every such key. System and reserved keys are never compared | + + Where `emailDomains` is set: in each deployment's metadata configuration. On CRC it is `deploy/manifests/environments/crc/20-config.yaml`, key `emailDomains`; on kind it is the same key in `deploy/manifests/environments/kind/20-config.yaml`. The examples are `examples/cluster-configs/policies/metadata-keys.yaml` (`[ephico2real.com]`, a placeholder) and the company profile `metadata-keys.company.yaml` (`[company.net]`). To change it on CRC, edit that key, apply the ConfigMap, then `oc rollout restart deploy/cmapi-api deploy/cmapi-worker -n cmapi`. The domain is checked for format only: cmapi never looks a DL up. +@@ -803,7 +803,7 @@ A `when` line reads these facts. The names are fixed in the code. An unknown nam + | `plugin`, `action`, `environment`, `namespace`, `clusterId`, `reason`, `team`, `tier` | The request | `core/pipeline.py` | + | `tierChange` | `up`, `down`, `same`, `to-custom`, `from-custom` or `custom`. Set for a change of an existing namespace only | `TierCatalog.compare` | + | `quotaIncreasePct` | The largest increase of a sizable key, in percent. Set for a change of an existing namespace only | `QuotaChange.quota_increase_pct` | +-| `quotaBelowRequested` | On a change of an existing namespace's quota (a plan, or a revert): a sizable key's new hard value is below what the pods request now, so Kubernetes would refuse new pods (#256). The use is the `status.used` of the live ResourceQuota that Git's quota is, from the cluster's watch cache. A key that the change lowers and whose use cannot be read counts as below (fail closed): the watch has not listed, is stale (no good read for 30 minutes) or is refused (401, 403), or the live namespace has no such quota. A namespace that the watch does not hold has no pods. A key that the change does not lower is not below for want of a read. The planner logs `quota_used_unknown` with the reason | `Pipeline.quota_used`, `TierCatalog.compare` | ++| `quotaBelowRequested` | On a change of an existing namespace's quota (a plan, or a revert): the change lowers a sizable key's hard value below what the pods request now, so Kubernetes would refuse new pods (#256). The use is the `status.used` of the live ResourceQuota that Git's quota is, from the cluster's watch cache. A key that the change lowers and whose use cannot be read counts as below (fail closed): the watch has not listed, is stale (no good read for 30 minutes) or is refused (401, 403), or the live namespace has no matching unscoped quota or usable value for that key. A namespace that the watch does not hold has no pods. Removing a bound or keeping or raising its value does not trigger this fact. A true fact requires a positive platform approval even if the site has omitted the threshold. The planner logs `quota_used_unknown` when it cannot use the quota object | `Pipeline.quota_used`, `TierCatalog.compare` | + | `requestToPeakRatio` | On a change of an existing namespace's quota, with `usage` `ok`: the largest planned hard limit over the namespace's 14-day peak, of a resource the change raises (#310). Absent otherwise, so a rule that reads it adds nothing | `plan_usage`, `capacity/usage.py` | + | `usage` | On a change of an existing namespace's quota: `ok`, `insufficient-data` (no usage source, or under 80% of the window's samples) or `unavailable` (Thanos did not answer, or the cluster's import check found the reader without its own Thanos grants, #724). The shipped rule adds approver-platform on `usage == "unavailable"`. If the active policy has no matching usage threshold that adds that group, the planner supplies one platform slot (#310) | `plan_usage`, `capacity/usage.py` | + | `capacity`, `capacityFresh` | `fits`, `warn`, `exceeded` or `unknown`, and whether the data is fresh. `unknown`, not fresh, when the cluster has neither `simulatedCapacity` nor fresh counted node allocatable, no watch cache, ResourceQuotas not listed yet, ResourceQuota reads refused (401 or 403), or a ResourceQuota watch with no good read for 30 minutes (#393). What is committed comes from the cluster's quota ledger: per namespace the smallest unscoped managed quota, scoped quotas left out (#302). The check adds the capacity that open requests hold (`capacity_reservations`, #62): each request with an increase holds it from submit until it leaves the holding states, and a hold stops counting once the ledger shows its quota. Submit checks again under the cluster's lock and takes the hold in the same transaction, so a request that fit when planned but not beside a hold taken since is refused (`exceeded`) or decided on the new answer; the last `:approve` and a `:retry` from `failed` check again and answer 422 `capacity-exceeded` when the request no longer fits | `core/capacity_backend.py`, `core/capacity_ledger.py` | +diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md +index a970f31..702c565 100644 +--- a/docs/GLOSSARY.md ++++ b/docs/GLOSSARY.md +@@ -111,7 +111,7 @@ Status: read from `main` at `afd1206` on 2026-11-23. Each row was read from the + | `base_sha` (`baseSha`) | The Git commit that the plan was made against. | [core/models.py](../cmapi/src/cmapi/core/models.py) | + | `request_events` | The table of one state change or note of a request, in order. `GET /api/v1/requests/{request_id}/events` reads it. Migration 0007 makes its time the insertion time. | [16-data-model.md](16-data-model.md) | + | Approval | One approval of one request by one person, in `approvals`. A person counts once (migration 0002). Requesters cannot approve their own request (409 `self-approval`). | [16-data-model.md](16-data-model.md), [core/docs.py](../cmapi/src/cmapi/core/docs.py) | +-| `quotaBelowRequested` | The approval fact of a quota change whose new hard value of a sizable key is below what the namespace's pods request now (the live ResourceQuota's `status.used`, #256). A lowered key whose use cannot be read counts as below (fail closed). | [18-configuration.md](18-configuration.md), [core/tiers.py](../cmapi/src/cmapi/core/tiers.py) | ++| `quotaBelowRequested` | The approval fact of a quota change that lowers the hard value of a sizable key below what the namespace's pods request now (the live ResourceQuota's `status.used`, #256). A lowered key whose use cannot be read counts as below (fail closed). | [18-configuration.md](18-configuration.md), [core/tiers.py](../cmapi/src/cmapi/core/tiers.py) | + | Auto-approval | An `auto:` rule of `approval-rules.yaml` that approves a plan with no person. A Kyverno warning keeps it from applying. `approvals:pause` stops it. | [18-configuration.md](18-configuration.md), [core/lifecycle.py](../cmapi/src/cmapi/core/lifecycle.py) | + | `:cancel`, `:approve`, `:reject`, `:retry`, `:revert` | The verbs on `/api/v1/requests/{request_id}`, each with its permission (`requests:cancel`, `requests:approve`, `requests:reject`, `requests:retry`; `:revert` also needs `requests:retry`). | [14-authorization.md](14-authorization.md), [core/lifecycle.py](../cmapi/src/cmapi/core/lifecycle.py) | + | In sync, Pending, Drift, Unknown | The state of a namespace in the portal and in the API field `state`. `pending`: an open request holds the namespace, also after the merge and before the cluster has it. `drift`: no request is open and a governed, extra or operator-only key differs between Git and the cluster, or the cluster does not have the namespace. `in-sync`: they are the same. `unknown`: cmapi cannot compare. | [schema.generated.ts](../cmapi-portal-ui/src/api/schema.generated.ts), [NamespacesTab.tsx](../cmapi-portal-ui/src/portal/NamespacesTab.tsx) | +diff --git a/docs/citations.lock.json b/docs/citations.lock.json +index 87fa178..22cbfac 100644 +--- a/docs/citations.lock.json ++++ b/docs/citations.lock.json +@@ -1,5 +1,5 @@ + { +- "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|337-364": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|343-370": [ + " def approve(self, approver: Identity, *, permitted: bool | None = None, relay: Identity | None = None,", + " relay_permitted: bool | None = None, comment: str = \"\") -> bool:", + " \"\"\"approver is the eligible person; relay is the channel client (approvals:relay) if any.", +@@ -29,20 +29,20 @@ + " return self.met", + "" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|344-347": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|350-353": [ + " if relay is not None:", + " ok = relay_permitted if relay_permitted is not None else \"approvals:relay\" in builtin_permissions(relay)", + " if not ok:", + " raise Problem.forbidden(\"Relay client lacks approvals:relay\")" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|347-347": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|353-353": [ + " raise Problem.forbidden(\"Relay client lacks approvals:relay\")" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|353-354": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|359-360": [ + " if approver.sub in self.client_owner_subs or approver.sub == self.operation_starter_sub:", + " raise Problem.conflict(\"self-approval\", \"The operation starter or client owner cannot approve\")" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|355-356": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/approvals.py|361-362": [ + " if approver.sub == self.requester_sub and not self.requirement.self_approval:", + " raise Problem.conflict(\"self-approval\", \"Requesters cannot approve their own request here\")" + ], +``` diff --git a/docs/reviews/2026-12-01-issue-256-258/reviewer-2-fable.md b/docs/reviews/2026-12-01-issue-256-258/reviewer-2-fable.md new file mode 100644 index 00000000..e8e232e3 --- /dev/null +++ b/docs/reviews/2026-12-01-issue-256-258/reviewer-2-fable.md @@ -0,0 +1,400 @@ +# Reviewer 2 (Fable 5.2) on PR #771 and on reviewer 1's fix + +PR #771 (`Closes #256`, `Closes #258`), head `cff8b36c`, base `0030e34`. Reviewer 1 is Codex gpt-6.2-astra +(`codex-report.md`, `codex-fix.diff`). I did not write the PR or reviewer 1's fix. + +## Read this first + +1. **`export/` is not the PR head.** Reviewer 1 worked in it, so it already holds `codex-fix.diff` + (`patch -p1 -F0 < codex-fix.diff` in a copy answered "Reversed (or previously applied) patch detected" for every + file). I took the head from Git (`git -C cmapi-design archive cff8b36c`, in `head/`); `head/` plus `codex-fix.diff` + is byte-identical to `export/`. **`final.diff` is against the PR head `cff8b36c`, not against `export/` as it is + now.** It applies to a fresh `git archive cff8b36c` with `patch -p1 -F0`, and it will not apply to `export/`. +2. **The PR head fails CI.** `gh pr checks 771`: `service` fail. The job log: `2 failed, 3431 passed`, both in + `tests/service/test_review_479_expiry.py`, `TypeError: cannot unpack non-iterable Mock object` at + `pipeline.py:976` (`stale, last = cache.kind_stale(kind)`). Reviewer 1 did not see it and its fix does not repair it: + the same 2 fail on `head/` plus `codex-fix.diff` (measured, `r2-outputs/before-ci-479-on-codex-tree.txt`). It is my + finding R2-1, fixed in `final.diff`. +3. **The portal suites did not run here.** No `node_modules` of `cmapi-portal-ui` exists on this machine to link + (`cmapi-design/cmapi-portal-ui/node_modules` is absent, and no worktree has one), and the brief forbids an install. So + `tsc --noEmit`, `vite build`, `direct.test.mjs` and the browser suites were **not run** on `final.diff`. I ran what + needs no package: `contract.test.mjs`, `standin.test.mjs`, `check-discipline.mjs`, and `api-types.mjs --check` with the + generator's own `node_modules` linked from `wt-256`. Because of this I cut reviewer 1's portal change down to one + lookup that is tested in Node (T3 below). CI's `portal-ui` job is the gate for the rest. + +## Rulings on reviewer 1's findings + +| ID | Reviewer 1 | Ruling | Severity as I rate it | +|---|---|---|---| +| Q1 | Only a lowered bound can be below | **Accept** | Medium | +| Q2 | A tighter short name in the target is a decrease | **Accept** | Medium (reviewer 1: High) | +| Q3 | A scoped quota's `status.used` is not the namespace's use | **Accept** | Medium (reviewer 1: High) | +| Q4 | A true fact always adds approver-platform | **Amend**: default closed when the file is silent; a rule that reads the fact stands | High as found, the fix was too wide | +| T1 | Deletes skip the team's daily allowance at submit | **Accept**, kept in this PR (one line) | Medium (reviewer 1: High); predates the PR | +| T2 | A revert to a Namespace with no team keeps the request's team | **Reject** here; issue text written | Low; predates the PR | +| T3 | The portal places with no team on a custom `teamKey` | **Amend**: the API key and one portal lookup accepted; the rest of the portal change rejected | High; introduced by the PR | +| T4 | Two API descriptions still name `cmapi.net/team` as the key | **Accept** | Low | + +### Q1: accept + +The design's sentence is about a decrease: docs/01:480, "A decrease below what pods already request is refused unless +approver-platform approve, because new pods would be rejected at admission." The PR head set the fact for any key whose +new value was under the use, also one kept or raised (a quota already below its use, approved earlier, then flagged again +on each label change), and for a key that the target drops (read as 0). A dropped bound is no bound: nothing is refused at +admission. Reviewer 1's condition (the key is in the target and its value is smaller) is right. Delta and percent are +unchanged. + +### Q2: accept + +`_plan_namespace` passed `binding_hard(old)` and the raw target, so a target that adds a tighter `cpu` beside an unchanged +`requests.cpu` was not a decrease. Kubernetes, Resource Quotas (https://kubernetes.io/docs/concepts/policy/resource-quotas/, +fetched 2026-12-01): "`cpu` | Same as `requests.cpu`" and "`memory` | Same as `requests.memory`". The capacity ledger +already folds the two names (`binding_hard`, #393, #710); `compare` now does the same on both sides. Moving `REQUEST_KEYS` +and `binding_hard` into `tiers.py` is needed (`capacity_ledger` imports `tiers`, not the reverse) and +`capacity_ledger` still exports both names. One side effect, which I accept and name: `quotaIncreasePct` of a target that +holds a short name is now computed from the binding value on both sides, where the head mixed a folded old value with a +raw new one. A shipped tier writes no short name, so no shipped configuration changes. I rate it Medium because it needs a +catalog that writes `cpu` or `memory` beside the long name. + +### Q3: accept + +ResourceQuota API reference (https://kubernetes.io/docs/reference/kubernetes-api/policy-resources/resource-quota-v1/, +fetched 2026-12-01), `spec.scopes`: "A collection of filters that must match each object tracked by a quota. If not +specified, the quota matches all objects." So a scoped quota's `status.used` counts only the pods of its scope, and it +cannot say that an unscoped target stays above the namespace's use. Unknown is the right answer, and a lowered key then +counts as below. It reuses the ledger's `is_scoped`. Reach: a lone adopted quota that is scoped (`own_quota`, #253). + +### Q4: amend. The site's rule stands; a silent file does not open the gate + +The question from the brief: is overriding a site's approval-rules.yaml right for the unknown case only, for the known +case too, or for neither? **Neither as an override. For both cases the engine supplies an approver only when no true +threshold reads the fact; a rule that reads it is the site's answer, with its group and count, `add: 0` included.** + +The texts this rests on: + +- docs/01:480: "A decrease below what pods already request is refused unless approver-platform approve". The design wants + an approver for this change. +- docs/01:539 lists it among the thresholds: "Thresholds add approvers from the plan's facts: quota increase over 100%, + ..., a decrease below what pods request, a custom-tier value beyond the tier, ...". So the site's file is where it is + answered. +- docs/18:789: "`thresholds[].add` ... `add: 0` is a rule that answers and adds no approver." +- docs/18:835-836, the owner's rule from #211 for the fact next to it in that list: "When no true threshold reads one of + those facts, cmapi adds one approver of `defaults.group` ... An instance that removes the rule does not open the gate by + accident." and "A rule that means no extra approver says `add: 0`." +- The owner on #211: approval rules are the gate. + +Why not "neither" in the plain sense (no engine default): before this PR the fact was always false, so a site that dropped +the dead rule from its file decided nothing by dropping it. On the PR head such a file turns a decrease below the use, and +a decrease whose use cannot be read, into `auto:` or `none-required` (reviewer 1's test shows `auto:updates`). That +is the accident that docs/18:835 names. + +Why not reviewer 1's override: its guard adds approver-platform unless a rule adds a positive approver-platform slot. So +it overrides `add: 0`, which docs/18:789 and :836 define as the site's "no extra approver", and it adds a second slot to a +site whose rule sends the fact to another group. Both are explicit answers of the site's own policy file. + +Why the unknown case gets no stricter rule than the known one: the PR already fails closed where the unknown is, in the +fact. docs/18, fact `quotaBelowRequested`: "A key that the change lowers and whose use cannot be read counts as below (fail +closed)". The PR cites OWASP for it: "a failure will follow the same execution path as disallowing the operation". With the +amendment an unknown use follows exactly the path of a known use below the target. A site that answers the known case with +`add: 0` has accepted the worst case that the unknown could be, so there is nothing stricter to fall back on. The docs/01 +sentence "the plan carries usage: unavailable and the change needs a platform approval instead of failing" is about the +14-day usage read from Thanos (the fact `usage`), which #310 enforces on its own and this PR does not touch. + +The group of the default is `defaults.group`, as for `beyondTier`, because that is what the shipped rule +(`when: quotaBelowRequested`, `add: 1`, no group) gives. It is approver-platform unless the site changed its default. + +The code, in `ApprovalRules._added` (`cmapi/src/cmapi/core/approvals.py:160`), replacing reviewer 1's block: + +```python + if facts.get("quotaBelowRequested") and not any("quotaBelowRequested" in names for _, _, names in out): + # The fact was always false before #256, so a file without the rule never answered it. A file that answers it, + # with any group or with `add: 0`, is the site's policy and stands, also for a use that could not be read. + g = self.defaults["group"] + out.append((Slot(g, 1, "Quota below what pods request"), + f"quota below what pods request, and no rule reads quotaBelowRequested: +1 {g}", + frozenset({"quotaBelowRequested"}))) +``` + +Tests (`cmapi/tests/core/test_quota_below_requested_256.py`), each for a known use above the target and for an unknown use: +`test_a_file_without_the_rule_does_not_open_the_gate` (no threshold; another `defaults.group`; a rule that is false for +the request) and `test_a_rule_that_reads_the_fact_is_the_sites_answer` (the shipped rule, 2 platform, another group, +`add: 0` with `auto:updates`). Measured on the PR head: both cases of the silent-file test fail (the request is auto-approved); the rule tests pass there, since the head adds nothing to a rule. Reviewer 1's guard fails the `add: 0` and other-group cases by its code (not run). + +If the coordinator rules the other way for the unknown case, it needs one more fact, because the engine cannot tell +unknown from known today: `QuotaChange.facts()` would add `"quotaUseUnknown": bool(self.unknown_lowered)` and `_added` +would apply reviewer 1's guard to that fact only. I do not recommend it, for the reason above. + +docs/02 (the Approval rules row of the tier catalog table) and docs/18 (the fact's row) say the amended rule. docs/02 is +an export of a live Claude Doc: the live doc needs the same sentence, by the coordinator. + +### T1: accept, kept in this PR + +History: `plan.action != "delete"` is in the first service commit (fd36e661, 2026-11-05), and #62 (832a90b5) only renamed +it into `decide_again`. No commit, review record or doc gives a reason for it. The `expired-namespace` policy was already +there on that day (`_auto` in fd36e661 has the `expiry_policy` exception), so the exclusion never matched the design: + +- docs/01:561: "A team gets at most maxPerTeamPerDay auto-approvals (20 by default)." +- docs/01:563, "Guards no policy can switch off": "A matching request still goes to humans when it is a delete (other than + expired-namespace, which has its own guards), ..., or when the team's daily allowance is used." The exception for + expired-namespace is from the guard on deletes, not from the allowance. +- docs/18:794: "cmapi counts at submit, for a request with a team." +- `jobs/expire_check.py`, step 4: "the approval rules decide it (the expired-namespace policy, or the environment's delete + rule with approvers)". A delete that falls to approvers is a designed outcome. + +And the count is already one-sided: an auto-approved expiry delete is an `auto:` row with a team, so +`auto_approvals_today` counts it against the team's later creates, while nothing limited the deletes themselves. + +What the one line changes, checked case by case: an expiry delete of a team over its allowance goes to the environment's +delete rule; an expiry delete planned before a pause and submitted after it now sees the pause (read in the submit +transaction); every other delete matches no expiry policy and falls back on the guard `delete` before the allowance is +looked at, as at plan time, so its requirement is the same. `test_expire_check_263.py` (23 tests on main's behaviour) +passes unchanged with the fix. + +Severity: Medium, not High. The four guards of the policy and the operator's prune confirmation still stand behind it. +It predates the PR; it stays here because the fix is one line in a function the PR's subject (#258, the allowance) runs +through. + +I added a PostgreSQL test to reviewer 1's mock test: `test_the_expiry_delete_counts_against_the_teams_daily_allowance` +(`cmapi/tests/service/test_expire_check_263.py`), through the real `expire_check` job. + +### T2: reject in this PR + +`team_of(labels) or row.team` is main's `labels.get("cmapi.net/team") or row.team` (f109f618, #719/#720) with the key made +configurable: the PR keeps the behaviour. The review of #719/#720 measured this very case and kept it +(docs/reviews/2026-11-26-issue-719-720/review/reviewer-2-opus.md, row M5: "delete, team payments (row.team), the same as +base"). Reviewer 1's fix makes the case looser, not stricter: with no team, submit counts no allowance for the revert. +The approval policies do not match on team, so the only effects of the fallback are the recorded `team` and whose +allowance is counted. That is a question of meaning, Low, and not this PR's. `final.diff` keeps the PR's line and drops +reviewer 1's test for it. Issue text: `r2-outputs/issue-texts.md`, Issue A. + +### T3: amend. The regression is real and the PR introduced it + +On main the create's team with the company file was `None` (it read `cmapi.net/team`), which matched the portal's hold +with no team. The PR makes the create's team the mnemonic, and the portal still looks for a field `cmapi.net/team`, finds +none and places with no team. `Pipeline._placement` then refuses every portal create on a company instance: 422 +`placement-mismatch` ("the placement's team is None, the create's 'abc'"). CI's `portal-ui` job passes on the head because +no browser test creates through the company answer. + +Accepted from reviewer 1: + +- **The API key.** `GET /api/v1/metadata-keys` and the create's label schema carry `x-cmapi-team-key` on the labels map + when the team label is not `cmapi.net/team` (`metadata.py:1612`). It is additive: left out for the default, so the + reference answer, `samples.json`, docs/04 and the committed contract do not change for it (the committed-contract test + and `api-types.mjs --check` pass). The company fixture `metadata-keys.company.json` gains the key and + `tests/core/test_metadata_form_336.py`, which holds the fixture to `keys_view()`, passes. +- `MetaForm.teamKey` in `metadataForm.ts`, `KEYWORDS.map.read`, the stand-in server's two readers. + +Changed by me: + +- **`NewNamespaceTab.tsx` is the head's file with one lookup changed**: `teamFieldOf(form)` in place of the constant + `TEAM_KEY`. `teamFieldOf` is a new pure function in `metadataForm.ts`, so the lookup is tested in Node + (`tests/contract.test.mjs`: the reference, company and company-479 answers, and an answer with no team field). For each + answer whose team label is `cmapi.net/team`, which is every answer the browser suites serve, the tab computes what the + head computes. +- **Rejected: the rest of reviewer 1's change to the tab** (a derived or optional team ranks with no team; Submit places + with the dry run's team label). It goes beyond the defect: it changes Submit for every instance and what an optional + empty team does. It also has a hole of its own: a ranking made with no team and a hold taken with the team can choose + different clusters, the form then says "Placement now holds X", and Check ranks with no team again. And I could not + type-check or run it. No shipped file has a derived or optional team label. Issue text: `r2-outputs/issue-texts.md`, + Issue B (Low). +- **Documented**: docs/18 (the `teamKey` row, and a row in the table of schema keywords), docs/09 (the keyword check), + GLOSSARY (`teamKey`). Reviewer 1 had one clause in docs/18. + +### T4: accept + +`NamespaceCreate.placement_id` and `ExpirationRow.team` named `cmapi.net/team` as the key. The model text, the contract +and the portal types are regenerated consistently (the committed-contract test passes; `api-types.mjs --check` passes). +I only wrapped the two source lines; the strings are the same. + +## What reviewer 1 missed + +### R2-1 (High, introduced by the PR): the pods' use is read on every change, and CI's service job fails + +**Where.** PR head `cmapi/src/cmapi/core/pipeline.py:474-475` and `:933` call `quota_used` for every change of an existing +namespace; `:976` unpacks `cache.kind_stale(kind)`. + +**Scenario.** A label change, a Make permanent, a raise: none can lower a bound, yet each reads the Namespace and +ResourceQuota watch state. Three effects: (1) CI: `tests/service/test_review_479_expiry.py`, whose cluster is a stand-in, +fails twice (`TypeError: cannot unpack non-iterable Mock object`), so the PR cannot merge; (2) on a cluster whose watch is +stale or refused, every label change logs `quota_used_unknown`, which says that a use could not be judged when no use was +needed; (3) work on the plan path of each change for nothing. After Q1 the use only ever matters for a lowered key, so +the read belongs behind that condition. Fixing the two tests' stand-in instead would have left (2) and (3). + +**Fix** (in `final.diff`). `TierCatalog.lowered` names the sizable bounds that a change lowers; `compare` judges exactly +those keys, and the pipeline reads the use only when there is one. + +`cmapi/src/cmapi/core/tiers.py`: + +```python +def _long_name(key: str) -> str: + """`requests.cpu` for `cpu` and `requests.memory` for `memory`: the name that binding_hard folds the short one into.""" + return REQUEST_KEYS[key][0] if key in REQUEST_KEYS else key +``` + +```python + def lowered(self, current_hard: Mapping[str, str], new_hard: Mapping[str, str]) -> list[str]: + """The sizable keys whose bound a change lowers: the new quota holds the key, with a smaller value than Git's. A + short name (`cpu`, `memory`) is read with its long one, the smaller of the two (binding_hard). A change that + removes a bound, keeps it or raises it lowers nothing. Only a lowered key can newly fall below what the pods + request, so only a change with one reads their use (Pipeline.quota_used).""" + old, new = binding_hard(current_hard), binding_hard(new_hard) + return [k for k in self.sizable + if (key := _long_name(k)) in new and qty(new[key]) < qty(old.get(key, "0"))] +``` + +and in `compare`, `lowered = self.lowered(current_hard, new_hard)` before the loop, `key = _long_name(k)`, and +`if k not in lowered: continue` in place of reviewer 1's `if key not in new_hard or new >= old: continue`. + +`cmapi/src/cmapi/core/pipeline.py`, used by `_plan_namespace` and `restore_facts` in place of `self.quota_used(...)`: + +```python + def _use_if_lowered(self, cluster_id: str, ns: str, quota: Mapping[str, Any] | None, old_hard: Mapping[str, str], + hard: Mapping[str, str]) -> dict[str, str] | None: + """quota_used for a change that lowers a sizable bound, None for any other: a change of a label, a raise or a quota + kept as it is cannot fall below the use, so it reads no watch and logs no quota_used_unknown (TierCatalog.lowered).""" + return self.quota_used(cluster_id, ns, quota) if self.cfg.tiers.lowered(old_hard, hard) else None +``` + +**Tests.** Before: `tests/service/test_review_479_expiry.py` 2 failed, 7 passed (CI on the head; here on `head/` plus +`codex-fix.diff`). After: 9 passed. New: `test_a_change_that_lowers_no_bound_does_not_read_the_pods_use` (a label change, a +raise) and `test_a_change_that_lowers_a_bound_reads_the_pods_use_once` (use 0, use above the target, unknown) in +`tests/service/test_review_771.py`; `test_lowered_names_the_sizable_bounds_that_a_change_lowers` (6 cases) in +`tests/core/test_quota_below_requested_256.py`. + +### R2-2 (Low, docs): docs/16 still says `change_requests.team` is `cmapi.net/team` + +`docs/16-data-model.md:104`: "The value of the label `cmapi.net/team` at plan time." The PR changed docs/02, docs/18 and +the glossary and left this row. Fixed in `final.diff` ("the label that metadata-keys.yaml names in `teamKey`, +`cmapi.net/team` by default (#258)"). No test: a sentence. + +### R2-3 (process, no code): reviewer 1's export was edited in place + +See "Read this first", 1. A reviewer that follows the brief's step 1 literally on this folder un-applies reviewer 1's fix +(BSD `patch` assumes `-R` without a terminal) and reviews the bare head as if it were the fixed tree. For the next review: +give each reviewer its own copy, or keep a read-only `head/` beside the working export. + +### Not defects, said so the coordinator need not find them again + +- docs/02:1953 says "Deletes are never auto-approved", which docs/01:563 and the `expired-namespace` policy contradict. It + predates the PR and T1 does not change it. One sentence for a records PR. +- `usage == "unavailable"` (#310) overrides `add: 0`; `beyondTier` and now `quotaBelowRequested` honour it. See the note + in `r2-outputs/issue-texts.md`. +- Reviewer 1's residual risk stands and is acceptable: within the watch's 30-minute window `status.used` can lag, and + submit does not read it again. A wrong low reading can auto-approve a decrease where a policy matches; the result is + pods refused at admission in that namespace, not a capacity or security breach. + +## Tests + +Trees: `head/` is `git archive cff8b36c`; `r2/` is `head/` plus `codex-fix.diff`; `verify/` is a fresh `head/` plus +`final.diff` (`patch -p1 -F0`, clean, and identical to my working tree `final/`); `before/` is `head/` with only the new +and changed test files of `final.diff`. One file at a time, load checked before each (`r2-outputs/run.sh` waits while the +1-minute load is 16 or more; the CRC VM held it above 16 for long stretches). PostgreSQL 16 on 127.0.0.1:55432, database +`cmapi_r771` (created). Never the full suite. Raw output: `r2-outputs/*.txt`. + +Commands, from `/cmapi/`: + +```sh +# service +CMAPI_TEST_DATABASE_URL=postgresql://cmapi:cmapi@127.0.0.1:55432/cmapi_r771 PYTHONPATH=src:tests/service \ + /Users/olasumbo/gitRepos/workbench/cmapi/wt-655-outputs/venv-merged/bin/python -m pytest -q -W ignore -p no:cacheprovider +# core +PYTHONPATH=src:tests/core /Users/olasumbo/gitRepos/workbench/cmapi/venv-ref/bin/python -m pytest -q -W ignore -p no:cacheprovider +``` + +**After: `verify/` (a fresh PR head plus `final.diff`), `r2-outputs/stage2-final-on-fresh-copy.txt`. All pass: 319 tests in 17 runs.** + +| File | Result | +|---|---| +| `tests/core/test_quota_below_requested_256.py` | 27 passed | +| `tests/core/test_team_key_258.py` | 17 passed | +| `tests/core/test_approvals.py` | 36 passed | +| `tests/core/test_metadata_form_336.py` (the company fixture equals `keys_view()`) | 11 passed | +| `tests/core/test_metadata_schema_328.py` | 46 passed | +| `tests/service/test_review_771.py` | 12 passed | +| `tests/service/test_review_479_expiry.py` (CI's 2 failures) | 9 passed | +| `tests/service/test_team_key_258.py` (PostgreSQL; reviewer 1 could not run it) | 1 passed | +| `tests/service/test_quota_below_requested_256.py` | 5 passed | +| `tests/service/test_helm_metadata_values.py` | 83 passed | +| `tests/service/test_openapi_render_337.py` | 8 passed | +| `tests/service/test_api_docs.py::test_the_committed_contract_is_the_document_this_code_serves` | 1 passed | +| `tests/service/test_expire_check_263.py` (T1, with the new PostgreSQL test) | 24 passed | +| `tests/service/test_revert_inverse_policy.py` | 10 passed | +| `tests/service/test_metadata_company_358_api.py` | 12 passed | +| `tests/service/test_revert_sizing.py` | 9 passed | +| `tests/service/test_catalog_drift_710.py` | 8 passed | + +**Before: `before/` (PR head production code, the new and changed tests), `r2-outputs/stage3-new-tests-on-pr-head-code.txt`.** + +| File | Result on the PR head's code | Which fail | +|---|---|---| +| `tests/core/test_quota_below_requested_256.py` | 13 failed, 14 passed | Q1 (3), Q4 silent file (2), Q2 (2), R2-1 `lowered` (6) | +| `tests/core/test_team_key_258.py` | 1 failed, 16 passed | T3: no `x-cmapi-team-key` | +| `tests/service/test_review_771.py` | 7 failed, 5 passed | Q3 (2), T1 (1), T4 (2), R2-1 no read for a label change or a raise (2) | +| `tests/service/test_review_479_expiry.py` | 2 failed, 7 passed | R2-1, as CI | +| `tests/service/test_expire_check_263.py::test_the_expiry_delete_counts_against_the_teams_daily_allowance` | 1 failed | T1, through PostgreSQL | + +The 5 that pass before in `test_review_771.py` are reviewer 1's two pins of what the PR gets right and the three cases of +`test_a_change_that_lowers_a_bound_reads_the_pods_use_once`, which hold the read that the head also makes. + +**Reviewer 1's tree as given (`r2/`), `r2-outputs/stage1-codex-as-given.txt`:** core 14, 17 and 36 passed; service +`test_review_771.py` 8, `test_team_key_258.py` 1, `test_quota_below_requested_256.py` 5, `test_helm_metadata_values.py` 83, +`test_openapi_render_337.py` 8, the committed contract 1, `test_expire_check_263.py` 23, `test_revert_inverse_policy.py` 10, +all passed. `test_review_479_expiry.py`: 2 failed, 7 passed (`before-ci-479-on-codex-tree.txt`). + +**Portal, Node only, in `verify/cmapi-portal-ui/`:** `node scripts/api-types.mjs --check` ok; `node tests/contract.test.mjs` +ok (3 lines, the new one included); `node tests/api/standin.test.mjs` 7 passed; `node scripts/check-discipline.mjs` ok. +Before, on the head's code: `contract.test.mjs` fails (the form does not know `x-cmapi-team-key`). **Not run:** `tsc`, +`vite build`, `direct.test.mjs`, `portal.test.mjs`, `behaviour.test.mjs`, `parity.test.mjs`, `mockup-pagination.test.mjs`. + +**Docs checks, on `final/` with a scratch Git index:** `scripts/doc-citations.py --check` 0 problems after `--relocate` +moved 8 citations (`approvals.py` and `pipeline.py:866` shifted); `scripts/api-examples-doc.py --check` exit 0. + +**Not tested:** the full service suite (CI is the gate; the head's CI failed only on the 2 tests above), Spectral, kind, +CRC, and a real quota controller's `status.used`. + +## Files + +- `final.diff`: one unified diff against the PR head `cff8b36c` (24 files). Apply: `patch -p1 -F0 < final.diff` in a + checkout of the PR branch, or `git apply final.diff`. +- `r2-outputs/issue-texts.md`: the two issue texts (T2; the portal's derived or optional team label) and the #310 note. +- `r2-outputs/*.txt`: the test runs. `r2-outputs/run.sh`: the runner. `r2-outputs/mkdiff.sh`: how `final.diff` was made. +- Trees left in the folder: `head/`, `r2/`, `final/`, `verify/`, `before/`. `export/` is untouched. + +Who wrote what in `final.diff`: reviewer 1 (Codex) wrote Q1, Q2, Q3, T1's line, T4, the API key and `MetaForm.teamKey` of +T3, and their tests; reviewer 2 (Fable 5.2) wrote the Q4 block and its tests, `TierCatalog.lowered`, +`Pipeline._use_if_lowered` and their tests, `teamFieldOf` and the Node test, the PostgreSQL test of T1, and the docs lines +for Q4, T1, T3 and docs/16. + +## Addendum: the coordinator's amendment to R2-1 (a first bound is a lowering) + +The coordinator found a gap in my `TierCatalog.lowered`: a key that Git's quota does not bound was read as 0, so a change +that gives it its first bound (an adopted quota without `requests.cpu`, moved to a tier) was not lowered and never read +the use. No bound is no limit. `lowered` now also names a key that the new quota holds and Git's does not: + +```python + old, new = binding_hard(current_hard), binding_hard(new_hard) + return [k for k in self.sizable + if (key := _long_name(k)) in new and (key not in old or qty(new[key]) < qty(old[key]))] +``` + +`compare`'s delta and percent are unchanged (an absent key still counts as 0 there). docs/18's fact row says it. + +One consequence to know: a live ResourceQuota reports `status.used` only for the keys it bounds, so the use of a newly +bounded key is normally unknown, and such a change then counts as below (fail closed) and gets the approver. That covers +an existing namespace's first quota too (Git holds none: `quota_used` answers unknown). A known use is reached only when +the live quota already bounds the key and Git's does not. + +Tests added: core `test_lowered_names_the_sizable_bounds_that_a_change_lowers` (the first-quota case corrected, two +adopted-quota cases added) and `test_a_first_bound_on_a_key_that_git_left_unbounded_is_judged_against_the_use` (use above, +use within, use not reported, unknown); service `test_an_unbounded_quota_moved_to_a_tier_reads_the_pods_use` (4 cases, +through `plan_namespace` with stand-ins). + +After, on `verify-b/` (a fresh PR head plus the rewritten `final.diff`; `r2-outputs/stage4-amended-on-fresh-copy.txt`): +core `test_quota_below_requested_256.py` 33 passed; service `test_review_771.py` 16, `test_review_479_expiry.py` 9, +`test_catalog_drift_710.py` 8, `test_revert_sizing.py` 9, `test_quota_below_requested_256.py` 5, all passed. +Before, on `prev-b/` (the same tree with the earlier condition in `lowered`; `stage5-new-tests-on-previous-lowered.txt`): +core 6 failed, 27 passed; `test_review_771.py` 4 failed, 12 passed. + +The other 11 files of the first run were not run again: the amendment changes one condition in `tiers.py`, tests and a +docs sentence. The counts above replace those of the same files in the tables. `verify/` and `verify2/` are the earlier +trees; a built-in safety check refused my `rm -rf` of scratch trees in a compound command, so they stay for you to delete. From 9b3464931e34cff407638feaea4d5c798cbebfb3 Mon Sep 17 00:00:00 2001 From: ephico2real2 Date: Tue, 1 Dec 2026 12:10:06 -0600 Subject: [PATCH 3/3] #256: a first quota lowers nothing (retracts the coordinator's amendment for that case; docs/01, #710) Reviewer 2 (Fable) amend2.diff, applied by the coordinator. --- cmapi/src/cmapi/core/tiers.py | 8 +++- .../core/test_quota_below_requested_256.py | 3 +- docs/18-configuration.md | 2 +- .../2026-12-01-issue-256-258/README.md | 2 + .../2026-12-01-issue-256-258/amend2.diff | 47 +++++++++++++++++++ 5 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 docs/reviews/2026-12-01-issue-256-258/amend2.diff diff --git a/cmapi/src/cmapi/core/tiers.py b/cmapi/src/cmapi/core/tiers.py index b6d6f686..cd03a76a 100644 --- a/cmapi/src/cmapi/core/tiers.py +++ b/cmapi/src/cmapi/core/tiers.py @@ -741,8 +741,14 @@ def lowered(self, current_hard: Mapping[str, str], new_hard: Mapping[str, str]) adopted quota without requests.cpu, moved to a tier). A short name (`cpu`, `memory`) is read with its long one, the smaller of the two (binding_hard). A change that removes a bound, keeps it or raises it lowers nothing. Only a lowered key can newly fall below what the pods request, so only a change with one reads their use - (Pipeline.quota_used). This is for the use alone: compare's delta and percent still count an absent key as 0.""" + (Pipeline.quota_used). This is for the use alone: compare's delta and percent still count an absent key as 0. + + A first quota lowers nothing: when Git bounds no sizable key at all, the change sets the namespace's first quota, + which reads no usage and adds no approver (docs/01, "Thanos on onboarding": "Never queried while creating a + namespace or setting its first quota"; the #710 review, tests/service/test_first_quota_usage.py).""" old, new = binding_hard(current_hard), binding_hard(new_hard) + if not any(_long_name(k) in old for k in self.sizable): + return [] return [k for k in self.sizable if (key := _long_name(k)) in new and (key not in old or qty(new[key]) < qty(old[key]))] diff --git a/cmapi/tests/core/test_quota_below_requested_256.py b/cmapi/tests/core/test_quota_below_requested_256.py index 03490dfe..e5ded062 100644 --- a/cmapi/tests/core/test_quota_below_requested_256.py +++ b/cmapi/tests/core/test_quota_below_requested_256.py @@ -123,7 +123,8 @@ def test_tighter_alias_in_the_target_is_a_decrease(cat, key, short, old, tighter ({"requests.cpu": "2", "pods": "20"}, {"requests.cpu": "1", "pods": "20"}, ["requests.cpu"]), ({"requests.cpu": "2", "pods": "20"}, {"requests.cpu": "2", "pods": "30"}, []), # kept and raised ({"requests.cpu": "2", "pods": "20"}, {"pods": "20"}, []), # a bound removed - ({}, {"requests.cpu": "1", "pods": "20"}, ["requests.cpu", "pods"]), # no bound in Git is no limit + ({}, {"requests.cpu": "1", "pods": "20"}, []), # a first quota (docs/01, #710) + ({"services.nodeports": "0"}, {"requests.cpu": "1", "pods": "20"}, []), # ... beside a quota of other keys ({"pods": "20"}, {"requests.cpu": "1", "pods": "20"}, ["requests.cpu"]), # an adopted quota gains a bound ({"pods": "20"}, {"cpu": "1", "pods": "20"}, ["requests.cpu"]), # ... by its short name ({"requests.memory": "4Gi"}, {"requests.memory": "4Gi", "memory": "1Gi"}, ["requests.memory"]), # a tighter short name diff --git a/docs/18-configuration.md b/docs/18-configuration.md index fbf0c547..c855cdde 100644 --- a/docs/18-configuration.md +++ b/docs/18-configuration.md @@ -804,7 +804,7 @@ A `when` line reads these facts. The names are fixed in the code. An unknown nam | `plugin`, `action`, `environment`, `namespace`, `clusterId`, `reason`, `team`, `tier` | The request | `core/pipeline.py` | | `tierChange` | `up`, `down`, `same`, `to-custom`, `from-custom` or `custom`. Set for a change of an existing namespace only | `TierCatalog.compare` | | `quotaIncreasePct` | The largest increase of a sizable key, in percent. Set for a change of an existing namespace only | `QuotaChange.quota_increase_pct` | -| `quotaBelowRequested` | On a change of an existing namespace's quota (a plan, or a revert): the change lowers a sizable key's hard value below what the pods request now, so Kubernetes would refuse new pods (#256). The use is the `status.used` of the live ResourceQuota that Git's quota is, from the cluster's watch cache. A key that the change lowers and whose use cannot be read counts as below (fail closed): the watch has not listed, is stale (no good read for 30 minutes) or is refused (401, 403), or the live namespace has no matching unscoped quota or usable value for that key. A namespace that the watch does not hold has no pods. A key that Git's quota does not bound has no limit, so its first bound lowers it: an adopted quota without `requests.cpu`, moved to a tier. Its use is rarely readable, since a live quota reports `status.used` only for the keys it bounds, so such a change usually counts as below. Removing a bound or keeping or raising its value does not trigger this fact. The shipped rule adds one approver of `defaults.group` (approver-platform). When no true threshold reads the fact, cmapi adds that approver itself, with the reason "Quota below what pods request": the fact was always false before #256, so a file without the rule never answered it, and docs/01 says "A decrease below what pods already request is refused unless approver-platform approve". A rule that reads the fact is the site's answer and stands, with its group and its count, also `add: 0`, and also for a use that could not be read (`test_a_rule_that_reads_the_fact_is_the_sites_answer`, `cmapi/tests/core/test_quota_below_requested_256.py`). The use is read only for a change that lowers a sizable bound: a label change or a raise reads no watch. The planner logs `quota_used_unknown` when it cannot use the quota object | `Pipeline.quota_used`, `TierCatalog.lowered`, `TierCatalog.compare` | +| `quotaBelowRequested` | On a change of an existing namespace's quota (a plan, or a revert): the change lowers a sizable key's hard value below what the pods request now, so Kubernetes would refuse new pods (#256). The use is the `status.used` of the live ResourceQuota that Git's quota is, from the cluster's watch cache. A key that the change lowers and whose use cannot be read counts as below (fail closed): the watch has not listed, is stale (no good read for 30 minutes) or is refused (401, 403), or the live namespace has no matching unscoped quota or usable value for that key. A namespace that the watch does not hold has no pods. A key that Git's quota does not bound has no limit, so its first bound lowers it: an adopted quota that bounds pods and not `requests.cpu`, moved to a tier. A first quota is not such a change: when Git bounds no sizable key at all, nothing is lowered and no use is read (docs/01, "Never queried while creating a namespace or setting its first quota", #710). Its use is rarely readable, since a live quota reports `status.used` only for the keys it bounds, so such a change usually counts as below. Removing a bound or keeping or raising its value does not trigger this fact. The shipped rule adds one approver of `defaults.group` (approver-platform). When no true threshold reads the fact, cmapi adds that approver itself, with the reason "Quota below what pods request": the fact was always false before #256, so a file without the rule never answered it, and docs/01 says "A decrease below what pods already request is refused unless approver-platform approve". A rule that reads the fact is the site's answer and stands, with its group and its count, also `add: 0`, and also for a use that could not be read (`test_a_rule_that_reads_the_fact_is_the_sites_answer`, `cmapi/tests/core/test_quota_below_requested_256.py`). The use is read only for a change that lowers a sizable bound: a label change or a raise reads no watch. The planner logs `quota_used_unknown` when it cannot use the quota object | `Pipeline.quota_used`, `TierCatalog.lowered`, `TierCatalog.compare` | | `requestToPeakRatio` | On a change of an existing namespace's quota, with `usage` `ok`: the largest planned hard limit over the namespace's 14-day peak, of a resource the change raises (#310). Absent otherwise, so a rule that reads it adds nothing | `plan_usage`, `capacity/usage.py` | | `usage` | On a change of an existing namespace's quota: `ok`, `insufficient-data` (no usage source, or under 80% of the window's samples) or `unavailable` (Thanos did not answer, or the cluster's import check found the reader without its own Thanos grants, #724). The shipped rule adds approver-platform on `usage == "unavailable"`. If the active policy has no matching usage threshold that adds that group, the planner supplies one platform slot (#310) | `plan_usage`, `capacity/usage.py` | | `capacity`, `capacityFresh` | `fits`, `warn`, `exceeded` or `unknown`, and whether the data is fresh. `unknown`, not fresh, when the cluster has neither `simulatedCapacity` nor fresh counted node allocatable, no watch cache, ResourceQuotas not listed yet, ResourceQuota reads refused (401 or 403), or a ResourceQuota watch with no good read for 30 minutes (#393). What is committed comes from the cluster's quota ledger: per namespace the smallest unscoped managed quota, scoped quotas left out (#302). The check adds the capacity that open requests hold (`capacity_reservations`, #62): each request with an increase holds it from submit until it leaves the holding states, and a hold stops counting once the ledger shows its quota. Submit checks again under the cluster's lock and takes the hold in the same transaction, so a request that fit when planned but not beside a hold taken since is refused (`exceeded`) or decided on the new answer; the last `:approve` and a `:retry` from `failed` check again and answer 422 `capacity-exceeded` when the request no longer fits | `core/capacity_backend.py`, `core/capacity_ledger.py` | diff --git a/docs/reviews/2026-12-01-issue-256-258/README.md b/docs/reviews/2026-12-01-issue-256-258/README.md index 6930da62..3aa8034f 100644 --- a/docs/reviews/2026-12-01-issue-256-258/README.md +++ b/docs/reviews/2026-12-01-issue-256-258/README.md @@ -21,3 +21,5 @@ Tests, one file at a time on the Mac: - After: core `test_quota_below_requested_256` 33 passed (the coordinator re-ran it), `test_review_771` 16, `test_review_479_expiry` 9, `test_catalog_drift_710` 8, `test_revert_sizing` 9, service `test_quota_below_requested_256` 5. The first round also passed `test_expire_check_263` (24), the metadata and approvals files and the Node-only portal checks. - Before: core quota 13 failed, `test_review_771` 7 failed, `test_review_479_expiry` 2 failed. - Not run: the portal browser suites (no node_modules locally), CRC and kind. CI is the gate. + +**After the merge attempt: a retraction.** CI failed `test_first_quota_usage.py::test_the_first_quota_reads_no_live_usage`. That test is the #710 review's decision: a namespace's first quota reads no usage and adds no approver (docs/01, "Thanos on onboarding": "Never queried while creating a namespace or setting its first quota"). The coordinator's amendment, "a key Git did not bound counts as lowered", reopened that decided design, and the coordinator retracts it for the first quota. Reviewer 2's [amend2.diff](amend2.diff) narrows it: when Git bounds no sizable key at all, nothing is lowered. A Git quota that bounds some sizable keys still has its newly bounded key judged against the use. Results: `test_first_quota_usage.py` 2 passed (the coordinator re-ran it; it was 1 failed before), core quota 34, `test_review_771` 16, `test_review_479_expiry` 9. diff --git a/docs/reviews/2026-12-01-issue-256-258/amend2.diff b/docs/reviews/2026-12-01-issue-256-258/amend2.diff new file mode 100644 index 00000000..e8629167 --- /dev/null +++ b/docs/reviews/2026-12-01-issue-256-258/amend2.diff @@ -0,0 +1,47 @@ +diff --git a/cmapi/src/cmapi/core/tiers.py b/cmapi/src/cmapi/core/tiers.py +index b6d6f68..cd03a76 100644 +--- a/cmapi/src/cmapi/core/tiers.py ++++ b/cmapi/src/cmapi/core/tiers.py +@@ -741,8 +741,14 @@ class TierCatalog: + adopted quota without requests.cpu, moved to a tier). A short name (`cpu`, `memory`) is read with its long one, + the smaller of the two (binding_hard). A change that removes a bound, keeps it or raises it lowers nothing. Only + a lowered key can newly fall below what the pods request, so only a change with one reads their use +- (Pipeline.quota_used). This is for the use alone: compare's delta and percent still count an absent key as 0.""" ++ (Pipeline.quota_used). This is for the use alone: compare's delta and percent still count an absent key as 0. ++ ++ A first quota lowers nothing: when Git bounds no sizable key at all, the change sets the namespace's first quota, ++ which reads no usage and adds no approver (docs/01, "Thanos on onboarding": "Never queried while creating a ++ namespace or setting its first quota"; the #710 review, tests/service/test_first_quota_usage.py).""" + old, new = binding_hard(current_hard), binding_hard(new_hard) ++ if not any(_long_name(k) in old for k in self.sizable): ++ return [] + return [k for k in self.sizable + if (key := _long_name(k)) in new and (key not in old or qty(new[key]) < qty(old[key]))] + +diff --git a/cmapi/tests/core/test_quota_below_requested_256.py b/cmapi/tests/core/test_quota_below_requested_256.py +index 03490df..e5ded06 100644 +--- a/cmapi/tests/core/test_quota_below_requested_256.py ++++ b/cmapi/tests/core/test_quota_below_requested_256.py +@@ -123,7 +123,8 @@ def test_tighter_alias_in_the_target_is_a_decrease(cat, key, short, old, tighter + ({"requests.cpu": "2", "pods": "20"}, {"requests.cpu": "1", "pods": "20"}, ["requests.cpu"]), + ({"requests.cpu": "2", "pods": "20"}, {"requests.cpu": "2", "pods": "30"}, []), # kept and raised + ({"requests.cpu": "2", "pods": "20"}, {"pods": "20"}, []), # a bound removed +- ({}, {"requests.cpu": "1", "pods": "20"}, ["requests.cpu", "pods"]), # no bound in Git is no limit ++ ({}, {"requests.cpu": "1", "pods": "20"}, []), # a first quota (docs/01, #710) ++ ({"services.nodeports": "0"}, {"requests.cpu": "1", "pods": "20"}, []), # ... beside a quota of other keys + ({"pods": "20"}, {"requests.cpu": "1", "pods": "20"}, ["requests.cpu"]), # an adopted quota gains a bound + ({"pods": "20"}, {"cpu": "1", "pods": "20"}, ["requests.cpu"]), # ... by its short name + ({"requests.memory": "4Gi"}, {"requests.memory": "4Gi", "memory": "1Gi"}, ["requests.memory"]), # a tighter short name +diff --git a/docs/18-configuration.md b/docs/18-configuration.md +index fbf0c54..c855cdd 100644 +--- a/docs/18-configuration.md ++++ b/docs/18-configuration.md +@@ -804,7 +804,7 @@ A `when` line reads these facts. The names are fixed in the code. An unknown nam + | `plugin`, `action`, `environment`, `namespace`, `clusterId`, `reason`, `team`, `tier` | The request | `core/pipeline.py` | + | `tierChange` | `up`, `down`, `same`, `to-custom`, `from-custom` or `custom`. Set for a change of an existing namespace only | `TierCatalog.compare` | + | `quotaIncreasePct` | The largest increase of a sizable key, in percent. Set for a change of an existing namespace only | `QuotaChange.quota_increase_pct` | +-| `quotaBelowRequested` | On a change of an existing namespace's quota (a plan, or a revert): the change lowers a sizable key's hard value below what the pods request now, so Kubernetes would refuse new pods (#256). The use is the `status.used` of the live ResourceQuota that Git's quota is, from the cluster's watch cache. A key that the change lowers and whose use cannot be read counts as below (fail closed): the watch has not listed, is stale (no good read for 30 minutes) or is refused (401, 403), or the live namespace has no matching unscoped quota or usable value for that key. A namespace that the watch does not hold has no pods. A key that Git's quota does not bound has no limit, so its first bound lowers it: an adopted quota without `requests.cpu`, moved to a tier. Its use is rarely readable, since a live quota reports `status.used` only for the keys it bounds, so such a change usually counts as below. Removing a bound or keeping or raising its value does not trigger this fact. The shipped rule adds one approver of `defaults.group` (approver-platform). When no true threshold reads the fact, cmapi adds that approver itself, with the reason "Quota below what pods request": the fact was always false before #256, so a file without the rule never answered it, and docs/01 says "A decrease below what pods already request is refused unless approver-platform approve". A rule that reads the fact is the site's answer and stands, with its group and its count, also `add: 0`, and also for a use that could not be read (`test_a_rule_that_reads_the_fact_is_the_sites_answer`, `cmapi/tests/core/test_quota_below_requested_256.py`). The use is read only for a change that lowers a sizable bound: a label change or a raise reads no watch. The planner logs `quota_used_unknown` when it cannot use the quota object | `Pipeline.quota_used`, `TierCatalog.lowered`, `TierCatalog.compare` | ++| `quotaBelowRequested` | On a change of an existing namespace's quota (a plan, or a revert): the change lowers a sizable key's hard value below what the pods request now, so Kubernetes would refuse new pods (#256). The use is the `status.used` of the live ResourceQuota that Git's quota is, from the cluster's watch cache. A key that the change lowers and whose use cannot be read counts as below (fail closed): the watch has not listed, is stale (no good read for 30 minutes) or is refused (401, 403), or the live namespace has no matching unscoped quota or usable value for that key. A namespace that the watch does not hold has no pods. A key that Git's quota does not bound has no limit, so its first bound lowers it: an adopted quota that bounds pods and not `requests.cpu`, moved to a tier. A first quota is not such a change: when Git bounds no sizable key at all, nothing is lowered and no use is read (docs/01, "Never queried while creating a namespace or setting its first quota", #710). Its use is rarely readable, since a live quota reports `status.used` only for the keys it bounds, so such a change usually counts as below. Removing a bound or keeping or raising its value does not trigger this fact. The shipped rule adds one approver of `defaults.group` (approver-platform). When no true threshold reads the fact, cmapi adds that approver itself, with the reason "Quota below what pods request": the fact was always false before #256, so a file without the rule never answered it, and docs/01 says "A decrease below what pods already request is refused unless approver-platform approve". A rule that reads the fact is the site's answer and stands, with its group and its count, also `add: 0`, and also for a use that could not be read (`test_a_rule_that_reads_the_fact_is_the_sites_answer`, `cmapi/tests/core/test_quota_below_requested_256.py`). The use is read only for a change that lowers a sizable bound: a label change or a raise reads no watch. The planner logs `quota_used_unknown` when it cannot use the quota object | `Pipeline.quota_used`, `TierCatalog.lowered`, `TierCatalog.compare` | + | `requestToPeakRatio` | On a change of an existing namespace's quota, with `usage` `ok`: the largest planned hard limit over the namespace's 14-day peak, of a resource the change raises (#310). Absent otherwise, so a rule that reads it adds nothing | `plan_usage`, `capacity/usage.py` | + | `usage` | On a change of an existing namespace's quota: `ok`, `insufficient-data` (no usage source, or under 80% of the window's samples) or `unavailable` (Thanos did not answer, or the cluster's import check found the reader without its own Thanos grants, #724). The shipped rule adds approver-platform on `usage == "unavailable"`. If the active policy has no matching usage threshold that adds that group, the planner supplies one platform slot (#310) | `plan_usage`, `capacity/usage.py` | + | `capacity`, `capacityFresh` | `fits`, `warn`, `exceeded` or `unknown`, and whether the data is fresh. `unknown`, not fresh, when the cluster has neither `simulatedCapacity` nor fresh counted node allocatable, no watch cache, ResourceQuotas not listed yet, ResourceQuota reads refused (401 or 403), or a ResourceQuota watch with no good read for 30 minutes (#393). What is committed comes from the cluster's quota ledger: per namespace the smallest unscoped managed quota, scoped quotas left out (#302). The check adds the capacity that open requests hold (`capacity_reservations`, #62): each request with an increase holds it from submit until it leaves the holding states, and a hold stops counting once the ledger shows its quota. Submit checks again under the cluster's lock and takes the hold in the same transaction, so a request that fit when planned but not beside a hold taken since is refused (`exceeded`) or decided on the new answer; the last `:approve` and a `:retry` from `failed` check again and answer 422 `capacity-exceeded` when the request no longer fits | `core/capacity_backend.py`, `core/capacity_ledger.py` |