From db63186bf7c4a124f7e3c105c9696abd71bb432b Mon Sep 17 00:00:00 2001 From: ephico2real2 Date: Tue, 1 Dec 2026 15:59:23 -0600 Subject: [PATCH 1/2] #763: cluster-onboard's preflight checks the Thanos retention and the root Application docs/02, "Onboarding becomes shorter", step 2: "the Thanos Route answers, retention is at least 15 days, and the root Application exists and is Synced". After the import's checks, preflight now reads the platform Prometheus's gauge prometheus_tsdb_retention_limit_seconds of job prometheus-k8s in openshift-monitoring through the usage path's ThanosQuerier (capacity/retention.py; the shortest replica counts, 0 is no time limit, under 15 days or unreadable is a finding), and the root Application of delivery.argocd with ArgoCdSignal (only status.sync.status Synced passes; missing, forbidden or unreadable is a finding). Each check passes, is a finding, or is not applicable with its reason: retention when usage.source is none, the root Application in apply mode, in gitops mode without delivery.signal argocd, or with a per-namespace name template. notChecked is gone. Tests: test_onboard_preflight_763.py (19; 14 fail with main's preflight); test_operations_26's onboarding test asserts notApplicable. Docs: docs/02 as built, docs/21 (the new reads, citations recorded), the template comment, and the decisions with their sources in docs/reviews/2026-12-01-issue-763/README.md. Written by Opus 5.5 (high), the implementer. --- cmapi/src/cmapi/capacity/retention.py | 46 ++++ cmapi/src/cmapi/ops/__init__.py | 98 ++++++- .../cmapi/ops/templates/cluster-onboard.yaml | 3 +- .../service/test_onboard_preflight_763.py | 240 ++++++++++++++++++ cmapi/tests/service/test_operations_26.py | 5 +- docs/02-technical-design-v2.md | 2 +- docs/21-usage-from-thanos.md | 10 +- docs/citations.lock.json | 49 ++++ docs/reviews/2026-12-01-issue-763/README.md | 165 ++++++++++++ 9 files changed, 606 insertions(+), 12 deletions(-) create mode 100644 cmapi/src/cmapi/capacity/retention.py create mode 100644 cmapi/tests/service/test_onboard_preflight_763.py create mode 100644 docs/reviews/2026-12-01-issue-763/README.md diff --git a/cmapi/src/cmapi/capacity/retention.py b/cmapi/src/cmapi/capacity/retention.py new file mode 100644 index 00000000..f98f7ea7 --- /dev/null +++ b/cmapi/src/cmapi/capacity/retention.py @@ -0,0 +1,46 @@ +"""How long a cluster's platform Prometheus keeps its samples, read through the cluster's Thanos Querier (#763). + +docs/02, "Onboarding becomes shorter", step 2: "preflight: the Thanos Route answers, retention is at least 15 days". docs/02, +"Retention limit": "Platform Prometheus keeps 15 days by default, and the in-cluster Thanos Querier has no long-term store +behind it, so any window over 14 days silently returns less data." The 14-day window of usage.py (WINDOW_DAYS) is the reason. + +The value is Prometheus's own gauge, read with the same query, the same Route and the same reader grants as the usage reads +(thanos.py): prometheus/tsdb/db.go, `prometheus_tsdb_retention_limit_seconds`, "How long to retain samples in storage", set +from the time retention (openshift/prometheus release-4.18, Prometheus 2.55.1, tsdb/db.go). 0 is no time limit: +`BeyondTimeRetention` returns at once when "Time retention is disabled" (`db.opts.RetentionDuration == 0`), which is how +Prometheus runs when only a size limit is set (cmd/prometheus/main.go applies the 15d default only when "neither this flag nor +storage.tsdb.retention.size is set"). + +Only the platform Prometheus counts: the series of job prometheus-k8s in openshift-monitoring (cluster-monitoring-operator +release-4.18, assets/prometheus-k8s/service-monitor.yaml and service.yaml; prometheus-operator sets `job` from the Service's +name). The Querier also answers the same gauge for the user-workload Prometheus and the Thanos Ruler, whose 24-hour default +says nothing of the platform metrics usage reads (measured on CRC 4.22.14, 2026-12-01: prometheus-k8s 1296000, the +user-workload Prometheus and Thanos Ruler 86400). The sources and the decisions: docs/reviews/2026-12-01-issue-763/README.md. +""" +from __future__ import annotations + +import math + +from cmapi.capacity.usage import MetricsUnavailable, sample +from cmapi.core.ports import MetricsSource + +# docs/02, "Onboarding becomes shorter", step 2. No configuration names another value, so it is a constant (#763). +MIN_RETENTION_DAYS = 15 +RETENTION_QUERY = 'prometheus_tsdb_retention_limit_seconds{namespace="openshift-monitoring", job="prometheus-k8s"}' + + +def platform_retention_seconds(metrics: MetricsSource, cluster_id: str) -> float: + """The shortest time retention of the cluster's platform Prometheus replicas, in seconds, or math.inf when none has a time + limit. MetricsUnavailable when it cannot be read: the query fails, no replica reports the gauge, or a value is not a + number of seconds. Never a default: a retention that is not read is not assumed.""" + series = metrics.query(cluster_id, RETENTION_QUERY) + if not series: + raise MetricsUnavailable(f"{cluster_id}: the Thanos Querier has no prometheus_tsdb_retention_limit_seconds of " + "job prometheus-k8s in openshift-monitoring") + seconds: list[float] = [] + for s in series: + v = sample(s) + if v is None or v < 0: + raise MetricsUnavailable(f"{cluster_id}: a prometheus_tsdb_retention_limit_seconds that is not a number of seconds") + seconds.append(math.inf if v == 0 else v) + return min(seconds) diff --git a/cmapi/src/cmapi/ops/__init__.py b/cmapi/src/cmapi/ops/__init__.py index b98341c3..6cceebd9 100644 --- a/cmapi/src/cmapi/ops/__init__.py +++ b/cmapi/src/cmapi/ops/__init__.py @@ -10,6 +10,7 @@ """ from __future__ import annotations +import math from typing import Any, Callable from sqlalchemy import select @@ -288,16 +289,101 @@ def wait_import(sc: StepContext) -> StepResult: @step("cluster-onboard", "preflight") def preflight(sc: StepContext) -> StepResult: - """docs/02, step 2. Built: the import's own checks, connected with no finding, which include the reader's grants for the - cluster's Thanos Querier when the instance reads usage (#724). Not built (#763): the retention of at least 15 days and the - root Application's sync; the outputs list them as not checked, so nobody reads them as passed.""" + """docs/02, step 2: "the Thanos Route answers, retention is at least 15 days, and the root Application exists and is + Synced", after the import's own checks (connected, no finding, which include the reader's Thanos grants when the instance + reads usage, #724). Each check passes, is a finding, or does not apply to this instance and cluster, with its reason under + notApplicable. A check that cannot be read is a finding, never a pass (#763; docs/reviews/2026-12-01-issue-763).""" cid = sc.parameters["cluster-id"] st = sc.ctx.registry.get(cid) - not_checked = ["Thanos retention of at least 15 days (#763)", "the root Application exists and is Synced (#763)"] if st.status != "connected" or st.findings: return StepResult.failed(f"{cid} is {st.status}: {'; '.join(st.findings) or 'no finding'}", - findings=list(st.findings), notChecked=not_checked) - return StepResult.done(checks=["import connected", "no import finding"], notChecked=not_checked) + findings=list(st.findings)) + checks, findings = ["import connected", "no import finding"], [] + not_applicable: dict[str, str] = {} + outputs: dict[str, Any] = {} + for name, check in (("thanosRetention", _retention), ("rootApplication", _root_application)): + outcome, text, facts = check(sc.ctx, cid, st) + outputs.update(facts) + if outcome == "check": + checks.append(text) + elif outcome == "finding": + findings.append(text) + else: + not_applicable[name] = text + outputs.update(checks=checks, notApplicable=not_applicable) + if findings: + return StepResult.failed("; ".join(findings), findings=findings, **outputs) + return StepResult.done(**outputs) + + +# One preflight check's result: ("check", what passed), ("finding", what is wrong) or ("notApplicable", why), and its facts. +Checked = tuple[str, str, dict[str, Any]] + + +def _retention(ctx: Any, cid: str, st: Any) -> Checked: + """The Thanos Route answers and the platform Prometheus keeps at least MIN_RETENTION_DAYS (capacity/retention.py), read + as the usage reads are. An instance that reads no usage (capacity.yaml usage.source none) never reaches Thanos, and its + readers need no grant for it (#724), so there is nothing to check.""" + from cmapi.capacity.retention import MIN_RETENTION_DAYS, platform_retention_seconds + from cmapi.capacity.usage import MetricsUnavailable + + metrics = getattr(ctx.usage, "metrics", None) if ctx.usage.configured else None + if metrics is None: + return "notApplicable", "capacity.yaml usage.source is none: cmapi reads no Thanos Querier", {} + try: + seconds = platform_retention_seconds(metrics, cid) + except MetricsUnavailable as exc: + return "finding", f"the Thanos retention cannot be read: {exc}"[:300], {} + if seconds == math.inf: + return "check", "Thanos answers; platform Prometheus has no time retention limit", {"retentionDays": None} + days = seconds / 86400 + # In seconds when not whole days, so a rounded figure never reads as the bound it misses (15 days less a second). + kept = f"{days:g} days" if seconds % 86400 == 0 else f"{seconds:.15g} seconds" + facts = {"retentionDays": days} + if seconds < MIN_RETENTION_DAYS * 86400: + return ("finding", f"platform Prometheus keeps {kept}, less than {MIN_RETENTION_DAYS} days: set prometheusK8s.retention " + f"to {MIN_RETENTION_DAYS}d or more in openshift-monitoring/cluster-monitoring-config", facts) + return "check", f"Thanos answers; platform Prometheus keeps {kept}", facts + + +def _root_application(ctx: Any, cid: str, st: Any) -> Checked: + """The Argo CD root Application of integrations.yaml delivery.argocd exists and its status.sync.status is Synced. It is + the Application cmapi reads for this cluster: the gate in argocd mode, the signal in gitops mode with delivery.signal + argocd. In apply mode, or gitops with another signal, no Argo CD Application of cmapi's delivers the cluster.""" + from cmapi.core.clients.kube import BadResponse, ClusterUnreachable, KubeError + from cmapi.core.sync import ArgoCdSignal, application_name + from cmapi.jobs.delivery import mode_of + + mode, d = mode_of(ctx, cid), ctx.delivery + if mode == "apply": + return "notApplicable", f"delivery mode apply: the worker applies {cid}'s folders, and no Argo CD Application does", {} + if mode == "gitops" and d.signal != "argocd": + return "notApplicable", f"delivery mode gitops with delivery.signal {d.signal}: cmapi reads no Argo CD Application", {} + template = d.argocd_root_application + if application_name(template, cid, "a") != application_name(template, cid, "b"): + return ("notApplicable", f"delivery.argocd.rootApplication {template!r} names one Application per namespace, so the " + "cluster has no root Application", {}) + ns, name = d.argocd_namespace, application_name(template, cid, "") + label, facts = f"root Application {ns}/{name}", {"rootApplication": {"namespace": ns, "name": name}} + client = st.client # once: the registry clears it when the cluster drops (#402) + if client is None: + return "finding", f"{label} cannot be read: {cid} is {st.status}", facts + try: + app = ArgoCdSignal(client, ns, name).status(cid) + except KubeError as exc: + if exc.status == 404: + return "finding", f"{label} does not exist", facts + if exc.status == 403: + return ("finding", f"{label} cannot be read: the reader may not get it (the baseline grants get on argoproj.io " + "applications)", facts) + return "finding", f"{label} cannot be read: {exc}"[:300], facts + except (ClusterUnreachable, BadResponse, AttributeError, KeyError, TypeError) as exc: + # AttributeError, KeyError, TypeError: a status of another shape, which is no Synced Application either. + return "finding", f"{label} cannot be read: {type(exc).__name__}: {exc}"[:300], facts + facts["rootApplication"].update(sync=app.sync, health=app.health) + if app.sync != "Synced": + return "finding", f"{label} is {app.sync} (health {app.health}), not Synced", facts + return "check", f"{label} is Synced (health {app.health})", facts @step("cluster-onboard", "propose-registry") diff --git a/cmapi/src/cmapi/ops/templates/cluster-onboard.yaml b/cmapi/src/cmapi/ops/templates/cluster-onboard.yaml index 130248ed..d07d00b9 100644 --- a/cmapi/src/cmapi/ops/templates/cluster-onboard.yaml +++ b/cmapi/src/cmapi/ops/templates/cluster-onboard.yaml @@ -1,5 +1,6 @@ # docs/02, "Onboarding becomes shorter", and its template (config/operations/cluster-onboard.yaml). The steps that the build -# has: wait-import (the baseline's import Secret appears and connects) and preflight (the import's checks). propose-registry +# has: wait-import (the baseline's import Secret appears and connects) and preflight (the import's checks, the Thanos retention +# and the root Application, #763). propose-registry # needs POST /api/v1/admin/clusters:propose and smoke-test a namespace made and removed, which are not built: each refuses with # its issue, after the steps before it ran. A cluster that clusters.yaml already names skips propose-registry and wait-request. # docs/02's onExit: cleanup is left out: the bootstrap left cluster-onboard for the baseline, so no step makes anything to diff --git a/cmapi/tests/service/test_onboard_preflight_763.py b/cmapi/tests/service/test_onboard_preflight_763.py new file mode 100644 index 00000000..78b849e0 --- /dev/null +++ b/cmapi/tests/service/test_onboard_preflight_763.py @@ -0,0 +1,240 @@ +"""#763: cluster-onboard's preflight checks the Thanos retention and the root Application (Part of #26, criterion 3). + +docs/02, "Onboarding becomes shorter", step 2: "preflight: the Thanos Route answers, retention is at least 15 days, and the +root Application exists and is Synced". The run goes through the API and the worker's jobs, as test_operations_26.py does. + +The fake Thanos is the cluster's own: the reader's KubeClient (the suite's FakeKube) answers the thanos-querier Route and +GET /api/v1/query on it, and the instance reads usage through the production ThanosQuerier (capacity.yaml usage.source thanos). +It holds the three series CRC's Thanos Querier answered for the retention gauge on 2026-12-01 (OpenShift 4.22.14): the +platform Prometheus at 1296000 seconds, the user-workload Prometheus and the Thanos Ruler at 86400, with the platform's value +set by each test. The decisions and sources: docs/reviews/2026-12-01-issue-763/README.md. + + cd cmapi && PYTHONPATH=src:tests/service python -m pytest tests/service/test_onboard_preflight_763.py -q -W ignore +""" +from __future__ import annotations + +import math +import re + +import httpx +import pytest + +from cmapi.capacity.retention import RETENTION_QUERY, platform_retention_seconds +from cmapi.capacity.thanos import ROUTE_PATH +from cmapi.capacity.usage import MetricsUnavailable, usage_source +from cmapi.core.clients.kube import KubeError +from cmapi.core.sync import DeliveryConfig +from test_operations_26 import drive, get, rows_of, start + +DAY = 86400 +APP_PATH = "/apis/argoproj.io/v1alpha1/namespaces/openshift-gitops/applications/cluster-configs-crc" + + +def series(job: str, namespace: str, pod: str, seconds: float | str) -> dict: + return {"metric": {"__name__": "prometheus_tsdb_retention_limit_seconds", "job": job, "namespace": namespace, "pod": pod, + "service": job}, "value": [1796161671.109, str(seconds)]} + + +def crc_series(platform: list[float | str]) -> list[dict]: + """What CRC's Querier answered, with one platform replica per value of `platform` (two on a cluster with two).""" + return ([series("prometheus-k8s", "openshift-monitoring", f"prometheus-k8s-{i}", s) for i, s in enumerate(platform)] + + [series("prometheus-user-workload", "openshift-user-workload-monitoring", "prometheus-user-workload-0", DAY), + series("thanos-ruler", "openshift-user-workload-monitoring", "thanos-ruler-user-workload-0", DAY)]) + + +class FakeThanos: + """The Thanos Querier behind the Route: an instant query of one metric with equality matchers, as RETENTION_QUERY is.""" + + def __init__(self, held: list[dict]): + self.held, self.queries = held, [] + + def answer(self, url: str, params, timeout: float) -> httpx.Response: + assert url == "https://thanos-querier-openshift-monitoring.apps.test/api/v1/query", url + assert params["partial_response"] == "false" and params["dedup"] == "true" + query = params["query"] + self.queries.append(query) + name, matchers = re.fullmatch(r'(\w+)\{(.*)\}', query).groups() + want = dict(re.findall(r'(\w+)="([^"]*)"', matchers)) + found = [s for s in self.held if s["metric"]["__name__"] == name + and all(s["metric"].get(k) == v for k, v in want.items())] + return httpx.Response(200, json={"status": "success", "data": {"resultType": "vector", "result": found}}) + + +def cluster(world, monkeypatch, *, platform: list[float | str] | None = None, app: dict | None = None, + app_error: int | None = None, mode: str = "argocd", **delivery) -> FakeThanos | None: + """CRC as the run sees it. `platform`: the instance reads usage from Thanos, whose platform Prometheus replicas report + these retentions (None: usage.source none). `app`: the root Application's status (None: there is none). `mode` and + `delivery`: integrations.yaml's delivery block.""" + client, ctx, git, kube, validator, keys = world + monkeypatch.setattr(ctx, "delivery", DeliveryConfig(mode=mode, **delivery)) + thanos = None + if platform is not None: + thanos = FakeThanos(crc_series(platform)) + monkeypatch.setattr(ctx, "usage", usage_source({"usage": {"source": "thanos"}}, ctx.registry)) + monkeypatch.setattr(kube, "monitoring_get", thanos.answer, raising=False) + monkeypatch.setattr(kube, "redact", lambda text: text, raising=False) + + def get_path(path, params=None): + if path == ROUTE_PATH: + return {"spec": {"host": "thanos-querier-openshift-monitoring.apps.test"}} + if path == APP_PATH: + if app_error: + raise KubeError(app_error, path, "forbidden") + return None if app is None else {"metadata": {"name": "cluster-configs-crc", "namespace": "openshift-gitops"}, + "status": app} + raise AssertionError(f"preflight read {path}") + + monkeypatch.setattr(kube, "get", get_path, raising=False) + return thanos + + +def synced(sync: str = "Synced", health: str = "Healthy") -> dict: + return {"sync": {"status": sync, "revision": "0123456789abcdef"}, "health": {"status": health}} + + +def preflight_of(world) -> dict: + op_id = start(world, "cluster-onboard", {"cluster-id": "CRC"}).json()["operationId"] + drive(world[1]) + return rows_of(get(world, op_id), "preflight")[0] + + +# --------------------------------------------------------------------------- the issue's proof + + +def test_seven_days_of_retention_fails_preflight_with_that_finding(world, monkeypatch): + thanos = cluster(world, monkeypatch, platform=[7 * DAY, 7 * DAY], app=synced()) + row = preflight_of(world) + assert row["phase"] == "Failed", row + assert row["outputs"]["findings"] == [ + "platform Prometheus keeps 7 days, less than 15 days: set prometheusK8s.retention to 15d or more in " + "openshift-monitoring/cluster-monitoring-config"] + assert row["outputs"]["retentionDays"] == 7 and "keeps 7 days" in row["outputs"]["note"] + assert thanos.queries == [RETENTION_QUERY] + + +def test_one_second_short_of_fifteen_days_fails(world, monkeypatch): + """The bound is the seconds, not a rounded number of days.""" + cluster(world, monkeypatch, platform=[15 * DAY - 1], app=synced()) + row = preflight_of(world) + assert row["phase"] == "Failed", row + assert row["outputs"]["findings"][0].startswith("platform Prometheus keeps 1295999 seconds, less than 15 days"), row + + +def test_fifteen_days_and_a_synced_root_application_pass(world, monkeypatch): + """CRC's own answer: the platform at 15 days, the user-workload Prometheus and the Thanos Ruler at one day. Only the + platform counts, so preflight passes, and every check is listed as passed: nothing is "not checked".""" + cluster(world, monkeypatch, platform=[15 * DAY, 15 * DAY], app=synced()) + row = preflight_of(world) + assert row["phase"] == "Succeeded", row + out = row["outputs"] + assert out["checks"] == ["import connected", "no import finding", "Thanos answers; platform Prometheus keeps 15 days", + "root Application openshift-gitops/cluster-configs-crc is Synced (health Healthy)"] + assert out["notApplicable"] == {} and "notChecked" not in out and out["retentionDays"] == 15 + assert out["rootApplication"] == {"namespace": "openshift-gitops", "name": "cluster-configs-crc", "sync": "Synced", + "health": "Healthy"} + + +def test_an_out_of_sync_root_application_fails_preflight(world, monkeypatch): + cluster(world, monkeypatch, platform=[15 * DAY], app=synced("OutOfSync")) + row = preflight_of(world) + assert row["phase"] == "Failed", row + assert row["outputs"]["findings"] == [ + "root Application openshift-gitops/cluster-configs-crc is OutOfSync (health Healthy), not Synced"] + + +def test_a_missing_root_application_fails_preflight(world, monkeypatch): + cluster(world, monkeypatch, platform=[15 * DAY], app=None) + row = preflight_of(world) + assert row["phase"] == "Failed", row + assert row["outputs"]["findings"] == ["root Application openshift-gitops/cluster-configs-crc does not exist"] + + +# --------------------------------------------------------------------------- fail closed + + +def test_a_retention_that_cannot_be_read_fails_preflight(world, monkeypatch): + """No platform series: the user-workload Prometheus's one day is not the platform's, and nothing is assumed.""" + cluster(world, monkeypatch, platform=[], app=synced()) + row = preflight_of(world) + assert row["phase"] == "Failed", row + [finding] = row["outputs"]["findings"] + assert finding.startswith("the Thanos retention cannot be read: CRC: the Thanos Querier has no " + "prometheus_tsdb_retention_limit_seconds of job prometheus-k8s"), finding + + +def test_a_root_application_the_reader_may_not_read_fails_preflight(world, monkeypatch): + cluster(world, monkeypatch, platform=[15 * DAY], app_error=403) + row = preflight_of(world) + assert row["phase"] == "Failed", row + assert row["outputs"]["findings"] == ["root Application openshift-gitops/cluster-configs-crc cannot be read: the reader may " + "not get it (the baseline grants get on argoproj.io applications)"] + + +def test_both_findings_are_named_together(world, monkeypatch): + cluster(world, monkeypatch, platform=[DAY], app=synced("Unknown", "Missing")) + row = preflight_of(world) + assert row["phase"] == "Failed" and len(row["outputs"]["findings"]) == 2, row + assert row["outputs"]["checks"] == ["import connected", "no import finding"] + + +# --------------------------------------------------------------------------- what does not apply + + +def test_an_instance_without_usage_or_argo_cd_lists_both_as_not_applicable(world, monkeypatch): + """The suite's instance, as CRC's delivery: usage.source none and delivery mode apply. Neither check applies, each says + why, and the step passes on the import's checks. The cluster is never read for them.""" + cluster(world, monkeypatch, mode="apply") + row = preflight_of(world) + assert row["phase"] == "Succeeded", row + assert row["outputs"]["notApplicable"] == { + "thanosRetention": "capacity.yaml usage.source is none: cmapi reads no Thanos Querier", + "rootApplication": "delivery mode apply: the worker applies CRC's folders, and no Argo CD Application does"} + assert row["outputs"]["checks"] == ["import connected", "no import finding"] + + +@pytest.mark.parametrize("delivery, checked", [ + ({"mode": "gitops"}, False), # signal none: the deliverer is not named + ({"mode": "gitops", "signal": "flux"}, False), + ({"mode": "gitops", "signal": "argocd"}, True), # the Application cmapi reads as signal + ({"mode": "argocd", "argocd_root_application": "cmapi-{clusterId}-{namespace}"}, False), # one per namespace +]) +def test_the_root_application_is_checked_where_cmapi_reads_one(world, monkeypatch, delivery, checked): + cluster(world, monkeypatch, platform=[15 * DAY], app=None, **delivery) + row = preflight_of(world) + if checked: + assert row["phase"] == "Failed" and row["outputs"]["findings"] == [ + "root Application openshift-gitops/cluster-configs-crc does not exist"], row + else: + assert row["phase"] == "Succeeded" and set(row["outputs"]["notApplicable"]) == {"rootApplication"}, row + + +# --------------------------------------------------------------------------- the gauge + + +class Answers: + def __init__(self, result: list[dict]): + self.result = result + + def query(self, cluster_id, promql, at=None): + return self.result + + +def test_the_shortest_replica_counts_and_zero_is_no_time_limit(): + assert platform_retention_seconds(Answers(crc_series([20 * DAY, 10 * DAY])[:2]), "C") == 10 * DAY + assert platform_retention_seconds(Answers(crc_series([0])[:1]), "C") == math.inf + assert platform_retention_seconds(Answers(crc_series([0, 16 * DAY])[:2]), "C") == 16 * DAY + + +@pytest.mark.parametrize("value", ["NaN", "+Inf", "-1", "fifteen days"]) +def test_a_value_that_is_not_seconds_cannot_be_read(value): + with pytest.raises(MetricsUnavailable, match="not a number of seconds"): + platform_retention_seconds(Answers(crc_series([value])[:1]), "C") + + +def test_no_time_limit_passes_preflight(world, monkeypatch): + """Size-only retention: Prometheus deletes nothing by age (tsdb BeyondTimeRetention: "Time retention is disabled").""" + cluster(world, monkeypatch, platform=[0], app=synced()) + row = preflight_of(world) + assert row["phase"] == "Succeeded", row + assert "Thanos answers; platform Prometheus has no time retention limit" in row["outputs"]["checks"] + assert row["outputs"]["retentionDays"] is None diff --git a/cmapi/tests/service/test_operations_26.py b/cmapi/tests/service/test_operations_26.py index af584d5a..01a7e778 100644 --- a/cmapi/tests/service/test_operations_26.py +++ b/cmapi/tests/service/test_operations_26.py @@ -431,7 +431,8 @@ def test_reconcile_with_nothing_unrecorded_succeeds(world): def test_cluster_onboard_runs_what_is_built_and_stops_at_the_step_that_is_not(world): """CRC is imported and named by clusters.yaml: wait-import and preflight pass, propose-registry and wait-request are - skipped, and smoke-test refuses with its issue (#765).""" + skipped, and smoke-test refuses with its issue (#765). The suite's instance reads no usage and delivers by apply, so + preflight's retention and root Application checks do not apply, each with its reason (#763).""" client, ctx, git, kube, validator, keys = world op_id = start(world, "cluster-onboard", {"cluster-id": "CRC"}).json()["operationId"] drive(ctx) @@ -440,7 +441,7 @@ def test_cluster_onboard_runs_what_is_built_and_stops_at_the_step_that_is_not(wo assert phases == {"wait-import": "Succeeded", "preflight": "Succeeded", "propose-registry": "Skipped", "wait-request": "Skipped", "smoke-test": "Failed"}, view["steps"] assert "#765" in rows_of(view, "smoke-test")[0]["lastError"] and view["phase"] == "Failed" - assert rows_of(view, "preflight")[0]["outputs"]["notChecked"] + assert set(rows_of(view, "preflight")[0]["outputs"]["notApplicable"]) == {"thanosRetention", "rootApplication"} def test_cluster_onboard_waits_for_an_import_that_is_not_there(world): diff --git a/docs/02-technical-design-v2.md b/docs/02-technical-design-v2.md index dbc21378..69abf65f 100644 --- a/docs/02-technical-design-v2.md +++ b/docs/02-technical-design-v2.md @@ -822,7 +822,7 @@ Refused, as `invalid-secret` before any client is built, so the token is never s `POST /api/v1/clusters/{id}:probe` requires `operations:run` in the cluster's environment. An import without a configured environment requires an unrestricted grant. The probe tests only this cluster's credential from the last successful discovery. It reads `GET /version`, then `GET /apis/user.openshift.io/v1/users/~` (with the relist's non-persistent SelfSubjectReview fallback), then lists namespaces to check the reader's grant, and, when the instance reads usage, reviews the reader's grants for Thanos as the relist does. It writes no hub or cluster resources. It shares the relist lock and publishes the same diagnostics, transition events and cache decisions. A healthy cache with the same fingerprint stays in use. Failure drops the cache, and recovery or a changed fingerprint installs a fresh one. The response is the cluster view, including for a known cluster without an import. An unknown ID or one outside the caller’s grant returns 404 `cluster-not-found`. Built (#456): a check of an import Secret logs `cluster_import` once when its status or redacted findings change (`ClusterRegistry._set`, `cmapi/src/cmapi/core/registry.py`). A new or different problem is a warning; recovery to `connected` is info, with empty findings. The first healthy import emits no recovery event. Each event has `cluster_id`, `status`, `previous` (the previous status) and `findings`. Relists with the same status and redacted findings emit no further event. Findings are redacted before comparison, storage and logging (#420); the status metric is still updated on every check. A cluster that loses its Secret becomes `not-imported` and logs one warning with the previous status and the finding `no import Secret`; repeated relists without the Secret stay silent (`ClusterRegistry._refresh`). Concurrent refresh passes are serialized, including their events and retirement. The fields phase, outcome and action are not built. -**Onboarding becomes shorter.** The bootstrap and store-credential steps leave cluster-onboard; the baseline does that work. What remains, as designed. *Built (#26) on the built-in engine (`cmapi/src/cmapi/ops/templates/cluster-onboard.yaml`): step 1, and step 2's check of the import (connected, no finding, with the reader's Thanos grants, #724). Not built: step 2's retention and root Application checks (#763), step 3 (`POST /api/v1/admin/clusters:propose`, #761; a cluster that clusters.yaml names skips it and step 4), and step 5 (#765), which refuses with its issue. Today step 3 is manual.* +**Onboarding becomes shorter.** The bootstrap and store-credential steps leave cluster-onboard; the baseline does that work. What remains, as designed. *Built (#26) on the built-in engine (`cmapi/src/cmapi/ops/templates/cluster-onboard.yaml`): step 1, and step 2 (#763): the import's check (connected, no finding, with the reader's Thanos grants, #724); then the platform Prometheus's time retention, its gauge `prometheus_tsdb_retention_limit_seconds` of job `prometheus-k8s` in openshift-monitoring read through the Thanos Querier as usage is, at least 15 days, 0 being no time limit; and the root Application of `delivery.argocd` with `status.sync.status` Synced. A check that cannot be read is a finding. The retention check applies when `capacity.yaml` `usage.source` is `thanos`, the root Application in `argocd` mode and in `gitops` mode with `delivery.signal: argocd`; otherwise the step's `notApplicable` output says why (`cmapi/src/cmapi/ops/__init__.py`, `preflight`; docs/reviews/2026-12-01-issue-763). Not built: step 3 (`POST /api/v1/admin/clusters:propose`, #761; a cluster that clusters.yaml names skips it and step 4), and step 5 (#765), which refuses with its issue. Today step 3 is manual.* 1. wait-import: the import Secret appears and the cluster connects. 2. preflight: the Thanos Route answers, retention is at least 15 days, and the root Application exists and is Synced. diff --git a/docs/21-usage-from-thanos.md b/docs/21-usage-from-thanos.md index b2f43a78..364d74b4 100644 --- a/docs/21-usage-from-thanos.md +++ b/docs/21-usage-from-thanos.md @@ -123,7 +123,7 @@ from the file. The file also creates the Namespace `cmapi-system` and the Servic | 6 (`examples/baseline/cmapi-reader-rbac.yaml:38-40`) | `quota.openshift.io`: `clusterresourcequotas` | get, list, watch | No code reads it today | | 7 (`examples/baseline/cmapi-reader-rbac.yaml:41-43`) | `redhatcop.redhat.io`: `groupsyncs`, `namespaceconfigs`, `groupconfigs` | get, list | No code reads it today | | 8 (`examples/baseline/cmapi-reader-rbac.yaml:44-47`) | `config.openshift.io`: `oauths`, `resourceNames: [cluster]` | get | No code reads it today | -| 9 (`examples/baseline/cmapi-reader-rbac.yaml:48-50`) | `argoproj.io`: `applications` | get, list, watch | The sync poll reads the root Application: `ArgoCdSignal.status` (`cmapi/src/cmapi/core/sync.py:191`), called from `cmapi/src/cmapi/jobs/watch_sync.py:168` | +| 9 (`examples/baseline/cmapi-reader-rbac.yaml:48-50`) | `argoproj.io`: `applications` | get, list, watch | The sync poll reads the root Application: `ArgoCdSignal.status` (`cmapi/src/cmapi/core/sync.py:191`), called from `cmapi/src/cmapi/jobs/watch_sync.py:168`; and cluster-onboard's preflight reads it once (`cmapi/src/cmapi/ops/__init__.py:372`, #763) | | 10 (`examples/baseline/cmapi-reader-rbac.yaml:51-53`) | `wgpolicyk8s.io`: `policyreports`, `clusterpolicyreports` | get, list, watch | The Policies tab's `ReportCache` watches both (`cmapi/src/cmapi/core/clients/policyreports.py:37`) | | 11 (`examples/baseline/cmapi-reader-rbac.yaml:54-56`) | `policies.kyverno.io`: `validatingpolicies`, `mutatingpolicies`, `generatingpolicies`, `deletingpolicies`, `imagevalidatingpolicies` | get, list, watch | Only `validatingpolicies` is read (`cmapi/src/cmapi/core/clients/policyreports.py:38`); the other four are not | | 12 (`examples/baseline/cmapi-reader-rbac.yaml:57-59`) | `kyverno.io`: `clusterpolicies`, `policies` | get, list | No code reads it today | @@ -214,6 +214,12 @@ they are kept. While any finding stands, `ThanosQuerier.query` refuses before it cluster, with no finding, still serves its cache. - **The daily usage sweep** reads the same source, every namespace of a cluster at one instant, in batches of eight, with a 120-second timeout per query (`cmapi/src/cmapi/capacity/usage.py:256-264`, `cmapi/src/cmapi/capacity/sweep.py:87`). +- **cluster-onboard's preflight** (#763) makes one instant query through the same `ThanosQuerier`: Prometheus's gauge + `prometheus_tsdb_retention_limit_seconds` of job `prometheus-k8s` in `openshift-monitoring` + (`cmapi/src/cmapi/capacity/retention.py:29`). The shortest replica counts, 0 is no time limit, and under 15 days, or no + answer, fails the step with that finding (`:32-46`, `cmapi/src/cmapi/ops/__init__.py:323-346`). The matchers keep out + the user-workload Prometheus and the Thanos Ruler, which CRC reported at 86400 seconds beside the platform's 1296000 + (`docs/reviews/2026-12-01-issue-763/README.md`, D1). - **A namespace create never queries Thanos.** Only a quota change on an existing namespace reads usage (`cmapi/src/cmapi/core/pipeline.py:467-474`). A test creates a namespace on PostgreSQL with `usage.source: thanos` and both grants missing: it is auto-approved, reaches `synced`, and makes no monitoring call; the quota change after it plans with @@ -245,7 +251,7 @@ cluster, so for 4.18 the sources below are the evidence. - With `usage.source: none`, the default, nothing is read: every plan says there is no usage, and why (`cmapi/src/cmapi/capacity/usage.py:168-176`). - Prometheus keeps 15 days by default, so a 14-day window is the longest that is safe (`docs/02-technical-design-v2.md`, - "Capacity plugin (API side)", "Retention limit"). + "Capacity plugin (API side)", "Retention limit"). cluster-onboard's preflight refuses a cluster whose platform Prometheus keeps less (#763). ## Sources (read on 2026-11-26) diff --git a/docs/citations.lock.json b/docs/citations.lock.json index ba62edf0..3bd61f75 100644 --- a/docs/citations.lock.json +++ b/docs/citations.lock.json @@ -1118,6 +1118,26 @@ "docs/16-data-model.md|cmapi/src/cmapi/jobs/channel_notify.py|30-30": [ " s.add(ApprovalNotificationRow(request_id=row.request_id, channel=ch.name, kind=kind," ], + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/capacity/retention.py|29-29": [ + "RETENTION_QUERY = 'prometheus_tsdb_retention_limit_seconds{namespace=\"openshift-monitoring\", job=\"prometheus-k8s\"}'" + ], + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/capacity/retention.py|32-46": [ + "def platform_retention_seconds(metrics: MetricsSource, cluster_id: str) -> float:", + " \"\"\"The shortest time retention of the cluster's platform Prometheus replicas, in seconds, or math.inf when none has a time", + " limit. MetricsUnavailable when it cannot be read: the query fails, no replica reports the gauge, or a value is not a", + " number of seconds. Never a default: a retention that is not read is not assumed.\"\"\"", + " series = metrics.query(cluster_id, RETENTION_QUERY)", + " if not series:", + " raise MetricsUnavailable(f\"{cluster_id}: the Thanos Querier has no prometheus_tsdb_retention_limit_seconds of \"", + " \"job prometheus-k8s in openshift-monitoring\")", + " seconds: list[float] = []", + " for s in series:", + " v = sample(s)", + " if v is None or v < 0:", + " raise MetricsUnavailable(f\"{cluster_id}: a prometheus_tsdb_retention_limit_seconds that is not a number of seconds\")", + " seconds.append(math.inf if v == 0 else v)", + " return min(seconds)" + ], "docs/21-usage-from-thanos.md|cmapi/src/cmapi/capacity/sweep.py|87-87": [ " measured = usage.cluster(st.cluster_id, idle_days=t.idle_days, ceiling=t.quota_tight_at, at=at)" ], @@ -1703,6 +1723,35 @@ "docs/21-usage-from-thanos.md|cmapi/src/cmapi/jobs/watch_sync.py|168-168": [ " app = ArgoCdSignal(reader, ctx.delivery.argocd_namespace," ], + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/ops/__init__.py|323-346": [ + "def _retention(ctx: Any, cid: str, st: Any) -> Checked:", + " \"\"\"The Thanos Route answers and the platform Prometheus keeps at least MIN_RETENTION_DAYS (capacity/retention.py), read", + " as the usage reads are. An instance that reads no usage (capacity.yaml usage.source none) never reaches Thanos, and its", + " readers need no grant for it (#724), so there is nothing to check.\"\"\"", + " from cmapi.capacity.retention import MIN_RETENTION_DAYS, platform_retention_seconds", + " from cmapi.capacity.usage import MetricsUnavailable", + "", + " metrics = getattr(ctx.usage, \"metrics\", None) if ctx.usage.configured else None", + " if metrics is None:", + " return \"notApplicable\", \"capacity.yaml usage.source is none: cmapi reads no Thanos Querier\", {}", + " try:", + " seconds = platform_retention_seconds(metrics, cid)", + " except MetricsUnavailable as exc:", + " return \"finding\", f\"the Thanos retention cannot be read: {exc}\"[:300], {}", + " if seconds == math.inf:", + " return \"check\", \"Thanos answers; platform Prometheus has no time retention limit\", {\"retentionDays\": None}", + " days = seconds / 86400", + " # In seconds when not whole days, so a rounded figure never reads as the bound it misses (15 days less a second).", + " kept = f\"{days:g} days\" if seconds % 86400 == 0 else f\"{seconds:.15g} seconds\"", + " facts = {\"retentionDays\": days}", + " if seconds < MIN_RETENTION_DAYS * 86400:", + " return (\"finding\", f\"platform Prometheus keeps {kept}, less than {MIN_RETENTION_DAYS} days: set prometheusK8s.retention \"", + " f\"to {MIN_RETENTION_DAYS}d or more in openshift-monitoring/cluster-monitoring-config\", facts)", + " return \"check\", f\"Thanos answers; platform Prometheus keeps {kept}\", facts" + ], + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/ops/__init__.py|372-372": [ + " app = ArgoCdSignal(client, ns, name).status(cid)" + ], "docs/21-usage-from-thanos.md|cmapi/tests/service/test_reader_thanos_grants_724.py|428-470": [ "def test_a_namespace_is_created_and_its_quota_changed_without_the_grants(test_config, fresh_db, keys, monkeypatch, tmp_path):", " \"\"\"The whole write path on PostgreSQL, with usage.source thanos and neither grant (#724). docs/02: \"Namespace creation and", diff --git a/docs/reviews/2026-12-01-issue-763/README.md b/docs/reviews/2026-12-01-issue-763/README.md new file mode 100644 index 00000000..fb37ac0d --- /dev/null +++ b/docs/reviews/2026-12-01-issue-763/README.md @@ -0,0 +1,165 @@ +# #763: cluster-onboard's preflight checks the Thanos retention and the root Application + +Part of story #26, criterion 3. The design is docs/02, "Onboarding becomes shorter", step 2: "preflight: the Thanos Route +answers, retention is at least 15 days, and the root Application exists and is Synced". docs/02, "Retention limit", says why: +"Platform Prometheus keeps 15 days by default, and the in-cluster Thanos Querier has no long-term store behind it, so any +window over 14 days silently returns less data". docs/02's operational section adds: "confirm the Thanos Route answers with the +API token, and confirm platform Prometheus retention is at least 15 days". It is built as written. This record holds the +decisions the design left open, each with the source it rests on. + +Written by the implementer (Opus 5.5, high) on 2026-12-01. Every source below was fetched that day; copies of the source files +are in the implementer's notes folder (`workbench/cmapi/build-763/sources/`), outside the repository. + +## What is built + +- `cmapi/src/cmapi/capacity/retention.py`: `platform_retention_seconds`, the shortest time retention of the cluster's + platform Prometheus replicas, read through the cluster's Thanos Querier. `MIN_RETENTION_DAYS = 15`. +- `cmapi/src/cmapi/ops/__init__.py`, `preflight`: after the import's own checks, `_retention` and `_root_application`. Each + check passes (`checks`), is a finding (`findings`, and the step is Failed), or does not apply to the instance and cluster + (`notApplicable`, with the reason). The outputs no longer hold `notChecked`. +- `cmapi/tests/service/test_onboard_preflight_763.py`, and the onboarding test of `test_operations_26.py` updated. + +## D1. Retention is Prometheus's own gauge, read by the usage query path + +Options weighed: + +1. **Thanos Query's `/api/v1/status/flags`.** Thanos registers it (thanos v0.36.1, `pkg/api/api.go`: + `r.Get("/status/flags", ...)`), but it returns Thanos Query's own flags. Measured on CRC (OpenShift 4.22.14, + 2026-12-01 21:47Z): 81 flags, none naming retention or the TSDB. Rejected: it cannot say what Prometheus keeps. +2. **Prometheus's own `/api/v1/status/flags` (`storage.tsdb.retention.time`).** The thanos-querier Route reaches the Thanos + Querier only (cluster-monitoring-operator release-4.18, `assets/thanos-querier/route.yaml`: `to: {kind: Service, name: + thanos-querier}`, "Expose the `/api` endpoints of the `thanos-querier` service via a router"). Reaching Prometheus itself + needs another Route or a grant on prometheus-k8s that the baseline does not give. Rejected: a new grant and a new path. +3. **The cluster-monitoring-config ConfigMap.** A grant on a ConfigMap in openshift-monitoring that the baseline does not + give, and it holds what was asked, not what runs: with no `retention` key the default applies (below). Rejected. +4. **Chosen: the gauge `prometheus_tsdb_retention_limit_seconds`, by an instant query on the Thanos Querier**, through + `ThanosQuerier.query`: the same Route, token, trust, grants (#724), `partial_response=false` and `dedup=true` as the usage + reads. One query proves "the Thanos Route answers" and reads the retention. + +The gauge (prometheus `tsdb/db.go`, main and openshift/prometheus release-4.18, which is Prometheus 2.55.1 per its +`VERSION`): + +> `Name: "prometheus_tsdb_retention_limit_seconds", Help: "How long to retain samples in storage."` +> `db.metrics.retentionDuration.Set((time.Duration(opts.RetentionDuration) * time.Millisecond).Seconds())` + +The series that count are the platform Prometheus's: `job="prometheus-k8s"` in `openshift-monitoring`. The platform +Prometheus scrapes itself through the ServiceMonitor `prometheus-k8s` with no metric relabelling +(cluster-monitoring-operator release-4.18, `assets/prometheus-k8s/service-monitor.yaml`), behind the Service +`prometheus-k8s` (`assets/prometheus-k8s/service.yaml`), and prometheus-operator sets `job` from the Service's name +(`pkg/prometheus/promcfg.go`: `source_labels: [__meta_kubernetes_service_name]`, `target_label: job`). The matchers are needed, +as measured on CRC the same night (`GET /api/v1/query?query=prometheus_tsdb_retention_limit_seconds`): + +| job | namespace | value (seconds) | +|---|---|---| +| prometheus-k8s | openshift-monitoring | 1296000 (15 days) | +| prometheus-user-workload | openshift-user-workload-monitoring | 86400 | +| thanos-ruler | openshift-user-workload-monitoring | 86400 | + +Without them the user-workload Prometheus's 24-hour default would fail every cluster with user-workload monitoring on. With +them, CRC answers the one series of `prometheus-k8s-0`. The usage reads (`usage.py`) read platform metrics (cAdvisor and +kube-state-metrics, scraped by the platform Prometheus), so the platform's retention is the one that bounds their window. + +A cluster with two replicas answers two series (one per pod; `dedup=true` removes only the replica label +`prometheus_replica`, `assets/thanos-querier/deployment.yaml`: `--query.replica-label=prometheus_replica`). The shortest +counts. + +## D2. The 15 days, and what a value of 0 means + +`MIN_RETENTION_DAYS = 15` is a constant: no configuration file has a key for it (`docs/18-configuration.md` has none), and +the brief says a constant with its source when no knob exists. The source is docs/02, step 2. It matches the platform's +default: + +- OpenShift 4.18 documentation (openshift-docs `enterprise-4.18`, + `modules/monitoring-modifying-retention-time-and-size-for-prometheus-metrics-data.adoc`): "By default, Prometheus retains + metrics data for 15 days for core platform monitoring." +- cluster-monitoring-operator release-4.18, `pkg/manifests/config.go`: `DefaultRetentionValue = "15d"`, applied when + `PrometheusK8sConfig.Retention == "" && PrometheusK8sConfig.RetentionSize == ""`. +- Prometheus `docs/storage.md`: "If neither this flag nor `storage.tsdb.retention.size` is set, the retention time defaults + to `15d`." + +A gauge of **0 passes**, as no time limit. Prometheus runs with a time retention of 0 when only a size is set (release-4.18 +`cmd/prometheus/main.go` applies the default only `if cfg.tsdb.RetentionDuration == 0 && cfg.tsdb.MaxBytes == 0`), and then +deletes nothing by age (`tsdb/db.go`, `BeyondTimeRetention`: "Time retention is disabled or no blocks to work with ... `if +len(blocks) == 0 || db.opts.RetentionDuration == 0 { return }`"). The design's check is of the time retention. A size limit +can delete sooner whatever the time retention is (Prometheus `docs/storage.md`: "If both time and size retention policies are +specified, whichever triggers first will be used"), with or without this check; it is not judged here, and the output says +"no time retention limit" rather than a number of days. + +## D3. A retention that cannot be read is a finding + +As the rest of preflight, it fails closed: no series of the platform job, a query error, a warning, a timeout, or a value +that is not a non-negative number (NaN, an infinity, text) is the finding `the Thanos retention cannot be read: `, and +the step is Failed. Nothing is assumed, the 15-day default included. A transient failure is fixed by starting the run again, +as the import check's failure already is. A cluster whose clusters.yaml entry names a `thanosUrl` is read there, as its usage +is (`ThanosQuerier._base_url`); an endpoint that does not serve the gauge gives the same finding. + +The bound is compared in seconds, never on a rounded number of days, and a retention that is not whole days is said in +seconds: 15 days less one second fails as `keeps 1295999 seconds, less than 15 days`. + +## D4. Retention applies when the instance reads usage from Thanos + +An instance with `capacity.yaml` `usage.source: none` (the default; kind) never reaches a Thanos Querier, and its readers +need no grant for one: the import check reviews the Thanos grants only with `usage.source: thanos` (#724, +`core/registry.py`). Requiring Thanos there would refuse a cluster cmapi never reads metrics from. So the check is listed under +`notApplicable` with "capacity.yaml usage.source is none: cmapi reads no Thanos Querier". CRC reads usage from Thanos +(`deploy/manifests/environments/crc/20-config.yaml`: `usage: {"source":"thanos"}`), so preflight checks it there. + +## D5. Which root Application, and when it applies + +The name and namespace are those cmapi already reads, not new ones: `integrations.yaml` `delivery.argocd.rootApplication` +(default `cluster-configs-{clusterId}`) in `delivery.argocd.namespace` (default `openshift-gitops`), by +`core/sync.application_name` (docs/18: "The name of the root Application"; "The namespace of the Argo CD root Application: +the gate in `argocd` mode, the signal in `gitops` mode with `delivery.signal: argocd`"). The read is `ArgoCdSignal`, the +one the argocd-mode sync poll uses, with the reader's baseline grant (`examples/baseline/cmapi-reader-rbac.yaml`: +`argoproj.io` `applications`, `get, list, watch`). + +The cluster's delivery mode is its clusters.yaml `delivery`, else the instance's `delivery.mode` (`jobs/delivery.mode_of`; +at onboarding clusters.yaml usually does not name the cluster yet). The check applies where cmapi reads an Argo CD Application +for the cluster: + +| Mode | Root Application | +|---|---| +| `argocd` | Checked: it is the gate of every request | +| `gitops` with `delivery.signal: argocd` | Checked: it is the deliverer the instance names | +| `gitops` with `delivery.signal` `none` or `flux` | Not applicable: cmapi reads no Argo CD Application (#751: whatever applies Git main, confirmed by the read of the plan) | +| `apply` | Not applicable: the worker applies the folder; CRC, which has no `applications.argoproj.io` CRD (measured 2026-12-01) | + +A template with `{namespace}` names one Application per namespace (docs/18), so the cluster has no root Application before +its first namespace: not applicable, with that reason. + +"Synced" is Argo CD's `status.sync.status` (argo-cd `pkg/apis/application/v1alpha1/types.go`: `SyncStatusCodeSynced +SyncStatusCode = "Synced"` "indicates that desired and live states match"; the other values are `OutOfSync` "there is a drift +between desired and live states" and `Unknown` "the status of a sync could not be reliably determined"). Only `Synced` +passes. Health is reported beside it and not judged: the design asks for "exists and is Synced". The findings: `does not +exist` (404), `cannot be read: the reader may not get it` (403), `cannot be read: ` (another status, the cluster +unreachable, a status of another shape), and `is (health ), not Synced`. + +A root Application that Argo CD cannot compare yet, for example a cluster folder not in Git, reports `Unknown` +(docs/reviews/2026-11-05-deployment-design.md measured "app path does not exist", status `Unknown`), so preflight fails there +until the folder exists. That is the design's order: the root Application must be Synced before the cluster is registered. + +## D6. Findings together, one step result + +Both checks run, and every finding is named in `findings` and in the step's error, so one run says all that is wrong. The +step is Failed, as the import check's failure already was: the operator fixes what is named and starts the run again. + +## Tests + +`cmapi/tests/service/test_onboard_preflight_763.py`, run one file at a time against PostgreSQL 16 on 127.0.0.1:55432 with +the suite's fakes (no cluster): + +- 7 days of retention fails with that finding; 15 days with a Synced root Application passes; an OutOfSync root + Application fails; a missing one fails (the issue's proof). 15 days less one second fails too. +- A retention that cannot be read fails; a forbidden root Application fails; both findings are named together. +- usage.source none and delivery mode apply list both checks as not applicable; the root Application is checked in exactly + the modes of D5; 0 passes as no time limit; the shortest replica counts; a value that is not seconds cannot be read. + +Each test of the preflight's behaviour fails on main's preflight: the final file, run with main's +`cmapi/src/cmapi/ops/__init__.py` in place, has 14 failed and 5 passed, the five being the tests of the gauge alone, which +test the new module; with this change, 19 passed (the implementer's notes hold both outputs). The test of 15 days less a +second was added after the implementer's second pass of the first version, which compared a number of days rounded to +two places. + +Not tested: a cluster with Argo CD (none is available without a cluster write); the reader's own token on CRC's Route for +this query (the measurement above used an administrator's token; the reader's grant for `/api/v1/query` is #724's, proven +there). From 12444a2680f8798ce7f7eaf9155dbf27682099c6 Mon Sep 17 00:00:00 2001 From: ephico2real2 Date: Tue, 1 Dec 2026 16:53:07 -0600 Subject: [PATCH 2/2] #763 review fixes: a configured usage source with no metrics reader is a retention finding, not a check that does not apply; rulings recorded --- cmapi/src/cmapi/ops/__init__.py | 7 ++-- .../service/test_onboard_preflight_763.py | 33 +++++++++++++++++++ docs/21-usage-from-thanos.md | 4 +-- docs/citations.lock.json | 11 ++++--- docs/reviews/2026-12-01-issue-763/README.md | 17 ++++++++++ 5 files changed, 64 insertions(+), 8 deletions(-) diff --git a/cmapi/src/cmapi/ops/__init__.py b/cmapi/src/cmapi/ops/__init__.py index 6cceebd9..369838d5 100644 --- a/cmapi/src/cmapi/ops/__init__.py +++ b/cmapi/src/cmapi/ops/__init__.py @@ -327,9 +327,12 @@ def _retention(ctx: Any, cid: str, st: Any) -> Checked: from cmapi.capacity.retention import MIN_RETENTION_DAYS, platform_retention_seconds from cmapi.capacity.usage import MetricsUnavailable - metrics = getattr(ctx.usage, "metrics", None) if ctx.usage.configured else None - if metrics is None: + if not ctx.usage.configured: return "notApplicable", "capacity.yaml usage.source is none: cmapi reads no Thanos Querier", {} + # `metrics` is not part of UsageSource: a configured source without it is a finding, never a check that does not apply. + metrics = getattr(ctx.usage, "metrics", None) + if metrics is None: + return "finding", "the Thanos retention cannot be read: the usage source has no metrics reader", {} try: seconds = platform_retention_seconds(metrics, cid) except MetricsUnavailable as exc: diff --git a/cmapi/tests/service/test_onboard_preflight_763.py b/cmapi/tests/service/test_onboard_preflight_763.py index 78b849e0..0713d8e1 100644 --- a/cmapi/tests/service/test_onboard_preflight_763.py +++ b/cmapi/tests/service/test_onboard_preflight_763.py @@ -238,3 +238,36 @@ def test_no_time_limit_passes_preflight(world, monkeypatch): assert row["phase"] == "Succeeded", row assert "Thanos answers; platform Prometheus has no time retention limit" in row["outputs"]["checks"] assert row["outputs"]["retentionDays"] is None + + +def test_a_configured_usage_source_without_a_metrics_reader_is_a_finding(world, monkeypatch): + """`metrics` is not part of the UsageSource protocol: a source that reads usage but has no reader for the gauge fails + closed, never "usage.source is none".""" + class ReaderlessUsage: + configured = True + + cluster(world, monkeypatch, mode="apply") + monkeypatch.setattr(world[1], "usage", ReaderlessUsage()) + row = preflight_of(world) + assert row["phase"] == "Failed", row + assert row["outputs"]["findings"] == ["the Thanos retention cannot be read: the usage source has no metrics reader"] + assert "thanosRetention" not in row["outputs"]["notApplicable"] + + +def test_an_unexpected_read_error_gets_the_templates_retry(world, monkeypatch): + """A client the registry closed between its snapshot and the read is transient (httpx raises RuntimeError "Cannot send a + request, as the client has been closed."). It is no finding: the step raises, the template's retry runs it again, and + the next attempt reads and passes.""" + cluster(world, monkeypatch, platform=[15 * DAY], app=synced()) + answer, calls = world[3].get, [] + + def closed_once(path, params=None): + calls.append(path) + if len(calls) == 1: + raise RuntimeError("Cannot send a request, as the client has been closed.") + return answer(path, params) + + monkeypatch.setattr(world[3], "get", closed_once) + row = preflight_of(world) + assert row["phase"] == "Succeeded" and row["attempts"] == 1, row + assert len(row["outputs"]["checks"]) == 4, row diff --git a/docs/21-usage-from-thanos.md b/docs/21-usage-from-thanos.md index 364d74b4..38643078 100644 --- a/docs/21-usage-from-thanos.md +++ b/docs/21-usage-from-thanos.md @@ -123,7 +123,7 @@ from the file. The file also creates the Namespace `cmapi-system` and the Servic | 6 (`examples/baseline/cmapi-reader-rbac.yaml:38-40`) | `quota.openshift.io`: `clusterresourcequotas` | get, list, watch | No code reads it today | | 7 (`examples/baseline/cmapi-reader-rbac.yaml:41-43`) | `redhatcop.redhat.io`: `groupsyncs`, `namespaceconfigs`, `groupconfigs` | get, list | No code reads it today | | 8 (`examples/baseline/cmapi-reader-rbac.yaml:44-47`) | `config.openshift.io`: `oauths`, `resourceNames: [cluster]` | get | No code reads it today | -| 9 (`examples/baseline/cmapi-reader-rbac.yaml:48-50`) | `argoproj.io`: `applications` | get, list, watch | The sync poll reads the root Application: `ArgoCdSignal.status` (`cmapi/src/cmapi/core/sync.py:191`), called from `cmapi/src/cmapi/jobs/watch_sync.py:168`; and cluster-onboard's preflight reads it once (`cmapi/src/cmapi/ops/__init__.py:372`, #763) | +| 9 (`examples/baseline/cmapi-reader-rbac.yaml:48-50`) | `argoproj.io`: `applications` | get, list, watch | The sync poll reads the root Application: `ArgoCdSignal.status` (`cmapi/src/cmapi/core/sync.py:191`), called from `cmapi/src/cmapi/jobs/watch_sync.py:168`; and cluster-onboard's preflight reads it once (`cmapi/src/cmapi/ops/__init__.py:375`, #763) | | 10 (`examples/baseline/cmapi-reader-rbac.yaml:51-53`) | `wgpolicyk8s.io`: `policyreports`, `clusterpolicyreports` | get, list, watch | The Policies tab's `ReportCache` watches both (`cmapi/src/cmapi/core/clients/policyreports.py:37`) | | 11 (`examples/baseline/cmapi-reader-rbac.yaml:54-56`) | `policies.kyverno.io`: `validatingpolicies`, `mutatingpolicies`, `generatingpolicies`, `deletingpolicies`, `imagevalidatingpolicies` | get, list, watch | Only `validatingpolicies` is read (`cmapi/src/cmapi/core/clients/policyreports.py:38`); the other four are not | | 12 (`examples/baseline/cmapi-reader-rbac.yaml:57-59`) | `kyverno.io`: `clusterpolicies`, `policies` | get, list | No code reads it today | @@ -217,7 +217,7 @@ they are kept. While any finding stands, `ThanosQuerier.query` refuses before it - **cluster-onboard's preflight** (#763) makes one instant query through the same `ThanosQuerier`: Prometheus's gauge `prometheus_tsdb_retention_limit_seconds` of job `prometheus-k8s` in `openshift-monitoring` (`cmapi/src/cmapi/capacity/retention.py:29`). The shortest replica counts, 0 is no time limit, and under 15 days, or no - answer, fails the step with that finding (`:32-46`, `cmapi/src/cmapi/ops/__init__.py:323-346`). The matchers keep out + answer, fails the step with that finding (`:32-46`, `cmapi/src/cmapi/ops/__init__.py:323-349`). The matchers keep out the user-workload Prometheus and the Thanos Ruler, which CRC reported at 86400 seconds beside the platform's 1296000 (`docs/reviews/2026-12-01-issue-763/README.md`, D1). - **A namespace create never queries Thanos.** Only a quota change on an existing namespace reads usage diff --git a/docs/citations.lock.json b/docs/citations.lock.json index 3bd61f75..b354df4f 100644 --- a/docs/citations.lock.json +++ b/docs/citations.lock.json @@ -1723,7 +1723,7 @@ "docs/21-usage-from-thanos.md|cmapi/src/cmapi/jobs/watch_sync.py|168-168": [ " app = ArgoCdSignal(reader, ctx.delivery.argocd_namespace," ], - "docs/21-usage-from-thanos.md|cmapi/src/cmapi/ops/__init__.py|323-346": [ + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/ops/__init__.py|323-349": [ "def _retention(ctx: Any, cid: str, st: Any) -> Checked:", " \"\"\"The Thanos Route answers and the platform Prometheus keeps at least MIN_RETENTION_DAYS (capacity/retention.py), read", " as the usage reads are. An instance that reads no usage (capacity.yaml usage.source none) never reaches Thanos, and its", @@ -1731,9 +1731,12 @@ " from cmapi.capacity.retention import MIN_RETENTION_DAYS, platform_retention_seconds", " from cmapi.capacity.usage import MetricsUnavailable", "", - " metrics = getattr(ctx.usage, \"metrics\", None) if ctx.usage.configured else None", - " if metrics is None:", + " if not ctx.usage.configured:", " return \"notApplicable\", \"capacity.yaml usage.source is none: cmapi reads no Thanos Querier\", {}", + " # `metrics` is not part of UsageSource: a configured source without it is a finding, never a check that does not apply.", + " metrics = getattr(ctx.usage, \"metrics\", None)", + " if metrics is None:", + " return \"finding\", \"the Thanos retention cannot be read: the usage source has no metrics reader\", {}", " try:", " seconds = platform_retention_seconds(metrics, cid)", " except MetricsUnavailable as exc:", @@ -1749,7 +1752,7 @@ " f\"to {MIN_RETENTION_DAYS}d or more in openshift-monitoring/cluster-monitoring-config\", facts)", " return \"check\", f\"Thanos answers; platform Prometheus keeps {kept}\", facts" ], - "docs/21-usage-from-thanos.md|cmapi/src/cmapi/ops/__init__.py|372-372": [ + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/ops/__init__.py|375-375": [ " app = ArgoCdSignal(client, ns, name).status(cid)" ], "docs/21-usage-from-thanos.md|cmapi/tests/service/test_reader_thanos_grants_724.py|428-470": [ diff --git a/docs/reviews/2026-12-01-issue-763/README.md b/docs/reviews/2026-12-01-issue-763/README.md index fb37ac0d..db0de683 100644 --- a/docs/reviews/2026-12-01-issue-763/README.md +++ b/docs/reviews/2026-12-01-issue-763/README.md @@ -163,3 +163,20 @@ two places. Not tested: a cluster with Argo CD (none is available without a cluster write); the reader's own token on CRC's Route for this query (the measurement above used an administrator's token; the reader's grant for `/api/v1/query` is #724's, proven there). + +## The coordinator's ruling (2026-12-01) + +Reviewer 1 was Codex, gpt-6.2-astra xhigh. Its findings are in `codex-report.md`, and it ran no test: its sandbox refused `sysctl`. +Reviewer 2 was a separate Opus 5.5 high agent, which did not write this code; its report is `r2-report.md`. The coordinator read +the production hunk of reviewer 2's `final.diff`. It applied the diff with `patch -p1 -F0`, and the four files are byte-identical +to reviewer 2's tested tree (`cmp`). + +| Finding | Ruling | +|---|---| +| R1 F1: the retention check is skipped when the configured usage source has no metrics reader | Accepted, narrowed to Low, and fixed, since the lines are this PR's. A configured source with no reader is now a finding. Only `ctx.usage.configured` decides whether the check applies. No production path reached it (`PromUsage.__init__` always sets `metrics`) | +| R1 F2: catch every exception at the read boundaries | Rejected. Premise checked: `run_step` (`core/operations.py:674-687`) sends an unexpected exception to `_retry_or_fail`, and the template retries 3 times (`cluster-onboard.yaml:13`). R1's catch-all would make a transient closed-client error a terminal failure. Reviewer 2's test fails with that catch-all applied | +| R1 F3: "High, credential disclosure" through sync, health or `BadResponse` text | Rejected: no path exists. Sync and health come from the Application's status. `BadResponse` carries only the Content-Type, cut to 60 characters, and a service-account JWS's protected header alone is longer than that. The missing redact-then-cut in `kube.py:221` is filed as #803 (Low, security) | +| R1 F4: a NUL in remote error text cannot be stored in JSONB | Narrowed to Low and pre-existing. It belongs in `thanos.parse_answer`, which other stores also feed. Filed in #804 with two other Low observations | + +Reviewer 2's run, on its tree: `test_onboard_preflight_763.py` 21 passed, `test_operations_26.py` 21 passed. The new F1 test fails on +head (`Succeeded == Failed`).