From 259db1c3ed07330762c39ed4058088f9f7f0be8f Mon Sep 17 00:00:00 2001 From: ephico2real2 Date: Tue, 1 Dec 2026 09:49:39 -0600 Subject: [PATCH 1/4] #26: the built-in operations engine and the Operations API (criterion 3, first slice) The built-in engine runs each operation template's steps in the cmapi worker, as jobs of kind operation_step, with their state in PostgreSQL (migration 0013: operations, operation_steps). Templates: tiers-rerender and rebuild-verify end to end; reconcile and cluster-onboard as far as what they need is built (#761, #762, #763, #765). Routes: POST, GET /api/v1/operations, GET /api/v1/operations/{id}, POST /api/v1/operations/{id}:cancel, each needing operations:run where the run acts. Steps open ordinary requests as svc-cmapi-workflows on behalf of the starter, retry as the template's retry block says, survive a dead worker by the job lease and a per-row Idempotency-Key, and an engine with no adapter answers 503 operations-engine-unavailable. --- cmapi/pyproject.toml | 2 +- cmapi/src/cmapi/contract/samples.json | 956 ++++++++++++------ cmapi/src/cmapi/core/context.py | 6 +- cmapi/src/cmapi/core/db/__init__.py | 2 +- .../db/migrations/versions/0013_operations.py | 109 ++ cmapi/src/cmapi/core/db/models.py | 67 ++ cmapi/src/cmapi/core/docs.py | 6 + cmapi/src/cmapi/core/observability.py | 3 + cmapi/src/cmapi/core/operations.py | 746 ++++++++++++++ cmapi/src/cmapi/core/pipeline.py | 16 +- cmapi/src/cmapi/core/ports.py | 12 +- cmapi/src/cmapi/core/problem_docs.py | 4 + cmapi/src/cmapi/jobs/__init__.py | 5 +- cmapi/src/cmapi/main.py | 4 +- cmapi/src/cmapi/ops/__init__.py | 317 ++++++ .../cmapi/ops/templates/cluster-onboard.yaml | 19 + .../cmapi/ops/templates/rebuild-verify.yaml | 15 + cmapi/src/cmapi/ops/templates/reconcile.yaml | 16 + .../cmapi/ops/templates/tiers-rerender.yaml | 19 + cmapi/src/cmapi/routers/operations.py | 317 ++++++ cmapi/src/cmapi/worker.py | 3 + cmapi/tests/service/conftest.py | 7 +- cmapi/tests/service/test_api_samples.py | 20 +- cmapi/tests/service/test_operations_26.py | 492 +++++++++ 24 files changed, 2833 insertions(+), 330 deletions(-) create mode 100644 cmapi/src/cmapi/core/db/migrations/versions/0013_operations.py create mode 100644 cmapi/src/cmapi/core/operations.py create mode 100644 cmapi/src/cmapi/ops/__init__.py create mode 100644 cmapi/src/cmapi/ops/templates/cluster-onboard.yaml create mode 100644 cmapi/src/cmapi/ops/templates/rebuild-verify.yaml create mode 100644 cmapi/src/cmapi/ops/templates/reconcile.yaml create mode 100644 cmapi/src/cmapi/ops/templates/tiers-rerender.yaml create mode 100644 cmapi/src/cmapi/routers/operations.py create mode 100644 cmapi/tests/service/test_operations_26.py diff --git a/cmapi/pyproject.toml b/cmapi/pyproject.toml index 4b09df67..3ea6d635 100644 --- a/cmapi/pyproject.toml +++ b/cmapi/pyproject.toml @@ -40,7 +40,7 @@ where = ["src"] [tool.setuptools.package-data] cmapi = ["core/db/migrations/*.py", "core/db/migrations/versions/*.py", "core/db/alembic.ini", "contract/changelog.json", "contract/samples.json", - "tools/reference_instance/*.yaml"] + "tools/reference_instance/*.yaml", "ops/templates/*.yaml"] [tool.pytest.ini_options] testpaths = ["tests"] diff --git a/cmapi/src/cmapi/contract/samples.json b/cmapi/src/cmapi/contract/samples.json index 045bd3e2..e9e3d2c6 100644 --- a/cmapi/src/cmapi/contract/samples.json +++ b/cmapi/src/cmapi/contract/samples.json @@ -14,7 +14,7 @@ "body": { "code": "precondition-failed", "detail": "If-Match does not list the current ETag of this answer: read it again", - "etag": "13b13a438dedd73906000f898819ba13", + "etag": "26d4367b57e62464bfa3089775962d25", "status": 412, "title": "precondition failed", "type": "https://cmapi.ephico2real.com/problems/precondition-failed" @@ -151,7 +151,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "If-Match": "\"d71165fa38f59dd4\"" + "If-Match": "\"1b59766bf9a3bbe7\"" }, "method": "PATCH", "path": "/api/v1/clusters/NOPE/namespaces/payments-dev?dryRun=true" @@ -177,7 +177,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "If-Match": "\"d71165fa38f59dd4\"" + "If-Match": "\"1b59766bf9a3bbe7\"" }, "method": "PATCH", "path": "/api/v1/clusters/CRC/namespaces/payments-dev?dryRun=true" @@ -203,7 +203,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "If-Match": "\"d71165fa38f59dd4\"" + "If-Match": "\"1b59766bf9a3bbe7\"" }, "method": "PATCH", "path": "/api/v1/clusters/CRC/namespaces/payments-dev" @@ -229,7 +229,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "If-Match": "\"d71165fa38f59dd4\"" + "If-Match": "\"1b59766bf9a3bbe7\"" }, "method": "PATCH", "path": "/api/v1/clusters/CRC/namespaces/not-there-dev?dryRun=true" @@ -262,7 +262,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "If-Match": "\"d71165fa38f59dd4\"" + "If-Match": "\"1b59766bf9a3bbe7\"" }, "method": "PATCH", "path": "/api/v1/clusters/CRC/namespaces/payments-dev?dryRun=true" @@ -311,7 +311,7 @@ "tier": "small" }, "headers": { - "If-Match": "\"d71165fa38f59dd4\"" + "If-Match": "\"1b59766bf9a3bbe7\"" }, "method": "PATCH", "path": "/api/v1/clusters/CRC/namespaces/payments-dev?dryRun=true" @@ -331,6 +331,29 @@ "status": 401 } }, + "operations_cancel:invalid-transition": { + "operationId": "operations_cancel", + "request": { + "headers": { + "Authorization": "Bearer $TOKEN" + }, + "method": "POST", + "path": "/api/v1/operations/op-20261201-7fead487:cancel" + }, + "response": { + "body": { + "code": "invalid-transition", + "detail": "op-20261201-7fead487 ended Stopped", + "state": "Stopped", + "status": 409, + "title": "invalid transition", + "type": "https://cmapi.ephico2real.com/problems/invalid-transition" + }, + "contentType": "application/problem+json", + "headers": {}, + "status": 409 + } + }, "quotas_export:invalid-sort": { "operationId": "quotas_export", "request": { @@ -366,7 +389,7 @@ "response": { "body": { "log": [ - "80f4f1ba Merge cmapi/CRC/req-20261127-0001", + "513f40b0 Merge cmapi/CRC/req-20261201-0001", "aaaaaaaa initial" ] }, @@ -435,18 +458,18 @@ "cpuThrottledPeriods": null, "cpuThrottledSeconds": null, "cpuUsageSeconds": null, - "measuredAt": 1795813135.55039, + "measuredAt": 1796137976.883476, "memoryBytes": null, "memoryLimitBytes": null } ], "database": { - "connections": 9, + "connections": 13, "connectionsMax": 100, "oldestTransactionSeconds": 0.0, "poolInUse": 0, "poolSize": 5, - "sizeBytes": 10173463, + "sizeBytes": 9018391, "walBytes": 83886080 }, "instance": "nonprod", @@ -458,7 +481,7 @@ "target": "under 10 min", "targetStatus": "proposed", "unit": "seconds", - "value": 0.332343 + "value": 0.27096 }, { "id": "lead-time-approved-p90", @@ -545,7 +568,7 @@ "body": { "paused": true, "reason": "incident 1234", - "setAt": "2026-11-27T20:59:01.388335+00:00", + "setAt": "2026-12-01T15:13:07.995528+00:00", "setBy": "ada" }, "contentType": "application/json", @@ -580,6 +603,13 @@ "name": "core", "version": "0.2.0" }, + { + "core": true, + "disabledEnvironments": [], + "enabled": true, + "name": "operations", + "version": "0.2.0" + }, { "core": true, "disabledEnvironments": [], @@ -668,7 +698,7 @@ "approval": { "approvals": [ { - "at": "2026-11-27T20:59:06.043703Z", + "at": "2026-12-01T15:13:18.601698Z", "comment": "", "relayedBy": null, "sub": "sub-amy", @@ -692,77 +722,77 @@ ], "timeoutHours": 8 }, - "baseSha": "479aab8dca85cfbd40e9c4c4b791535b8a69d428", + "baseSha": "4afd09a1a70bbf2c03d8d2253e817b57a5812c0a", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:05.959028Z", + "createdAt": "2026-12-01T15:13:18.496644Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:05.969036Z", + "at": "2026-12-01T15:13:18.510655Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", "status": "pending_approval" }, { - "at": "2026-11-27T20:59:06.061082Z", + "at": "2026-12-01T15:13:18.626143Z", "by": "amy", "event": "approval", "note": "", "status": "pending_approval" }, { - "at": "2026-11-27T20:59:06.073368Z", + "at": "2026-12-01T15:13:18.644510Z", "by": "amy", "event": "approved", "note": "approval count met", "status": "approved" }, { - "at": "2026-11-27T20:59:06.208729Z", + "at": "2026-12-01T15:13:18.898838Z", "by": "cmapi-bot", "event": "branch_pushed", - "note": "cmapi/CRC/req-20261127-0008 at a539f2ec on 479aab8d (created)", + "note": "cmapi/CRC/req-20261201-0008 at f33469a0 on 4afd09a1 (created)", "status": "approved" }, { - "at": "2026-11-27T20:59:06.335675Z", + "at": "2026-12-01T15:13:19.140751Z", "by": "cmapi-bot", "event": "pr_opened", - "note": "cmapi/CRC/req-20261127-0008 #7", + "note": "cmapi/CRC/req-20261201-0008 #7", "status": "pr_open" }, { - "at": "2026-11-27T20:59:06.426044Z", + "at": "2026-12-01T15:13:19.339159Z", "by": "ci", "event": "ci", "note": "kubeconform: pass; kyverno: pass; cmapi check: pass", "status": "pr_open" }, { - "at": "2026-11-27T20:59:06.516666Z", + "at": "2026-12-01T15:13:19.519914Z", "by": "worker", "event": "merge_verified", - "note": "merged a539f2ec; the folder at it is the plan's", + "note": "merged f33469a0; the folder at it is the plan's", "status": "pr_open" }, { - "at": "2026-11-27T20:59:06.526607Z", + "at": "2026-12-01T15:13:19.535474Z", "by": "cmapi-bot", "event": "merged", - "note": "merged a539f2ec", + "note": "merged f33469a0", "status": "merged" }, { - "at": "2026-11-27T20:59:06.642678Z", + "at": "2026-12-01T15:13:19.737680Z", "by": "cmapi-deliverer", "event": "prune_pending", "note": "Prune=confirm: waiting for an operator to confirm the prune", "status": "awaiting_prune" }, { - "at": "2026-11-27T20:59:07.179743Z", + "at": "2026-12-01T15:13:20.879794Z", "by": "opal", "event": "prune_confirm", "note": "operator confirmed the prune", @@ -779,22 +809,22 @@ "instance": "nonprod", "justification": null, "links": { - "events": "/api/v1/requests/req-20261127-0008/events", + "events": "/api/v1/requests/req-20261201-0008/events", "pr": "https://git.test/pulls/7", - "self": "/api/v1/requests/req-20261127-0008" + "self": "/api/v1/requests/req-20261201-0008" }, - "mergeSha": "a539f2ec", + "mergeSha": "f33469a0", "namespace": "search-dev", "planHash": "c490196334dad591c3196aa59224d119861392145360aee1d428c93109235dbe", "plugin": "namespaces", "pr": { - "branch": "cmapi/CRC/req-20261127-0008", - "head": "a539f2ec", + "branch": "cmapi/CRC/req-20261201-0008", + "head": "f33469a0", "number": 7, "url": "https://git.test/pulls/7" }, "reason": null, - "requestId": "req-20261127-0008", + "requestId": "req-20261201-0008", "requester": { "automated": false, "requester": { @@ -812,7 +842,7 @@ "submittedByClient": null }, "status": "awaiting_prune", - "updatedAt": "2026-11-27T20:59:07.078985Z" + "updatedAt": "2026-12-01T15:13:20.605642Z" }, "contentType": "application/json", "headers": {}, @@ -834,7 +864,7 @@ "body": { "paused": false, "reason": "incident 1234 closed", - "setAt": "2026-11-27T20:59:01.394640+00:00", + "setAt": "2026-12-01T15:13:07.918684+00:00", "setBy": "ada" }, "contentType": "application/json", @@ -875,7 +905,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "dc5937b4-07db-42a9-9ff8-e9f04936f012" + "Idempotency-Key": "40ae86b4-eb22-4705-936f-26a3b8a972ec" }, "method": "POST", "path": "/api/v1/clusters/CRC/namespaces/abc-rnd:adopt" @@ -910,7 +940,7 @@ ], "timeoutHours": 8 }, - "baseSha": "ca16e8cc000b1d1f2305f2259948a58c6035e62a", + "baseSha": "e33ccf390a5fc196bb270e81c03752e59a2385f7", "beyondTier": { "approvals": [ { @@ -928,11 +958,11 @@ ] }, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:16.210356Z", + "createdAt": "2026-12-01T15:13:36.361990Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:16.232805Z", + "at": "2026-12-01T15:13:36.396117Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 3)]", @@ -948,16 +978,16 @@ "instance": "nonprod", "justification": "Bring abc-rnd under cmapi", "links": { - "events": "/api/v1/requests/req-20261127-0016/events", - "self": "/api/v1/requests/req-20261127-0016" + "events": "/api/v1/requests/req-20261201-0016/events", + "self": "/api/v1/requests/req-20261201-0016" }, "mergeSha": null, "namespace": "abc-rnd", - "planHash": "7630777637466bdb231a248db34b6e67aafe718082ab15403db130f4b28b73ee", + "planHash": "49c73db929d9a990a0acdf6bd9c262076939964693858d51f17c7de254db4939", "plugin": "adoption", "pr": null, "reason": null, - "requestId": "req-20261127-0016", + "requestId": "req-20261201-0016", "requester": { "automated": false, "requester": { @@ -975,7 +1005,7 @@ "submittedByClient": null }, "status": "pending_approval", - "updatedAt": "2026-11-27T20:59:16.134586Z" + "updatedAt": "2026-12-01T15:13:36.123405Z" }, "contentType": "application/json", "headers": {}, @@ -1411,7 +1441,7 @@ "body": { "clusters": [ { - "asOf": "2026-11-27T20:59:00Z", + "asOf": "2026-12-01T15:13:00Z", "basis": "simulated", "boundBy": "cpu", "clusterId": "CRC", @@ -1564,7 +1594,7 @@ }, "contentType": "application/json", "headers": { - "etag": "\"1966474983b788a05effcc14deb90586\"" + "etag": "\"b71217a3b2368e40b964c0a3511fdad3\"" }, "status": 200 } @@ -1622,7 +1652,7 @@ "detail": null, "source": "api", "state": "ok", - "takenAt": "2026-11-27T20:30:00Z" + "takenAt": "2026-12-01T15:00:00Z" }, "staleAfterSeconds": 3600 }, @@ -1649,11 +1679,11 @@ }, "response": { "body": { - "asOf": "2026-11-27T20:59:13Z", + "asOf": "2026-12-01T15:13:31Z", "clusterId": "CRC", "excluded": [], - "expiresAt": "2026-11-27T21:14:13.469598Z", - "placementId": "pl-20261127-7658a163", + "expiresAt": "2026-12-01T15:28:31.965297Z", + "placementId": "pl-20261201-52bb3c04", "ranked": [ { "basis": "simulated", @@ -1682,7 +1712,7 @@ }, "reserved": true, "score": 29, - "snapshotAt": "2026-11-27T20:30:00Z" + "snapshotAt": "2026-12-01T15:00:00Z" } ], "request": { @@ -1722,7 +1752,7 @@ }, "response": { "body": { - "asOf": "2026-11-27T20:59:13Z", + "asOf": "2026-12-01T15:13:31Z", "clusterId": null, "excluded": [], "expiresAt": null, @@ -1755,7 +1785,7 @@ }, "reserved": false, "score": 39, - "snapshotAt": "2026-11-27T20:30:00Z" + "snapshotAt": "2026-12-01T15:00:00Z" } ], "request": { @@ -1807,7 +1837,7 @@ "body": { "items": [ { - "checkedAt": "2026-11-27T20:58:53.069187Z", + "checkedAt": "2026-12-01T15:12:54.018046Z", "clusterId": "CRC", "environment": "dev", "findingDetails": [], @@ -1816,11 +1846,11 @@ "labels": { "region": "us-central" }, - "lastProbeAt": "2026-11-27T20:58:53.069187Z", + "lastProbeAt": "2026-12-01T15:12:54.018046Z", "secretName": "cmapi-cluster-crc", "serverVersion": "v1.35.6-fake", "status": "connected", - "statusSince": "2026-11-27T20:58:53.069187Z", + "statusSince": "2026-12-01T15:12:54.018046Z", "tokenExpiresAt": null, "trust": { "downgrade": false, @@ -2190,7 +2220,7 @@ }, "response": { "body": { - "checkedAt": "2026-11-27T20:58:53.587291Z", + "checkedAt": "2026-12-01T15:12:54.578527Z", "clusterId": "CRC", "environment": "dev", "findingDetails": [], @@ -2199,11 +2229,11 @@ "labels": { "region": "us-central" }, - "lastProbeAt": "2026-11-27T20:58:53.587291Z", + "lastProbeAt": "2026-12-01T15:12:54.578527Z", "secretName": "cmapi-cluster-crc", "serverVersion": "v1.35.6-fake", "status": "connected", - "statusSince": "2026-11-27T20:58:53.069187Z", + "statusSince": "2026-12-01T15:12:54.018046Z", "tokenExpiresAt": null, "trust": { "downgrade": false, @@ -2304,11 +2334,11 @@ ], "app": null, "clusterId": "CRC", - "created": "2026-11-27", + "created": "2026-12-01", "daysLeft": 21, "env": "dev", - "expiresAt": "2026-12-18", - "graceEnds": "2026-12-25", + "expiresAt": "2026-12-22", + "graceEnds": "2026-12-29", "lifetimeDays": 21, "name": "notes-dev", "noticesSent": 0, @@ -2323,15 +2353,15 @@ ], "app": null, "clusterId": "CRC", - "created": "2026-11-27", + "created": "2026-12-01", "daysLeft": 27, "env": "dev", - "expiresAt": "2026-12-24", - "graceEnds": "2026-12-31", + "expiresAt": "2026-12-28", + "graceEnds": "2027-01-04", "lifetimeDays": 27, "name": "sprint-dev", "noticesSent": 0, - "openRequest": "req-20261127-0013", + "openRequest": "req-20261201-0013", "state": "active", "team": "payments" }, @@ -2341,7 +2371,7 @@ ], "app": null, "clusterId": "CRC", - "created": "2026-11-27", + "created": "2026-12-01", "daysLeft": null, "env": "dev", "expiresAt": null, @@ -2349,7 +2379,7 @@ "lifetimeDays": null, "name": "payments-dev", "noticesSent": 0, - "openRequest": "req-20261127-0002", + "openRequest": "req-20261201-0002", "state": "permanent", "team": "payments" } @@ -2379,7 +2409,7 @@ ] } }, - "today": "2026-11-27" + "today": "2026-12-01" }, "contentType": "application/json", "headers": {}, @@ -2402,7 +2432,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "c192b0c3-19ff-428c-9dd7-173c546eecf9" + "Idempotency-Key": "98e7dc4c-2964-491f-a744-8e30136a914c" }, "method": "POST", "path": "/api/v1/clusters/CRC/namespaces" @@ -2427,11 +2457,11 @@ "baseSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:54.441022Z", + "createdAt": "2026-12-01T15:12:55.670320Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:54.488801Z", + "at": "2026-12-01T15:12:55.724895Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", @@ -2448,16 +2478,16 @@ "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0001/events", - "self": "/api/v1/requests/req-20261127-0001" + "events": "/api/v1/requests/req-20261201-0001/events", + "self": "/api/v1/requests/req-20261201-0001" }, "mergeSha": null, "namespace": "payments-dev", - "planHash": "9fed510537c2c36b3dc18a5b461ebfac4c2f1b7dfc2a61a394afd47b96624c09", + "planHash": "4e9af3fc1f212f0387b6958adccca82242cc53b7fd67192be64529da18a31563", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0001", + "requestId": "req-20261201-0001", "requester": { "automated": false, "requester": { @@ -2475,7 +2505,7 @@ "submittedByClient": null }, "status": "approved", - "updatedAt": "2026-11-27T20:58:54.385979Z" + "updatedAt": "2026-12-01T15:12:55.450056Z" }, "contentType": "application/json", "headers": {}, @@ -2661,8 +2691,8 @@ "request": { "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "80e6b56d-0067-4f87-9d9a-51ccedf5e15d", - "If-Match": "\"2482d135c8aae7da\"" + "Idempotency-Key": "40a8770b-3f6d-449b-96a9-32cfedc91435", + "If-Match": "\"ca777167c63ddb5e\"" }, "method": "DELETE", "path": "/api/v1/clusters/CRC/namespaces/search-dev" @@ -2694,14 +2724,14 @@ ], "timeoutHours": 8 }, - "baseSha": "479aab8dca85cfbd40e9c4c4b791535b8a69d428", + "baseSha": "4afd09a1a70bbf2c03d8d2253e817b57a5812c0a", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:05.959028Z", + "createdAt": "2026-12-01T15:13:18.496644Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:05.969036Z", + "at": "2026-12-01T15:13:18.510655Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", @@ -2718,8 +2748,8 @@ "instance": "nonprod", "justification": null, "links": { - "events": "/api/v1/requests/req-20261127-0008/events", - "self": "/api/v1/requests/req-20261127-0008" + "events": "/api/v1/requests/req-20261201-0008/events", + "self": "/api/v1/requests/req-20261201-0008" }, "mergeSha": null, "namespace": "search-dev", @@ -2727,7 +2757,7 @@ "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0008", + "requestId": "req-20261201-0008", "requester": { "automated": false, "requester": { @@ -2745,7 +2775,7 @@ "submittedByClient": null }, "status": "pending_approval", - "updatedAt": "2026-11-27T20:59:05.871308Z" + "updatedAt": "2026-12-01T15:13:18.239084Z" }, "contentType": "application/json", "headers": {}, @@ -2756,7 +2786,7 @@ "request": { "headers": { "Authorization": "Bearer $TOKEN", - "If-Match": "\"2482d135c8aae7da\"" + "If-Match": "\"ca777167c63ddb5e\"" }, "method": "DELETE", "path": "/api/v1/clusters/CRC/namespaces/search-dev?dryRun=true" @@ -2802,7 +2832,7 @@ "clusters/CRC/namespaces/search-dev/resourcequota-search-dev-quota.yaml": "removed", "clusters/CRC/namespaces/search-dev/token-issuer-rolebinding.yaml": "removed" }, - "etag": "2482d135c8aae7da", + "etag": "ca777167c63ddb5e", "files": {}, "findings": [], "metadata": null, @@ -2839,8 +2869,8 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "18098166-c5a6-473f-8dee-6bfe47dcc67b", - "If-Match": "\"35aa9051ec1a5e15\"" + "Idempotency-Key": "056db2fd-eee9-4c6f-9f60-1748557cb407", + "If-Match": "\"f64411040f43a72b\"" }, "method": "POST", "path": "/api/v1/clusters/CRC/namespaces/sprint-dev/expiration:extend" @@ -2861,14 +2891,14 @@ "slots": [], "timeoutHours": 8 }, - "baseSha": "3e8ad5005d0b72c1869d34e49299f12f1b03b5b5", + "baseSha": "fff48c23f20c46278e17f5d0f1143fbe488baf9f", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:59.299718Z", + "createdAt": "2026-12-01T15:13:04.324648Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:59.374768Z", + "at": "2026-12-01T15:13:04.427407Z", "by": "ola", "event": "plan_auto_approved", "note": "none-required", @@ -2885,16 +2915,16 @@ "instance": "nonprod", "justification": "Another sprint", "links": { - "events": "/api/v1/requests/req-20261127-0004/events", - "self": "/api/v1/requests/req-20261127-0004" + "events": "/api/v1/requests/req-20261201-0004/events", + "self": "/api/v1/requests/req-20261201-0004" }, "mergeSha": null, "namespace": "sprint-dev", - "planHash": "fd55be2f5fa99dbc2d1abb18df09cb134f778a075ba88a80375fd4004efd3024", + "planHash": "94647a196d1eadd68a6e7f32e52ece621b84b432d66fe07079e993d28f81f1a4", "plugin": "namespaces", "pr": null, "reason": "expiration:extend", - "requestId": "req-20261127-0004", + "requestId": "req-20261201-0004", "requester": { "automated": false, "requester": { @@ -2912,7 +2942,7 @@ "submittedByClient": null }, "status": "approved", - "updatedAt": "2026-11-27T20:58:59.274371Z" + "updatedAt": "2026-12-01T15:13:04.155474Z" }, "contentType": "application/json", "headers": {}, @@ -2926,7 +2956,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "If-Match": "\"073bd8faea2248ce\"" + "If-Match": "\"917c7a62361f9e08\"" }, "method": "POST", "path": "/api/v1/clusters/CRC/namespaces/sprint-dev/expiration:extend?dryRun=true" @@ -2964,9 +2994,9 @@ "changes": { "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed" }, - "etag": "073bd8faea2248ce", + "etag": "917c7a62361f9e08", "files": { - "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: sprint-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2026-12-31'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" + "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: sprint-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2027-01-04'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" }, "findings": [], "metadata": null, @@ -2974,7 +3004,7 @@ "annotations": {}, "labels": {} }, - "planHash": "45af0b7fd4a2f76619cf99f889c9d19edb65d059722e4e459866be1859ec697b", + "planHash": "1f9cb50d801c839f9d81f17c0bdfa248ec47c1aa58de25faff503e675da9a4f6", "requester": { "automated": false, "requester": { @@ -3011,19 +3041,19 @@ "annotations": { "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", "cmapi.net/instance": "nonprod", - "cmapi.net/request-id": "req-20261127-0001", + "cmapi.net/request-id": "req-20261201-0001", "cmapi.net/requested-by": "ola@ephico2real.com", "cmapi.net/team-dl": "payments-team@ephico2real.com" }, "clusterId": "CRC", "env": "dev", - "etag": "d71165fa38f59dd4", + "etag": "1b59766bf9a3bbe7", "expiresAt": null, "git": { "annotations": { "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", "cmapi.net/instance": "nonprod", - "cmapi.net/request-id": "req-20261127-0001", + "cmapi.net/request-id": "req-20261201-0001", "cmapi.net/requested-by": "ola@ephico2real.com", "cmapi.net/team-dl": "payments-team@ephico2real.com" }, @@ -3136,7 +3166,7 @@ }, "contentType": "application/json", "headers": { - "etag": "\"d71165fa38f59dd4\"" + "etag": "\"1b59766bf9a3bbe7\"" }, "status": 200 } @@ -3159,7 +3189,7 @@ "annotations": { "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", "cmapi.net/instance": "nonprod", - "cmapi.net/request-id": "req-20261127-0001", + "cmapi.net/request-id": "req-20261201-0001", "cmapi.net/requested-by": "ola@ephico2real.com", "cmapi.net/team-dl": "payments-team@ephico2real.com" }, @@ -3206,8 +3236,8 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "7a9dd47f-ef0b-4ac6-8c3b-ee6c725a7bd6", - "If-Match": "\"073bd8faea2248ce\"" + "Idempotency-Key": "97ee74f3-bc78-44aa-9201-2c6099277c2d", + "If-Match": "\"917c7a62361f9e08\"" }, "method": "POST", "path": "/api/v1/clusters/CRC/namespaces/sprint-dev/expiration:makePermanent" @@ -3240,14 +3270,14 @@ ], "timeoutHours": 8 }, - "baseSha": "ac1e81f58836d7f8a36ae1cdff67fe152c02fd02", + "baseSha": "feb3ec3f7d9810aff0adcce6cd4aa4a92b85fefd", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:12.604388Z", + "createdAt": "2026-12-01T15:13:30.640365Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:12.676330Z", + "at": "2026-12-01T15:13:30.783091Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", @@ -3264,16 +3294,16 @@ "instance": "nonprod", "justification": "In production use", "links": { - "events": "/api/v1/requests/req-20261127-0013/events", - "self": "/api/v1/requests/req-20261127-0013" + "events": "/api/v1/requests/req-20261201-0013/events", + "self": "/api/v1/requests/req-20261201-0013" }, "mergeSha": null, "namespace": "sprint-dev", - "planHash": "b2e28a66559008829930431df326dc1a91864514d67474024f7fae04298cdfd0", + "planHash": "7e351d77c635272d0628a10556f6e2a86b180aac067848e44417651013b36b00", "plugin": "namespaces", "pr": null, "reason": "expiration:makePermanent", - "requestId": "req-20261127-0013", + "requestId": "req-20261201-0013", "requester": { "automated": false, "requester": { @@ -3291,7 +3321,7 @@ "submittedByClient": null }, "status": "pending_approval", - "updatedAt": "2026-11-27T20:59:12.577772Z" + "updatedAt": "2026-12-01T15:13:30.497696Z" }, "contentType": "application/json", "headers": {}, @@ -3305,7 +3335,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "If-Match": "\"073bd8faea2248ce\"" + "If-Match": "\"917c7a62361f9e08\"" }, "method": "POST", "path": "/api/v1/clusters/CRC/namespaces/sprint-dev/expiration:makePermanent?dryRun=true" @@ -3355,7 +3385,7 @@ "changes": { "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed" }, - "etag": "073bd8faea2248ce", + "etag": "917c7a62361f9e08", "files": { "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: sprint-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" }, @@ -3365,7 +3395,7 @@ "annotations": {}, "labels": {} }, - "planHash": "4e2f1ef26fab90b27dc41e0fd496b8e8006b2742bc192f09a8dea81ffefb031b", + "planHash": "70bbacf492d9d66211a7592e0a14a89dcac6317e2376b7674bc0ee2f01e6b85f", "requester": { "automated": false, "requester": { @@ -3393,12 +3423,12 @@ "request": { "body": { "justification": "A load test this sprint", - "until": "2026-12-18" + "until": "2026-12-22" }, "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "65f63b9e-7fec-4286-bbf6-25d1f1091004", - "If-Match": "\"2763b4eb2ce407b5\"" + "Idempotency-Key": "83f4857b-0e55-4198-b675-30f07238686d", + "If-Match": "\"fc99df943d89d3a5\"" }, "method": "POST", "path": "/api/v1/clusters/CRC/namespaces/notes-dev/expiration:set" @@ -3419,14 +3449,14 @@ "slots": [], "timeoutHours": 8 }, - "baseSha": "2b2f51e093acbd69fb6b2fb05c5acbef76ecb749", + "baseSha": "efebfc8bb689241a62f847984e2721f3262dc61f", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:11.598086Z", + "createdAt": "2026-12-01T15:13:28.971548Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:11.671849Z", + "at": "2026-12-01T15:13:29.129136Z", "by": "ola", "event": "plan_auto_approved", "note": "none-required", @@ -3443,16 +3473,16 @@ "instance": "nonprod", "justification": "A load test this sprint", "links": { - "events": "/api/v1/requests/req-20261127-0012/events", - "self": "/api/v1/requests/req-20261127-0012" + "events": "/api/v1/requests/req-20261201-0012/events", + "self": "/api/v1/requests/req-20261201-0012" }, "mergeSha": null, "namespace": "notes-dev", - "planHash": "9b232cebe5e7f6c7322d8707f3ec6242b41b2249fb7589b4e77ef7413540258c", + "planHash": "e03939885c418d98170f15ddf95c7ff62ccfa9557329000845f1b4171c55cc30", "plugin": "namespaces", "pr": null, "reason": "expiration:set", - "requestId": "req-20261127-0012", + "requestId": "req-20261201-0012", "requester": { "automated": false, "requester": { @@ -3470,7 +3500,7 @@ "submittedByClient": null }, "status": "approved", - "updatedAt": "2026-11-27T20:59:11.573014Z" + "updatedAt": "2026-12-01T15:13:28.855961Z" }, "contentType": "application/json", "headers": {}, @@ -3481,11 +3511,11 @@ "request": { "body": { "justification": "A load test this sprint", - "until": "2026-12-18" + "until": "2026-12-22" }, "headers": { "Authorization": "Bearer $TOKEN", - "If-Match": "\"2763b4eb2ce407b5\"" + "If-Match": "\"fc99df943d89d3a5\"" }, "method": "POST", "path": "/api/v1/clusters/CRC/namespaces/notes-dev/expiration:set?dryRun=true" @@ -3523,9 +3553,9 @@ "changes": { "clusters/CRC/namespaces/notes-dev/namespace.yaml": "changed" }, - "etag": "2763b4eb2ce407b5", + "etag": "fc99df943d89d3a5", "files": { - "clusters/CRC/namespaces/notes-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: notes-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2026-12-18'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" + "clusters/CRC/namespaces/notes-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: notes-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2026-12-22'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" }, "findings": [], "metadata": null, @@ -3533,7 +3563,7 @@ "annotations": {}, "labels": {} }, - "planHash": "38d5d19ff384c206da94f3e9d1844ceeb7e15bedcd639467c71f7677117614a3", + "planHash": "9c1158dfa0d79c5c9f0c241dec6a32d5b2a292a37433713da86353035f89f39e", "requester": { "automated": false, "requester": { @@ -3565,8 +3595,8 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "d4e49281-9384-4e5c-ab97-2f611f6f43be", - "If-Match": "\"d71165fa38f59dd4\"" + "Idempotency-Key": "8ec948a8-feee-46b2-8da8-adccdd6d007b", + "If-Match": "\"1b59766bf9a3bbe7\"" }, "method": "PATCH", "path": "/api/v1/clusters/CRC/namespaces/payments-dev" @@ -3599,14 +3629,14 @@ ], "timeoutHours": 8 }, - "baseSha": "80f4f1badad17a36a1e6c5d25834f76fef11435b", + "baseSha": "513f40b0ee251859ba80791976ccc3addcfdf1ba", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:55.923726Z", + "createdAt": "2026-12-01T15:12:57.455807Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:56.005112Z", + "at": "2026-12-01T15:12:57.536560Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", @@ -3623,16 +3653,16 @@ "instance": "nonprod", "justification": "Load test next sprint", "links": { - "events": "/api/v1/requests/req-20261127-0002/events", - "self": "/api/v1/requests/req-20261127-0002" + "events": "/api/v1/requests/req-20261201-0002/events", + "self": "/api/v1/requests/req-20261201-0002" }, "mergeSha": null, "namespace": "payments-dev", - "planHash": "df5602a2038007a6de28e19adf060fd6b5f8fb3d5b86637f790b31efdc510039", + "planHash": "7aebcbffedf4cef6b095bd7594ab08df7c4f3964ede6f8138b15048c990b9ed3", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0002", + "requestId": "req-20261201-0002", "requester": { "automated": false, "requester": { @@ -3650,7 +3680,7 @@ "submittedByClient": null }, "status": "pending_approval", - "updatedAt": "2026-11-27T20:58:55.904486Z" + "updatedAt": "2026-12-01T15:12:57.263260Z" }, "contentType": "application/json", "headers": {}, @@ -3671,7 +3701,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "If-Match": "\"d71165fa38f59dd4\"" + "If-Match": "\"1b59766bf9a3bbe7\"" }, "method": "PATCH", "path": "/api/v1/clusters/CRC/namespaces/payments-dev?dryRun=true" @@ -3712,7 +3742,7 @@ "clusters/CRC/namespaces/payments-dev/namespace.yaml": "changed", "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "changed" }, - "etag": "d71165fa38f59dd4", + "etag": "1b59766bf9a3bbe7", "files": { "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-cpu\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: medium\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 44fd85f2d7cb\nspec:\n limits:\n - type: Container\n defaultRequest:\n cpu: 100m\n default:\n cpu: 500m\n max:\n cpu: '4'\n", "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-memory\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: medium\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 44fd85f2d7cb\nspec:\n limits:\n - type: Container\n defaultRequest:\n memory: 256Mi\n default:\n memory: 512Mi\n max:\n memory: 8Gi\n", @@ -3737,7 +3767,7 @@ } } }, - "planHash": "13472056b96785ab1172af6108e4ab3bda9d07c0663fd117bcb98fe6d7c3c4d8", + "planHash": "3409c7cab6683ab5c6280d06452d63623f90b3231e915bb31b5b4efee19b9adc", "requester": { "automated": false, "requester": { @@ -3789,6 +3819,277 @@ "status": 200 } }, + "operations_cancel": { + "request": { + "headers": { + "Authorization": "Bearer $TOKEN" + }, + "method": "POST", + "path": "/api/v1/operations/op-20261201-7fead487:cancel" + }, + "response": { + "body": { + "cancelRequestedAt": "2026-12-01T15:13:36.705960Z", + "cancelRequestedBy": "opal", + "engine": "builtin", + "environments": [ + "dev" + ], + "finishedAt": null, + "links": { + "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + "self": "/api/v1/operations/op-20261201-7fead487" + }, + "operationId": "op-20261201-7fead487", + "parameters": { + "batchSize": 20, + "environments": [ + "dev" + ], + "maxOpenPerCluster": 5, + "tier": "small" + }, + "phase": "Running", + "progress": { + "finished": 0, + "phases": { + "Running": 1 + }, + "total": 1 + }, + "report": null, + "runName": "op-20261201-7fead487", + "startedAt": "2026-12-01T15:13:36.696696Z", + "startedBy": "opal", + "steps": [ + { + "attempts": 0, + "clusterId": "", + "finishedAt": null, + "item": "", + "lastError": null, + "outputs": null, + "phase": "Running", + "startedAt": "2026-12-01T15:13:36.480026Z", + "step": "select-outdated" + } + ], + "template": "tiers-rerender" + }, + "contentType": "application/json", + "headers": {}, + "status": 200 + } + }, + "operations_get_operation": { + "request": { + "headers": { + "Authorization": "Bearer $TOKEN" + }, + "method": "GET", + "path": "/api/v1/operations/op-20261201-7fead487" + }, + "response": { + "body": { + "cancelRequestedAt": "2026-12-01T15:13:36.705960Z", + "cancelRequestedBy": "opal", + "engine": "builtin", + "environments": [ + "dev" + ], + "finishedAt": "2026-12-01T15:13:36.995319Z", + "links": { + "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + "self": "/api/v1/operations/op-20261201-7fead487" + }, + "operationId": "op-20261201-7fead487", + "parameters": { + "batchSize": 20, + "environments": [ + "dev" + ], + "maxOpenPerCluster": 5, + "tier": "small" + }, + "phase": "Stopped", + "progress": { + "finished": 1, + "phases": { + "Stopped": 1 + }, + "total": 1 + }, + "report": { + "steps": [ + { + "items": [], + "phases": { + "Stopped": 1 + }, + "step": "select-outdated" + } + ] + }, + "runName": "op-20261201-7fead487", + "startedAt": "2026-12-01T15:13:36.696696Z", + "startedBy": "opal", + "steps": [ + { + "attempts": 0, + "clusterId": "", + "finishedAt": "2026-12-01T15:13:36.968745Z", + "item": "", + "lastError": null, + "outputs": { + "note": "stopped by opal" + }, + "phase": "Stopped", + "startedAt": "2026-12-01T15:13:36.480026Z", + "step": "select-outdated" + } + ], + "template": "tiers-rerender" + }, + "contentType": "application/json", + "headers": {}, + "status": 200 + } + }, + "operations_list_operations": { + "request": { + "headers": { + "Authorization": "Bearer $TOKEN" + }, + "method": "GET", + "path": "/api/v1/operations?template=tiers-rerender" + }, + "response": { + "body": { + "items": [ + { + "cancelRequestedAt": null, + "cancelRequestedBy": null, + "engine": "builtin", + "environments": [ + "dev" + ], + "finishedAt": null, + "links": { + "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + "self": "/api/v1/operations/op-20261201-7fead487" + }, + "operationId": "op-20261201-7fead487", + "parameters": { + "batchSize": 20, + "environments": [ + "dev" + ], + "maxOpenPerCluster": 5, + "tier": "small" + }, + "phase": "Running", + "progress": { + "finished": 0, + "phases": { + "Running": 1 + }, + "total": 1 + }, + "runName": "op-20261201-7fead487", + "startedAt": "2026-12-01T15:13:36.696696Z", + "startedBy": "opal", + "template": "tiers-rerender" + } + ], + "letters": { + "T": 1 + }, + "page": { + "from": 1, + "limit": 50, + "nextCursor": null, + "prevCursor": null, + "to": 1, + "total": 1 + } + }, + "contentType": "application/json", + "headers": {}, + "status": 200 + } + }, + "operations_start": { + "request": { + "body": { + "parameters": { + "environments": [ + "dev" + ], + "tier": "small" + }, + "template": "tiers-rerender" + }, + "headers": { + "Authorization": "Bearer $TOKEN", + "Idempotency-Key": "a516db56-8f45-4b54-8053-d1e94767949e" + }, + "method": "POST", + "path": "/api/v1/operations" + }, + "response": { + "body": { + "cancelRequestedAt": null, + "cancelRequestedBy": null, + "engine": "builtin", + "environments": [ + "dev" + ], + "finishedAt": null, + "links": { + "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + "self": "/api/v1/operations/op-20261201-7fead487" + }, + "operationId": "op-20261201-7fead487", + "parameters": { + "batchSize": 20, + "environments": [ + "dev" + ], + "maxOpenPerCluster": 5, + "tier": "small" + }, + "phase": "Running", + "progress": { + "finished": 0, + "phases": { + "Running": 1 + }, + "total": 1 + }, + "report": null, + "runName": "op-20261201-7fead487", + "startedAt": "2026-12-01T15:13:36.696696Z", + "startedBy": "opal", + "steps": [ + { + "attempts": 0, + "clusterId": "", + "finishedAt": null, + "item": "", + "lastError": null, + "outputs": null, + "phase": "Running", + "startedAt": "2026-12-01T15:13:36.480026Z", + "step": "select-outdated" + } + ], + "template": "tiers-rerender" + }, + "contentType": "application/json", + "headers": {}, + "status": 202 + } + }, "policies_rejections": { "request": { "headers": { @@ -3799,7 +4100,7 @@ }, "response": { "body": { - "from": "2026-11-20T20:59:12.816211Z", + "from": "2026-11-24T15:13:31.152927Z", "items": [ { "action": "create", @@ -3818,9 +4119,9 @@ "source": "cmapi" } ], - "firstAt": "2026-11-27T20:59:09.886777Z", + "firstAt": "2026-12-01T15:13:26.735685Z", "id": "rej-2", - "lastAt": "2026-11-27T20:59:09.886777Z", + "lastAt": "2026-12-01T15:13:26.735685Z", "namespace": "kube-tools", "outcome": "refused", "plugin": "namespaces", @@ -3838,7 +4139,7 @@ "findings": [ { "kyvernoRule": null, - "message": "the head moved from 479aab8d to 9df23668 after the pull request was opened", + "message": "the head moved from 4afd09a1 to 00ee2444 after the pull request was opened", "path": null, "policy": "cmapi-check", "rule": null, @@ -3846,14 +4147,14 @@ "source": "cmapi" } ], - "firstAt": "2026-11-27T20:59:03.193672Z", + "firstAt": "2026-12-01T15:13:12.465909Z", "id": "rej-1", - "lastAt": "2026-11-27T20:59:03.193672Z", + "lastAt": "2026-12-01T15:13:12.465909Z", "namespace": "search-dev", "outcome": "refused", "plugin": "namespaces", "problem": null, - "requestId": "req-20261127-0007", + "requestId": "req-20261201-0007", "stage": "ci", "username": "ola" } @@ -3890,7 +4191,7 @@ "body": { "clusters": [ { - "asOf": "2026-11-27T20:59:12.694710Z", + "asOf": "2026-12-01T15:13:30.959859Z", "bundle": { "actionsDiffer": [], "actionsDifferTotal": 0, @@ -4743,13 +5044,13 @@ "Authorization": "Bearer $TOKEN" }, "method": "GET", - "path": "/api/v1/requests/req-20261127-0001/approval-status" + "path": "/api/v1/requests/req-20261201-0001/approval-status" }, "response": { "body": { "approved": true, - "planHash": "9fed510537c2c36b3dc18a5b461ebfac4c2f1b7dfc2a61a394afd47b96624c09", - "requestId": "req-20261127-0001", + "planHash": "4e9af3fc1f212f0387b6958adccca82242cc53b7fd67192be64529da18a31563", + "requestId": "req-20261201-0001", "status": "synced" }, "contentType": "application/json", @@ -4766,7 +5067,7 @@ "Authorization": "Bearer $TOKEN" }, "method": "POST", - "path": "/api/v1/requests/req-20261127-0002:approve" + "path": "/api/v1/requests/req-20261201-0002:approve" }, "response": { "body": { @@ -4774,7 +5075,7 @@ "approval": { "approvals": [ { - "at": "2026-11-27T20:58:56.181147Z", + "at": "2026-12-01T15:12:57.737114Z", "comment": "sizing reviewed", "relayedBy": null, "sub": "sub-amy", @@ -4799,28 +5100,28 @@ ], "timeoutHours": 8 }, - "baseSha": "80f4f1badad17a36a1e6c5d25834f76fef11435b", + "baseSha": "513f40b0ee251859ba80791976ccc3addcfdf1ba", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:55.923726Z", + "createdAt": "2026-12-01T15:12:57.455807Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:56.005112Z", + "at": "2026-12-01T15:12:57.536560Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", "status": "pending_approval" }, { - "at": "2026-11-27T20:58:56.208815Z", + "at": "2026-12-01T15:12:57.766421Z", "by": "amy", "event": "approval", "note": "sizing reviewed", "status": "pending_approval" }, { - "at": "2026-11-27T20:58:56.231666Z", + "at": "2026-12-01T15:12:57.795342Z", "by": "amy", "event": "approved", "note": "approval count met", @@ -4837,16 +5138,16 @@ "instance": "nonprod", "justification": "Load test next sprint", "links": { - "events": "/api/v1/requests/req-20261127-0002/events", - "self": "/api/v1/requests/req-20261127-0002" + "events": "/api/v1/requests/req-20261201-0002/events", + "self": "/api/v1/requests/req-20261201-0002" }, "mergeSha": null, "namespace": "payments-dev", - "planHash": "df5602a2038007a6de28e19adf060fd6b5f8fb3d5b86637f790b31efdc510039", + "planHash": "7aebcbffedf4cef6b095bd7594ab08df7c4f3964ede6f8138b15048c990b9ed3", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0002", + "requestId": "req-20261201-0002", "requester": { "automated": false, "requester": { @@ -4864,7 +5165,7 @@ "submittedByClient": null }, "status": "approved", - "updatedAt": "2026-11-27T20:58:56.128756Z" + "updatedAt": "2026-12-01T15:12:57.519349Z" }, "contentType": "application/json", "headers": {}, @@ -4877,7 +5178,7 @@ "Authorization": "Bearer $TOKEN" }, "method": "POST", - "path": "/api/v1/requests/req-20261127-0005:cancel" + "path": "/api/v1/requests/req-20261201-0005:cancel" }, "response": { "body": { @@ -4906,21 +5207,21 @@ ], "timeoutHours": 8 }, - "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + "baseSha": "f33469a0b99e67100557d4172703299def66403b", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:00.839033Z", + "createdAt": "2026-12-01T15:13:07.269501Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:00.869605Z", + "at": "2026-12-01T15:13:07.303276Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", "status": "pending_approval" }, { - "at": "2026-11-27T20:59:01.284709Z", + "at": "2026-12-01T15:13:07.829553Z", "by": "ola", "event": "cancel", "note": "", @@ -4937,16 +5238,16 @@ "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0005/events", - "self": "/api/v1/requests/req-20261127-0005" + "events": "/api/v1/requests/req-20261201-0005/events", + "self": "/api/v1/requests/req-20261201-0005" }, "mergeSha": null, "namespace": "ledger-dev", - "planHash": "872bc285608555d97234f8f6f440473a920a3da01e2e5509a176628b51d35ac3", + "planHash": "ce7e669a03e55261cb76f1ec4054133e9985c1ab51a26c1edf7bfb18ea4bf918", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0005", + "requestId": "req-20261201-0005", "requester": { "automated": false, "requester": { @@ -4964,7 +5265,7 @@ "submittedByClient": null }, "status": "cancelled", - "updatedAt": "2026-11-27T20:59:01.183312Z" + "updatedAt": "2026-12-01T15:13:07.554237Z" }, "contentType": "application/json", "headers": {}, @@ -4977,76 +5278,76 @@ "Authorization": "Bearer $TOKEN" }, "method": "GET", - "path": "/api/v1/requests/req-20261127-0001/events" + "path": "/api/v1/requests/req-20261201-0001/events" }, "response": { "body": { "events": [ { - "at": "2026-11-27T20:58:54.488801Z", + "at": "2026-12-01T15:12:55.724895Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", "status": "approved" }, { - "at": "2026-11-27T20:58:54.586895Z", + "at": "2026-12-01T15:12:55.840600Z", "by": "cmapi-bot", "event": "branch_pushed", - "note": "cmapi/CRC/req-20261127-0001 at 80f4f1ba on aaaaaaaa (created)", + "note": "cmapi/CRC/req-20261201-0001 at 513f40b0 on aaaaaaaa (created)", "status": "approved" }, { - "at": "2026-11-27T20:58:54.636706Z", + "at": "2026-12-01T15:12:55.901812Z", "by": "cmapi-bot", "event": "pr_opened", - "note": "cmapi/CRC/req-20261127-0001 #1", + "note": "cmapi/CRC/req-20261201-0001 #1", "status": "pr_open" }, { - "at": "2026-11-27T20:58:54.677782Z", + "at": "2026-12-01T15:12:55.945117Z", "by": "ci", "event": "ci", "note": "kubeconform: pass; kyverno: pass; cmapi check: pass", "status": "pr_open" }, { - "at": "2026-11-27T20:58:54.757184Z", + "at": "2026-12-01T15:12:56.052717Z", "by": "cmapi-deliverer", "event": "apply_started", - "note": "applying 80f4f1ba before the merge", + "note": "applying 513f40b0 before the merge", "status": "pr_open" }, { - "at": "2026-11-27T20:58:54.799387Z", + "at": "2026-12-01T15:12:56.124941Z", "by": "cmapi-deliverer", "event": "applied", - "note": "5 objects from cmapi/CRC/req-20261127-0001 at 80f4f1ba, before the merge, confirmed by a read: 1 Namespace, 1 ResourceQuota and 2 LimitRanges match the plan", + "note": "5 objects from cmapi/CRC/req-20261201-0001 at 513f40b0, before the merge, confirmed by a read: 1 Namespace, 1 ResourceQuota and 2 LimitRanges match the plan, as do 1 RoleBinding", "status": "applied" }, { - "at": "2026-11-27T20:58:54.850841Z", + "at": "2026-12-01T15:12:56.188647Z", "by": "worker", "event": "merge_verified", - "note": "merged 80f4f1ba; the folder at it is the plan's", + "note": "merged 513f40b0; the folder at it is the plan's", "status": "applied" }, { - "at": "2026-11-27T20:58:54.864833Z", + "at": "2026-12-01T15:12:56.204485Z", "by": "cmapi-bot", "event": "merged", - "note": "merged 80f4f1ba", + "note": "merged 513f40b0", "status": "merged" }, { - "at": "2026-11-27T20:58:54.881820Z", + "at": "2026-12-01T15:12:56.223876Z", "by": "cmapi-deliverer", "event": "synced", "note": "applied and confirmed by a read before the merge", "status": "synced" } ], - "requestId": "req-20261127-0001", + "requestId": "req-20261201-0001", "status": "synced" }, "contentType": "application/json", @@ -5060,7 +5361,7 @@ "Authorization": "Bearer $TOKEN" }, "method": "GET", - "path": "/api/v1/requests/req-20261127-0001" + "path": "/api/v1/requests/req-20261201-0001" }, "response": { "body": { @@ -5082,67 +5383,67 @@ "baseSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:54.441022Z", + "createdAt": "2026-12-01T15:12:55.670320Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:54.488801Z", + "at": "2026-12-01T15:12:55.724895Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", "status": "approved" }, { - "at": "2026-11-27T20:58:54.586895Z", + "at": "2026-12-01T15:12:55.840600Z", "by": "cmapi-bot", "event": "branch_pushed", - "note": "cmapi/CRC/req-20261127-0001 at 80f4f1ba on aaaaaaaa (created)", + "note": "cmapi/CRC/req-20261201-0001 at 513f40b0 on aaaaaaaa (created)", "status": "approved" }, { - "at": "2026-11-27T20:58:54.636706Z", + "at": "2026-12-01T15:12:55.901812Z", "by": "cmapi-bot", "event": "pr_opened", - "note": "cmapi/CRC/req-20261127-0001 #1", + "note": "cmapi/CRC/req-20261201-0001 #1", "status": "pr_open" }, { - "at": "2026-11-27T20:58:54.677782Z", + "at": "2026-12-01T15:12:55.945117Z", "by": "ci", "event": "ci", "note": "kubeconform: pass; kyverno: pass; cmapi check: pass", "status": "pr_open" }, { - "at": "2026-11-27T20:58:54.757184Z", + "at": "2026-12-01T15:12:56.052717Z", "by": "cmapi-deliverer", "event": "apply_started", - "note": "applying 80f4f1ba before the merge", + "note": "applying 513f40b0 before the merge", "status": "pr_open" }, { - "at": "2026-11-27T20:58:54.799387Z", + "at": "2026-12-01T15:12:56.124941Z", "by": "cmapi-deliverer", "event": "applied", - "note": "5 objects from cmapi/CRC/req-20261127-0001 at 80f4f1ba, before the merge, confirmed by a read: 1 Namespace, 1 ResourceQuota and 2 LimitRanges match the plan", + "note": "5 objects from cmapi/CRC/req-20261201-0001 at 513f40b0, before the merge, confirmed by a read: 1 Namespace, 1 ResourceQuota and 2 LimitRanges match the plan, as do 1 RoleBinding", "status": "applied" }, { - "at": "2026-11-27T20:58:54.850841Z", + "at": "2026-12-01T15:12:56.188647Z", "by": "worker", "event": "merge_verified", - "note": "merged 80f4f1ba; the folder at it is the plan's", + "note": "merged 513f40b0; the folder at it is the plan's", "status": "applied" }, { - "at": "2026-11-27T20:58:54.864833Z", + "at": "2026-12-01T15:12:56.204485Z", "by": "cmapi-bot", "event": "merged", - "note": "merged 80f4f1ba", + "note": "merged 513f40b0", "status": "merged" }, { - "at": "2026-11-27T20:58:54.881820Z", + "at": "2026-12-01T15:12:56.223876Z", "by": "cmapi-deliverer", "event": "synced", "note": "applied and confirmed by a read before the merge", @@ -5159,22 +5460,22 @@ "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0001/events", + "events": "/api/v1/requests/req-20261201-0001/events", "pr": "https://git.test/pulls/1", - "self": "/api/v1/requests/req-20261127-0001" + "self": "/api/v1/requests/req-20261201-0001" }, - "mergeSha": "80f4f1ba", + "mergeSha": "513f40b0", "namespace": "payments-dev", - "planHash": "9fed510537c2c36b3dc18a5b461ebfac4c2f1b7dfc2a61a394afd47b96624c09", + "planHash": "4e9af3fc1f212f0387b6958adccca82242cc53b7fd67192be64529da18a31563", "plugin": "namespaces", "pr": { - "branch": "cmapi/CRC/req-20261127-0001", - "head": "80f4f1ba", + "branch": "cmapi/CRC/req-20261201-0001", + "head": "513f40b0", "number": 1, "url": "https://git.test/pulls/1" }, "reason": null, - "requestId": "req-20261127-0001", + "requestId": "req-20261201-0001", "requester": { "automated": false, "requester": { @@ -5192,7 +5493,7 @@ "submittedByClient": null }, "status": "synced", - "updatedAt": "2026-11-27T20:58:54.780441Z" + "updatedAt": "2026-12-01T15:12:55.949790Z" }, "contentType": "application/json", "headers": {}, @@ -5237,14 +5538,14 @@ ], "timeoutHours": 8 }, - "baseSha": "80f4f1badad17a36a1e6c5d25834f76fef11435b", + "baseSha": "513f40b0ee251859ba80791976ccc3addcfdf1ba", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:55.923726Z", + "createdAt": "2026-12-01T15:12:57.455807Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:56.005112Z", + "at": "2026-12-01T15:12:57.536560Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", @@ -5261,16 +5562,16 @@ "instance": "nonprod", "justification": "Load test next sprint", "links": { - "events": "/api/v1/requests/req-20261127-0002/events", - "self": "/api/v1/requests/req-20261127-0002" + "events": "/api/v1/requests/req-20261201-0002/events", + "self": "/api/v1/requests/req-20261201-0002" }, "mergeSha": null, "namespace": "payments-dev", - "planHash": "df5602a2038007a6de28e19adf060fd6b5f8fb3d5b86637f790b31efdc510039", + "planHash": "7aebcbffedf4cef6b095bd7594ab08df7c4f3964ede6f8138b15048c990b9ed3", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0002", + "requestId": "req-20261201-0002", "requester": { "automated": false, "requester": { @@ -5288,7 +5589,7 @@ "submittedByClient": null }, "status": "pending_approval", - "updatedAt": "2026-11-27T20:58:55.904486Z" + "updatedAt": "2026-12-01T15:12:57.263260Z" } ], "letters": { @@ -5317,7 +5618,7 @@ "Authorization": "Bearer $TOKEN" }, "method": "POST", - "path": "/api/v1/requests/req-20261127-0006:reject" + "path": "/api/v1/requests/req-20261201-0006:reject" }, "response": { "body": { @@ -5346,21 +5647,21 @@ ], "timeoutHours": 8 }, - "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + "baseSha": "f33469a0b99e67100557d4172703299def66403b", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:01.025136Z", + "createdAt": "2026-12-01T15:13:07.467592Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:01.059924Z", + "at": "2026-12-01T15:13:07.523173Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", "status": "pending_approval" }, { - "at": "2026-11-27T20:59:01.177791Z", + "at": "2026-12-01T15:13:07.689889Z", "by": "amy", "event": "rejected", "note": "Use the medium tier", @@ -5377,16 +5678,16 @@ "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0006/events", - "self": "/api/v1/requests/req-20261127-0006" + "events": "/api/v1/requests/req-20261201-0006/events", + "self": "/api/v1/requests/req-20261201-0006" }, "mergeSha": null, "namespace": "billing-dev", - "planHash": "83fbdd10e46eb59ab7a8469389ca3be081d6248b68e498bd28f9b5553b7d319b", + "planHash": "2dc6e0f17a140f4c9b54f8ba3f3438767816ea38ea0e7288d30ad08d61977635", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0006", + "requestId": "req-20261201-0006", "requester": { "automated": false, "requester": { @@ -5404,7 +5705,7 @@ "submittedByClient": null }, "status": "rejected", - "updatedAt": "2026-11-27T20:59:01.074654Z" + "updatedAt": "2026-12-01T15:13:07.412997Z" }, "contentType": "application/json", "headers": {}, @@ -5417,7 +5718,7 @@ "Authorization": "Bearer $TOKEN" }, "method": "POST", - "path": "/api/v1/requests/req-20261127-0007:retry" + "path": "/api/v1/requests/req-20261201-0007:retry" }, "response": { "body": { @@ -5436,70 +5737,70 @@ "slots": [], "timeoutHours": 8 }, - "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + "baseSha": "f33469a0b99e67100557d4172703299def66403b", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:02.774593Z", + "createdAt": "2026-12-01T15:13:11.695133Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:02.805919Z", + "at": "2026-12-01T15:13:11.739486Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", "status": "approved" }, { - "at": "2026-11-27T20:59:02.926517Z", + "at": "2026-12-01T15:13:12.002993Z", "by": "cmapi-bot", "event": "branch_pushed", - "note": "cmapi/CRC/req-20261127-0007 at 479aab8d on a539f2ec (created)", + "note": "cmapi/CRC/req-20261201-0007 at 4afd09a1 on f33469a0 (created)", "status": "approved" }, { - "at": "2026-11-27T20:59:03.034663Z", + "at": "2026-12-01T15:13:12.223049Z", "by": "cmapi-bot", "event": "pr_opened", - "note": "cmapi/CRC/req-20261127-0007 #5", + "note": "cmapi/CRC/req-20261201-0007 #5", "status": "pr_open" }, { - "at": "2026-11-27T20:59:03.202028Z", + "at": "2026-12-01T15:13:12.476559Z", "by": "ci", "event": "ci", "note": "kubeconform: pass; kyverno: pass; cmapi check: fail", "status": "pr_open" }, { - "at": "2026-11-27T20:59:03.221341Z", + "at": "2026-12-01T15:13:12.503772Z", "by": "ci", "event": "head_moved", - "note": "PR head moved from 479aab8d to 9df23668 after approval", + "note": "PR head moved from 4afd09a1 to 00ee2444 after approval", "status": "pr_open" }, { - "at": "2026-11-27T20:59:03.235587Z", + "at": "2026-12-01T15:13:12.524707Z", "by": "ci", "event": "pr_failed", "note": "checks failed", "status": "failed" }, { - "at": "2026-11-27T20:59:03.235646Z", + "at": "2026-12-01T15:13:12.524778Z", "by": "worker", "event": "pr_closed", "note": "#5: its checks failed; the request is failed and may be retried", "status": "failed" }, { - "at": "2026-11-27T20:59:03.337967Z", + "at": "2026-12-01T15:13:12.722929Z", "by": "worker", "event": "branch_deleted", - "note": "cmapi/CRC/req-20261127-0007 at 9df23668", + "note": "cmapi/CRC/req-20261201-0007 at 00ee2444", "status": "failed" }, { - "at": "2026-11-27T20:59:04.480562Z", + "at": "2026-12-01T15:13:15.355831Z", "by": "opal", "event": "retry", "note": "retry requested", @@ -5516,22 +5817,22 @@ "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0007/events", + "events": "/api/v1/requests/req-20261201-0007/events", "pr": "https://git.test/pulls/5", - "self": "/api/v1/requests/req-20261127-0007" + "self": "/api/v1/requests/req-20261201-0007" }, "mergeSha": null, "namespace": "search-dev", - "planHash": "2cbf58b2fd56a364d34143e4ad6349cd2aeda2faa6214d9720de95dce8966f81", + "planHash": "9e54f6892405d065608268e425a03e3a4ffcbf02c1d0465424fc7f3a06a65833", "plugin": "namespaces", "pr": { - "branch": "cmapi/CRC/req-20261127-0007", - "head": "479aab8d", + "branch": "cmapi/CRC/req-20261201-0007", + "head": "4afd09a1", "number": 5, "url": "https://git.test/pulls/5" }, "reason": null, - "requestId": "req-20261127-0007", + "requestId": "req-20261201-0007", "requester": { "automated": false, "requester": { @@ -5549,7 +5850,7 @@ "submittedByClient": null }, "status": "approved", - "updatedAt": "2026-11-27T20:59:04.382387Z" + "updatedAt": "2026-12-01T15:13:15.083613Z" }, "contentType": "application/json", "headers": {}, @@ -5562,7 +5863,7 @@ "Authorization": "Bearer $TOKEN" }, "method": "POST", - "path": "/api/v1/requests/req-20261127-0009:revert" + "path": "/api/v1/requests/req-20261201-0009:revert" }, "response": { "body": { @@ -5581,63 +5882,63 @@ "slots": [], "timeoutHours": 8 }, - "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + "baseSha": "f33469a0b99e67100557d4172703299def66403b", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:08.498578Z", + "createdAt": "2026-12-01T15:13:24.659107Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:08.528720Z", + "at": "2026-12-01T15:13:24.709971Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", "status": "approved" }, { - "at": "2026-11-27T20:59:08.615802Z", + "at": "2026-12-01T15:13:24.888974Z", "by": "cmapi-bot", "event": "branch_pushed", - "note": "cmapi/CRC/req-20261127-0009 at f4851764 on a539f2ec (created)", + "note": "cmapi/CRC/req-20261201-0009 at 8dde0960 on f33469a0 (created)", "status": "approved" }, { - "at": "2026-11-27T20:59:08.662018Z", + "at": "2026-12-01T15:13:24.957534Z", "by": "cmapi-bot", "event": "pr_opened", - "note": "cmapi/CRC/req-20261127-0009 #8", + "note": "cmapi/CRC/req-20261201-0009 #8", "status": "pr_open" }, { - "at": "2026-11-27T20:59:08.703276Z", + "at": "2026-12-01T15:13:25.016675Z", "by": "ci", "event": "ci", "note": "kubeconform: pass; kyverno: pass; cmapi check: pass", "status": "pr_open" }, { - "at": "2026-11-27T20:59:08.743034Z", + "at": "2026-12-01T15:13:25.072457Z", "by": "worker", "event": "merge_verified", - "note": "merged f4851764; the folder at it is the plan's", + "note": "merged 8dde0960; the folder at it is the plan's", "status": "pr_open" }, { - "at": "2026-11-27T20:59:08.753863Z", + "at": "2026-12-01T15:13:25.089654Z", "by": "cmapi-bot", "event": "merged", - "note": "merged f4851764", + "note": "merged 8dde0960", "status": "merged" }, { - "at": "2026-11-27T20:59:08.804072Z", + "at": "2026-12-01T15:13:25.173437Z", "by": "worker", "event": "sync_timeout", "note": "orders-dev exists on the cluster and cmapi does not manage it; nothing applied", "status": "sync_failed" }, { - "at": "2026-11-27T20:59:08.972422Z", + "at": "2026-12-01T15:13:25.438291Z", "by": "opal", "event": "revert_requested", "note": "", @@ -5654,22 +5955,22 @@ "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0009/events", + "events": "/api/v1/requests/req-20261201-0009/events", "pr": "https://git.test/pulls/8", - "self": "/api/v1/requests/req-20261127-0009" + "self": "/api/v1/requests/req-20261201-0009" }, - "mergeSha": "f4851764", + "mergeSha": "8dde0960", "namespace": "orders-dev", - "planHash": "2b55cc5cb3a1687f1a10e7038a5ce91dfb672e864e45f9479f2a4ca2b85ddcdc", + "planHash": "4b5e5a0bd420f5925cbcfcc96fecca8e8fc2c4ccd0a7f579ffa057a49b37af02", "plugin": "namespaces", "pr": { - "branch": "cmapi/CRC/req-20261127-0009", - "head": "f4851764", + "branch": "cmapi/CRC/req-20261201-0009", + "head": "8dde0960", "number": 8, "url": "https://git.test/pulls/8" }, "reason": null, - "requestId": "req-20261127-0009", + "requestId": "req-20261201-0009", "requester": { "automated": false, "requester": { @@ -5687,7 +5988,7 @@ "submittedByClient": null }, "status": "sync_failed", - "updatedAt": "2026-11-27T20:59:08.871988Z" + "updatedAt": "2026-12-01T15:13:25.162107Z" }, "contentType": "application/json", "headers": {}, @@ -5937,8 +6238,8 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "e60a18fd-0706-4184-be61-45c673b6b14a", - "If-Match": "\"fcaf1ac2eae8c00e\"" + "Idempotency-Key": "40c5fe41-18e9-4b59-bc91-06b0f5fb5d02", + "If-Match": "\"cb4d81bed601c81a\"" }, "method": "PATCH", "path": "/api/v1/clusters/CRC/namespaces/audit-dev" @@ -5946,8 +6247,8 @@ "response": { "body": { "code": "change-pending", - "detail": "req-20261127-0015 holds audit-dev", - "requestId": "req-20261127-0015", + "detail": "req-20261201-0015 holds audit-dev", + "requestId": "req-20261201-0015", "status": 409, "title": "change pending", "type": "https://cmapi.ephico2real.com/problems/change-pending" @@ -6008,12 +6309,12 @@ "operationId": "namespaces_set_expiry", "request": { "body": { - "until": "2026-12-18" + "until": "2026-12-22" }, "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "f0cef618-748f-4614-b614-f857e8798c1e", - "If-Match": "\"073bd8faea2248ce\"" + "Idempotency-Key": "7576ba93-00ae-499a-bdc0-cf057fc7ade0", + "If-Match": "\"917c7a62361f9e08\"" }, "method": "POST", "path": "/api/v1/clusters/CRC/namespaces/sprint-dev/expiration:set" @@ -6101,8 +6402,8 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "128d4aa7-248c-46c9-ab46-aff1b5e0e17f", - "If-Match": "\"fcaf1ac2eae8c00e\"" + "Idempotency-Key": "6e0052b0-9048-4037-99b6-14a6e1dc154d", + "If-Match": "\"cb4d81bed601c81a\"" }, "method": "PATCH", "path": "/api/v1/clusters/CRC/namespaces/audit-dev" @@ -6111,7 +6412,7 @@ "body": { "code": "idempotency-replay", "detail": "Idempotency-Key was used for a different request", - "requestId": "req-20261127-0015", + "requestId": "req-20261201-0015", "status": 409, "title": "idempotency replay", "type": "https://cmapi.ephico2real.com/problems/idempotency-replay" @@ -6150,7 +6451,7 @@ "Authorization": "Bearer $TOKEN" }, "method": "POST", - "path": "/api/v1/requests/req-20261127-0007:revert" + "path": "/api/v1/requests/req-20261201-0007:revert" }, "response": { "body": { @@ -6183,7 +6484,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "42ec4138-ef5a-47a4-971f-8d8102a2a4b6" + "Idempotency-Key": "b54d3e23-1b14-4402-a9b0-41dc1e37f5c6" }, "method": "POST", "path": "/api/v1/clusters/CRC/namespaces" @@ -6237,7 +6538,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "If-Match": "\"d71165fa38f59dd4\"" + "If-Match": "\"1b59766bf9a3bbe7\"" }, "method": "PATCH", "path": "/api/v1/clusters/CRC/namespaces/payments-dev?dryRun=true" @@ -6314,6 +6615,39 @@ "status": 404 } }, + "operation-template-unknown": { + "operationId": "operations_start", + "request": { + "body": { + "parameters": {}, + "template": "tier-rerender" + }, + "headers": { + "Authorization": "Bearer $TOKEN", + "Idempotency-Key": "a941db58-c6a6-4ef3-9771-9a420143122d" + }, + "method": "POST", + "path": "/api/v1/operations" + }, + "response": { + "body": { + "code": "operation-template-unknown", + "detail": "No operation template 'tier-rerender'; this build has ['cluster-onboard', 'rebuild-verify', 'reconcile', 'tiers-rerender']", + "status": 422, + "templates": [ + "cluster-onboard", + "rebuild-verify", + "reconcile", + "tiers-rerender" + ], + "title": "operation template unknown", + "type": "https://cmapi.ephico2real.com/problems/operation-template-unknown" + }, + "contentType": "application/problem+json", + "headers": {}, + "status": 422 + } + }, "placement-mismatch": { "operationId": "namespaces_create_namespace", "request": { @@ -6327,7 +6661,7 @@ "cmapi.net/team": "payments" }, "namespace": "payments-placed", - "placementId": "pl-20261127-7658a163", + "placementId": "pl-20261201-52bb3c04", "tier": "small" }, "headers": { @@ -6339,7 +6673,7 @@ "response": { "body": { "code": "placement-mismatch", - "detail": "Placement pl-20261127-7658a163 was made for another target: the placement's team is 'billing', the create's 'payments'", + "detail": "Placement pl-20261201-52bb3c04 was made for another target: the placement's team is 'billing', the create's 'payments'", "status": 422, "title": "placement mismatch", "type": "https://cmapi.ephico2real.com/problems/placement-mismatch" @@ -6438,7 +6772,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "4d830e7a-d18a-4b95-a13b-896166df08fd", + "Idempotency-Key": "5120602f-f304-40bc-baf1-c137df2665a1", "If-Match": "\"stale\"" }, "method": "PATCH", @@ -6448,7 +6782,7 @@ "body": { "code": "precondition-failed", "detail": "The namespace changed in Git since you read it", - "etag": "d71165fa38f59dd4", + "etag": "1b59766bf9a3bbe7", "status": 412, "title": "precondition failed", "type": "https://cmapi.ephico2real.com/problems/precondition-failed" @@ -6466,7 +6800,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "fe4f9058-9447-4831-a225-c4ada6e56abf" + "Idempotency-Key": "3c168684-ca55-4915-8048-3de66de4a07b" }, "method": "PATCH", "path": "/api/v1/clusters/CRC/namespaces/payments-dev" @@ -6501,7 +6835,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "Idempotency-Key": "7bc95474-8f53-4e34-9661-faead4a22fa0" + "Idempotency-Key": "74be9051-d3fe-4502-9ba4-5beeff72cb0b" }, "method": "POST", "path": "/api/v1/clusters/CRC/namespaces" @@ -6550,7 +6884,7 @@ }, "headers": { "Authorization": "Bearer $TOKEN", - "If-Match": "\"d71165fa38f59dd4\"" + "If-Match": "\"1b59766bf9a3bbe7\"" }, "method": "PATCH", "path": "/api/v1/clusters/CRC/namespaces/payments-dev?dryRun=true" diff --git a/cmapi/src/cmapi/core/context.py b/cmapi/src/cmapi/core/context.py index fedd08a8..767df36f 100644 --- a/cmapi/src/cmapi/core/context.py +++ b/cmapi/src/cmapi/core/context.py @@ -26,6 +26,7 @@ from cmapi.core.identity.keycloak_admin import KeycloakAdminDirectory, split_issuer from cmapi.core.listquery import Lister, Sorts, severity from cmapi.core.observability import AUTO_PAUSED, CONFIG_INFO, POLICY_MODE, VALIDATOR_WAIT +from cmapi.core.operations import Operations from cmapi.core.pipeline import Pipeline from cmapi.core.placement import PlacementSettings from cmapi.core.policybundle import PolicyBundle @@ -60,6 +61,9 @@ class AppContext: usage: UsageSource = field(default_factory=NoUsage) # capacity.yaml usage.source: live 14-day usage (#310) analysis: AnalysisSettings = field(default_factory=lambda: AnalysisSettings(None, set())) # analysis.yaml thresholds placement: PlacementSettings = field(default_factory=lambda: PlacementSettings(None)) # placement.yaml (#21) + # integrations.yaml `operations`, the templates of this build and the engine (#26). A value integrations.yaml cannot hold + # stops the start; an engine with no adapter in this build answers 503 operations-engine-unavailable at POST. + operations: Operations = field(default_factory=lambda: Operations.from_integrations(None)) def auto_paused(self, session: Any = None) -> bool: """Whether an admin paused auto-approval. With `session`, read in the caller's transaction: pipeline.submit holds a @@ -190,7 +194,7 @@ def nodes_for(st: ClusterState, client: KubeClient) -> NodeCache: delivery=DeliveryConfig.from_integrations(integrations), integrations=integrations, capacity_cfg=capacity_cfg, capacity=capacity_settings, issuer=issuer, audience=audience, bundle=policy_bundle, limiter=RateLimiter(limits=dict(cfg.rate_limits)), usage=usage, analysis=analysis, - placement=placement) + placement=placement, operations=Operations.from_integrations(integrations)) reserved = (inst.get("namespaces") or {}).get("reservedPatterns") or [] ctx.pipeline = Pipeline(cfg, registry, git, validator, capacity, directory, reserved, auto_paused=ctx.auto_paused, usage=usage) diff --git a/cmapi/src/cmapi/core/db/__init__.py b/cmapi/src/cmapi/core/db/__init__.py index cc56d4d9..48b5f80a 100644 --- a/cmapi/src/cmapi/core/db/__init__.py +++ b/cmapi/src/cmapi/core/db/__init__.py @@ -84,7 +84,7 @@ def schema_status(self) -> str: return str(exc) -REQUIRED_REVISION = "0012" # placement reads 0012's capacity_snapshots and placement holds (#21); 0011: the holds (#62) +REQUIRED_REVISION = "0013" # the operations API reads 0013's operations and operation_steps (#26); 0012: placement (#21) FUTURE_REVISION = re.compile(r"([0-9]{4})(?:_[a-z0-9_]+)?") # the repository's convention: four digits, counting up diff --git a/cmapi/src/cmapi/core/db/migrations/versions/0013_operations.py b/cmapi/src/cmapi/core/db/migrations/versions/0013_operations.py new file mode 100644 index 00000000..6b75a2f5 --- /dev/null +++ b/cmapi/src/cmapi/core/db/migrations/versions/0013_operations.py @@ -0,0 +1,109 @@ +"""operations and operation_steps: the runs of the built-in operations engine (story #26, criterion 3; docs/02, "One step +library, any engine" and "Built-in engine"). + +operation_steps has docs/02's columns, with five added: + +- `cluster_id`: the cluster of a fan-out item, for the per-cluster cap of a fan-out step ("A fan-out step gets one row per item, + capped per cluster"); '' for a step that is not about one cluster. +- `inputs`: the item's value, as the step that generated the items wrote it; null for a single step. +- `started_at`, `finished_at` and `updated_at`: when the row first ran, when it reached a final phase, and its last change, so + the status of record shows progress and a wait's timeout can be measured. + +operations has docs/07's columns ("Tracking", the operations table), with these changes: + +- `workflow_name` is `run_name`, the name docs/02's RunStatus uses: the run's name on its engine (the operation's own ID on the + built-in engine), and `engine` names the engine that ran it. +- `started_by_sub` is text, not UUID: cmapi's subjects are the token's `sub`, which a Keycloak service account or another + issuer need not write as a UUID (change_requests.requester_sub is text too). `started_by` keeps the starter's identity record + with the roles and groups of the token that started it: the grant the steps act under (docs/reviews/2026-12-01-issue-26- + operations/design.md, D3). +- `environments`: the environments the operation acts in, null for an instance-wide one, so a read or a cancel checks + `operations:run` where the operation acts, as `:probe` and `prune:confirm` do. +- `idempotency_key` and `idempotency_fingerprint`: the start's Idempotency-Key under the starter's subject, as change_requests + keeps a write's (0008, 0009). +- `cancel_requested_by` and `cancel_requested_at`: who asked to stop it, and when; the run is Stopped once no step is running. +- `report`: the built-in engine's report ("reports go into the operations row as JSON instead of S3"); `report_url` is left + for the Argo and Tekton adapters, which are not built. +- `updated_at`. + +change_requests gets no `operation_id` column (docs/07 adds one): the request a step opens is in the step's outputs, and the +request records the step's client and the starter (docs/02, rule 4), so the table of every write stays as it is. + +Revision ID: 0013 +Revises: 0012 +Create Date: 2026-12-01 +""" +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects.postgresql import JSONB + +revision = "0013" +down_revision = "0012" +branch_labels = None +depends_on = None + +RUN_PHASES = "'Pending', 'Running', 'Succeeded', 'Failed', 'Error', 'Stopped'" +STEP_PHASES = "'Pending', 'Running', 'Waiting', 'Succeeded', 'Skipped', 'Failed', 'Error', 'Stopped'" + + +def upgrade() -> None: + op.create_table( + "operations", + sa.Column("operation_id", sa.String(40), primary_key=True), + sa.Column("template", sa.String(80), nullable=False), + sa.Column("parameters", JSONB, nullable=False), + sa.Column("engine", sa.String(20), nullable=False), + sa.Column("run_name", sa.String(253), nullable=False), + sa.Column("phase", sa.String(20), nullable=False, server_default="Pending"), + sa.Column("environments", JSONB), + sa.Column("started_by_sub", sa.String(100), nullable=False), + sa.Column("started_by", JSONB, nullable=False), + sa.Column("idempotency_key", sa.String(100)), + sa.Column("idempotency_fingerprint", sa.String(64)), + sa.Column("cancel_requested_by", sa.String(100)), + sa.Column("cancel_requested_at", sa.DateTime(timezone=True)), + sa.Column("report", JSONB), + sa.Column("started_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()), + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()), + sa.Column("finished_at", sa.DateTime(timezone=True)), + sa.CheckConstraint(f"phase IN ({RUN_PHASES})", name="ck_op_phase"), + sa.CheckConstraint("(finished_at IS NULL) = (phase IN ('Pending', 'Running'))", name="ck_op_finished"), + sa.CheckConstraint("(idempotency_key IS NULL) = (idempotency_fingerprint IS NULL)", name="ck_op_idempotency"), + sa.CheckConstraint("(cancel_requested_at IS NULL) = (cancel_requested_by IS NULL)", name="ck_op_cancel"), + ) + # One start per Idempotency-Key and caller: a retried POST finds the run it started. + op.create_index("uq_op_idempotency", "operations", ["started_by_sub", "idempotency_key"], unique=True, + postgresql_where=sa.text("idempotency_key IS NOT NULL")) + op.create_index("idx_op_started", "operations", ["started_at"]) + # The scheduler reads the runs that are not finished on every step it completes. + op.create_index("idx_op_active", "operations", ["phase"], postgresql_where=sa.text("finished_at IS NULL")) + op.create_table( + "operation_steps", + sa.Column("operation_id", sa.String(40), sa.ForeignKey("operations.operation_id"), nullable=False), + sa.Column("step", sa.String(80), nullable=False), + sa.Column("item", sa.String(253), nullable=False, server_default=""), + sa.Column("cluster_id", sa.String(63), nullable=False, server_default=""), + sa.Column("phase", sa.String(20), nullable=False, server_default="Pending"), + sa.Column("attempts", sa.Integer, nullable=False, server_default="0"), + sa.Column("inputs", JSONB), + sa.Column("outputs", JSONB), + sa.Column("last_error", sa.Text), + sa.Column("started_at", sa.DateTime(timezone=True)), + sa.Column("finished_at", sa.DateTime(timezone=True)), + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()), + sa.PrimaryKeyConstraint("operation_id", "step", "item"), + sa.CheckConstraint(f"phase IN ({STEP_PHASES})", name="ck_opstep_phase"), + sa.CheckConstraint("attempts >= 0", name="ck_opstep_attempts"), + sa.CheckConstraint("(finished_at IS NULL) = (phase IN ('Pending', 'Running', 'Waiting'))", name="ck_opstep_finished"), + ) + # The engine counts the steps in flight across every run (maxConcurrentSteps) and per cluster (a fan-out's cap). + op.create_index("idx_opstep_active", "operation_steps", ["phase", "cluster_id"], + postgresql_where=sa.text("phase IN ('Running', 'Waiting')")) + + +def downgrade() -> None: + # The runs' history goes with the tables; the requests that their steps opened stay, each with its own record. + op.drop_table("operation_steps") + op.drop_table("operations") diff --git a/cmapi/src/cmapi/core/db/models.py b/cmapi/src/cmapi/core/db/models.py index 0a5cc38f..1c5d62c0 100644 --- a/cmapi/src/cmapi/core/db/models.py +++ b/cmapi/src/cmapi/core/db/models.py @@ -318,3 +318,70 @@ class NamespaceVerdictRow(Base): verdict: Mapped[str] = mapped_column(String(30), primary_key=True) kind: Mapped[str] = mapped_column(String(8), nullable=False) evidence: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False) + + +RUN_PHASES = ("Pending", "Running", "Succeeded", "Failed", "Error", "Stopped") +STEP_PHASES = ("Pending", "Running", "Waiting", "Succeeded", "Skipped", "Failed", "Error", "Stopped") + + +def _among(column: str, values: tuple[str, ...]) -> str: + return f"{column} IN (" + ", ".join(f"'{v}'" for v in values) + ")" + + +class OperationRow(Base): + """One run of an operation template (story #26, migration 0013; docs/02, "One step library, any engine"). The status of + record of GET /api/v1/operations/{id}: its phase, the run's steps (OperationStepRow) and, once finished, its report.""" + __tablename__ = "operations" + __table_args__ = ( + CheckConstraint(_among("phase", RUN_PHASES), name="ck_op_phase"), + CheckConstraint("(finished_at IS NULL) = (phase IN ('Pending', 'Running'))", name="ck_op_finished"), + CheckConstraint("(idempotency_key IS NULL) = (idempotency_fingerprint IS NULL)", name="ck_op_idempotency"), + CheckConstraint("(cancel_requested_at IS NULL) = (cancel_requested_by IS NULL)", name="ck_op_cancel"), + Index("uq_op_idempotency", "started_by_sub", "idempotency_key", unique=True, + postgresql_where=text("idempotency_key IS NOT NULL")), + Index("idx_op_started", "started_at"), + Index("idx_op_active", "phase", postgresql_where=text("finished_at IS NULL")), + ) + operation_id: Mapped[str] = mapped_column(String(40), primary_key=True) + template: Mapped[str] = mapped_column(String(80), nullable=False) + parameters: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False) + engine: Mapped[str] = mapped_column(String(20), nullable=False) + run_name: Mapped[str] = mapped_column(String(253), nullable=False) + phase: Mapped[str] = mapped_column(String(20), nullable=False, server_default="Pending") + environments: Mapped[list[str] | None] = mapped_column(JSONB) # None: instance-wide + started_by_sub: Mapped[str] = mapped_column(String(100), nullable=False) + started_by: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False) # Identity.record() with roles and groups + idempotency_key: Mapped[str | None] = mapped_column(String(100)) + idempotency_fingerprint: Mapped[str | None] = mapped_column(String(64)) + cancel_requested_by: Mapped[str | None] = mapped_column(String(100)) + cancel_requested_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + report: Mapped[dict[str, Any] | None] = mapped_column(JSONB) + started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now()) + updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now(), + onupdate=func.now()) + finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + + +class OperationStepRow(Base): + """One step of a run, or one item of a fan-out step (item '' for a step that is not fanned out). Its phase is the progress + the API reports; its attempts and last_error are the template's retry block at work.""" + __tablename__ = "operation_steps" + __table_args__ = ( + CheckConstraint(_among("phase", STEP_PHASES), name="ck_opstep_phase"), + CheckConstraint("attempts >= 0", name="ck_opstep_attempts"), + CheckConstraint("(finished_at IS NULL) = (phase IN ('Pending', 'Running', 'Waiting'))", name="ck_opstep_finished"), + Index("idx_opstep_active", "phase", "cluster_id", postgresql_where=text("phase IN ('Running', 'Waiting')")), + ) + operation_id: Mapped[str] = mapped_column(String(40), ForeignKey("operations.operation_id"), primary_key=True) + step: Mapped[str] = mapped_column(String(80), primary_key=True) + item: Mapped[str] = mapped_column(String(253), primary_key=True, server_default="") + cluster_id: Mapped[str] = mapped_column(String(63), nullable=False, server_default="") + phase: Mapped[str] = mapped_column(String(20), nullable=False, server_default="Pending") + attempts: Mapped[int] = mapped_column(Integer, nullable=False, server_default="0") + inputs: Mapped[dict[str, Any] | None] = mapped_column(JSONB) + outputs: Mapped[dict[str, Any] | None] = mapped_column(JSONB) + last_error: Mapped[str | None] = mapped_column(Text) + started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now(), + onupdate=func.now()) diff --git a/cmapi/src/cmapi/core/docs.py b/cmapi/src/cmapi/core/docs.py index 587d814e..6652930c 100644 --- a/cmapi/src/cmapi/core/docs.py +++ b/cmapi/src/cmapi/core/docs.py @@ -87,6 +87,8 @@ "reserved-namespace": (422, "kube-tools is reserved"), "invalid-namespace-name": (422, "Not a DNS-1123 label"), "no-change": (422, "The request changes nothing"), + "operation-template-unknown": (422, "No operation template 'tier-rerender'; this build has ['cluster-onboard', " + "'rebuild-verify', 'reconcile', 'tiers-rerender']"), "adoption-key-held": (422, "abc-rnd already has the label company.net/lob: an adoption keeps each key it finds as it is. " "Leave it out, and change it with a request after the adoption"), "identity-incomplete": (422, "The token has no employee_id claim"), @@ -115,6 +117,9 @@ "capacity-service-unavailable": (503, "cmapi-capacity cannot be reached"), "git-unavailable": (502, "The Git host answered 500"), "validator-unavailable": (503, "kubeconform did not start"), + "operations-engine-unavailable": (503, "The argo-workflows engine that integrations.yaml operations.engine names has " + "no adapter in this build; set it to builtin, which runs the same templates in the " + "cmapi worker"), "validator-busy": (503, "The policy check is temporarily busy. Try again after the delay in Retry-After."), "internal-error": (500, "The service failed. Give the X-Request-Id of this answer to the platform team"), "docs-assets-missing": (503, "The Swagger UI bundle is not in /opt/app-root/static"), @@ -210,6 +215,7 @@ def takes_validated_input(op: dict[str, Any]) -> bool: "folder-not-utf8": {"paths": ["clusters/CRC/namespaces/payments-dev/caf\\xe9.yaml"]}, "folder-not-yaml": {"paths": ["clusters/CRC/namespaces/payments-dev/namespace.yaml"]}, "several-resource-quotas": {"resourceQuotas": ["payments-dev-objects", "payments-dev-quota"]}, + "operation-template-unknown": {"templates": ["cluster-onboard", "rebuild-verify", "reconcile", "tiers-rerender"]}, # the instance that serves qa, from instance.yaml directory (core/config.py environment_not_served, #671) "environment-not-served": {"instanceUrl": "https://cmapi-staging.ephico2real.com", "portalUrl": "https://portal-staging.ephico2real.com"}, diff --git a/cmapi/src/cmapi/core/observability.py b/cmapi/src/cmapi/core/observability.py index 043030f2..7f2a3832 100644 --- a/cmapi/src/cmapi/core/observability.py +++ b/cmapi/src/cmapi/core/observability.py @@ -62,6 +62,9 @@ REQUESTS_STALLED = Gauge("cmapi_requests_stalled", "pr_open requests with no PR and no job, older than syncTimeout") JOBS_PENDING = Gauge("cmapi_jobs_pending", "Jobs waiting to run", ["kind"]) JOB_FAILURES = Counter("cmapi_job_failures_total", "Jobs that raised", ["kind"]) +# docs/01, Observability: cmapi_operation_runs_total{template, engine, result}, one for each run that ends (#26). +OPERATION_RUNS = Counter("cmapi_operation_runs_total", "Operation runs that ended, by their final phase", + ["template", "engine", "result"]) EXPIRY_ACTIONS = Counter("cmapi_expiry_actions_total", "What expire_check did for a namespace: notice, notice_failed, grace, " "delete_opened, delete_held or error", ["action", "environment"]) LEAD_TIME = Histogram("cmapi_change_lead_time_seconds", "Submit to synced", ["plugin", "action", "approval"], diff --git a/cmapi/src/cmapi/core/operations.py b/cmapi/src/cmapi/core/operations.py new file mode 100644 index 00000000..fd30aa24 --- /dev/null +++ b/cmapi/src/cmapi/core/operations.py @@ -0,0 +1,746 @@ +"""The operations engine (story #26, criterion 3; docs/02, "One step library, any engine"). + +An operation template is data (cmapi/ops/templates/*.yaml): its parameters, its retry block and its steps, each a Python +function of the step library (cmapi/ops). The built-in engine runs the steps in the cmapi worker and keeps their state in +PostgreSQL: one `operations` row per run and one `operation_steps` row per step, or per item of a fan-out step (migration +0013). Each step that is due is one job of kind `operation_step` in the jobs table, so a worker that dies mid-step leaves a job +that another worker claims when the lease runs out, and the step runs again from the state it committed. + +How a run moves (`advance`, under one advisory lock for the whole engine): + +1. A step gets its rows once every step it runs `after` is Succeeded or Skipped. A fan-out step (`withParam`) gets one row + per item that the step it names wrote in its `items` output, and one Skipped row when there is none. +2. A Pending row starts (Running, and its job queued) while fewer than `maxConcurrentSteps` rows of the whole instance are + Running, so a run never fills the queue ahead of the request jobs. A fan-out row also waits while its step has + `parallelism` rows in flight (Running or Waiting), or `perCluster` on its cluster. +3. A row that waits for something outside the engine (a request's approval and delivery, an import, a retry's backoff) is + Waiting: its next job is queued for later and holds no slot. +4. The run ends when no row is Pending, Running or Waiting: Stopped when someone cancelled it, else Error, Failed or Succeeded + by its worst row, with the report in the row (docs/02: "reports go into the operations row as JSON"). + +The four rules of docs/02 that hold on every engine, and where each holds here: + +- Steps change managed objects only by calling cmapi: a step opens an ordinary request through `Pipeline` (cmapi/ops). +- Runs start only through cmapi, which records an operations row: `Operations.start`, from POST /api/v1/operations. +- No pause nodes: a step that needs approval opens a request and polls it (StepResult.wait). +- Steps act as svc-cmapi-workflows, and every request they open records that client and the person who started the run + (`StepContext.actor`, `StepContext.requester`). + +The design decisions, with their sources: docs/reviews/2026-12-01-issue-26-operations/design.md. +""" +from __future__ import annotations + +import hashlib +import re +import secrets +from dataclasses import dataclass, field +from datetime import datetime, timedelta, timezone +from importlib import resources +from typing import Any, Callable, Mapping + +import yaml +from sqlalchemy import func, select, text +from sqlalchemy.orm import Session + +from cmapi.core.db.models import JobRow, OperationRow, OperationStepRow +from cmapi.core.db.repo import JobRepo, utcnow +from cmapi.core.errors import Problem +from cmapi.core.identity.checks import Requester +from cmapi.core.identity.claims import Identity +from cmapi.core.observability import OPERATION_RUNS, log + +ENGINES = ("builtin", "argo-workflows", "tekton") +STEP_JOB = "operation_step" +# docs/02, rule 4: "Steps call cmapi as svc-cmapi-workflows". On the built-in engine the step runs in the worker, with no token: +# this is the client the requests record, acting under the grant of the person who started the run (design.md, D3). +WORKFLOWS_CLIENT = "svc-cmapi-workflows" +ACTIVE = ("Pending", "Running", "Waiting") +IN_FLIGHT = ("Running", "Waiting") +FINAL_RUN = ("Succeeded", "Failed", "Error", "Stopped") +DONE_OK = ("Succeeded", "Skipped") +_DURATION = re.compile(r"^([0-9]+)([smh])$") +_REFERENCE = re.compile(r"^\{\{(steps|parameters)\.([A-Za-z0-9-]+)(?:\.outputs\.([A-Za-z0-9-]+))?\}\}$") +_CLUSTER_ID = re.compile(r"^[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$") +_ENGINE_LOCK = int.from_bytes(hashlib.sha256(b"cmapi-operations").digest()[:8], "big", signed=True) + + +def valid_cluster_id(value: str) -> bool: + """A cluster ID as an import Secret's cmapi.net/cluster-id label holds one: a label value of 1 to 63 characters.""" + return bool(_CLUSTER_ID.fullmatch(value)) + + +def seconds(value: Any, where: str) -> int: + """A duration of a template: `30s`, `5m`, `24h`, or a number of seconds.""" + if isinstance(value, int) and not isinstance(value, bool) and value >= 0: + return value + m = _DURATION.fullmatch(str(value)) + if not m: + raise ValueError(f"{where}: {value!r} is not a duration such as 30s, 5m or 24h") + return int(m.group(1)) * {"s": 1, "m": 60, "h": 3600}[m.group(2)] + + +# --------------------------------------------------------------------------- configuration + + +@dataclass(frozen=True) +class OperationsSettings: + """integrations.yaml `operations` (docs/18). `engine` picks the engine; `builtin.maxConcurrentSteps` caps the steps of all + runs that are Running at once ("separate from request jobs, so operations never starve them", docs/02).""" + engine: str = "builtin" + max_concurrent_steps: int = 4 + + @classmethod + def from_integrations(cls, raw: Mapping[str, Any] | None) -> "OperationsSettings": + ops = (raw or {}).get("operations") or {} + if not isinstance(ops, Mapping): + raise ValueError("integrations.yaml operations must be a mapping") + engine = ops.get("engine", "builtin") + if engine not in ENGINES: + raise ValueError(f"integrations.yaml operations.engine is one of {list(ENGINES)}, not {engine!r}") + limit = (ops.get("builtin") or {}).get("maxConcurrentSteps", 4) + if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 64: + raise ValueError(f"integrations.yaml operations.builtin.maxConcurrentSteps is a whole number from 1 to 64, " + f"not {limit!r}") + return cls(engine=engine, max_concurrent_steps=limit) + + +# --------------------------------------------------------------------------- templates + + +@dataclass(frozen=True) +class Param: + name: str + type: str # string, integer, list (of strings) or object + required: bool = False + default: Any = None + minimum: int | None = None + maximum: int | None = None + description: str = "" + + +@dataclass(frozen=True) +class Retry: + """Argo Workflows' retryStrategy: `limit` is "the maximum number of retry attempts [...] the maximum number of total + attempts will be limit + 1", and each retry waits `backoff` times `factor` to the power of the retries before it.""" + limit: int = 3 + backoff_seconds: int = 30 + factor: float = 2.0 + + def delay(self, retry: int) -> int: + return int(self.backoff_seconds * self.factor ** (retry - 1)) + + +@dataclass(frozen=True) +class StepDef: + name: str + after: tuple[str, ...] = () + with_param: str | None = None # the step whose `items` output fans this one out + parallelism: int | str | None = None # a number, or the name of an integer parameter + per_cluster: int | str | None = None + timeout_seconds: int | None = None # a step still not final this long after it started is Failed + inputs: dict[str, tuple[str, str]] = field(default_factory=dict) # input -> (step, output) + not_built: str | None = None # the issue that builds this step; the step refuses until then + + +@dataclass(frozen=True) +class OperationTemplate: + name: str + description: str + scope: str # environments, cluster, new-cluster or instance: what a start is checked in + permissions: tuple[str, ...] # what the starter needs beside operations:run, where the run acts + parameters: tuple[Param, ...] + retry: Retry + steps: tuple[StepDef, ...] + + def step(self, name: str) -> StepDef: + return next(s for s in self.steps if s.name == name) + + def order(self, name: str) -> int: + return next(i for i, s in enumerate(self.steps) if s.name == name) + + def cap(self, value: int | str | None, parameters: Mapping[str, Any]) -> int | None: + return parameters.get(value) if isinstance(value, str) else value + + def validate(self, raw: Mapping[str, Any]) -> dict[str, Any]: + """The run's parameters, with their defaults; 422 validation-failed naming each one that is wrong.""" + errors = [] + known = {p.name: p for p in self.parameters} + for name in sorted(set(raw) - set(known)): + errors.append({"field": f"parameters.{name}", "code": "unknown_parameter", + "message": f"{self.name} takes no parameter {name}; it takes {sorted(known)}"}) + out: dict[str, Any] = {} + for p in self.parameters: + value = raw.get(p.name, p.default) + if value is None: + if p.required: + errors.append({"field": f"parameters.{p.name}", "code": "missing", "message": "required"}) + continue + problem = _type_problem(p, value) + if problem: + errors.append({"field": f"parameters.{p.name}", "code": "invalid_value", "message": problem}) + continue + out[p.name] = value + if errors: + raise Problem(422, "validation-failed", f"The parameters of {self.name} are not valid", errors) + return out + + +def _type_problem(p: Param, value: Any) -> str | None: + if p.type == "string": + return None if isinstance(value, str) and value.strip() and len(value) <= 253 else "a text of 1 to 253 characters" + if p.type == "integer": + if not isinstance(value, int) or isinstance(value, bool): + return "a whole number" + if (p.minimum is not None and value < p.minimum) or (p.maximum is not None and value > p.maximum): + return f"from {p.minimum} to {p.maximum}" + return None + if p.type == "list": + ok = isinstance(value, list) and value and all(isinstance(v, str) and v for v in value) and len(set(value)) == len(value) + return None if ok else "a list of distinct texts, not empty" + if p.type == "selector": + # A clusterSelector as approval rules write one (core/approvals.py): {matchLabels: {key: value}}, nothing else. + labels = value.get("matchLabels") if isinstance(value, Mapping) else None + ok = isinstance(labels, Mapping) and set(value) == {"matchLabels"} and \ + all(isinstance(k, str) and isinstance(v, str) for k, v in labels.items()) + return None if ok else "{matchLabels: {key: value}}" + return f"unknown type {p.type}" + + +_TEMPLATE_KEYS = {"name", "description", "scope", "permissions", "parameters", "retry", "steps"} +_STEP_KEYS = {"name", "after", "withParam", "parallelism", "perCluster", "timeout", "inputs", "outputs", "notBuilt"} +SCOPES = ("environments", "cluster", "new-cluster", "instance") + + +def parse_template(raw: Mapping[str, Any], steps: Mapping[tuple[str, str], Callable[..., Any]]) -> OperationTemplate: + """A template from its YAML, checked: every key known, every step after the steps it names, every reference to an earlier + step or a parameter, and every step a function of the library. ValueError names what is wrong.""" + name = raw.get("name") + where = f"template {name}" + unknown = set(raw) - _TEMPLATE_KEYS + if unknown: + raise ValueError(f"{where}: unknown keys {sorted(unknown)}") + if raw.get("scope") not in SCOPES: + raise ValueError(f"{where}: scope is one of {list(SCOPES)}") + params = [] + for p in raw.get("parameters") or []: + if isinstance(p, str): + p = {"name": p, "type": "string", "required": True} + params.append(Param(name=p["name"], type=p.get("type", "string"), required=bool(p.get("required", False)), + default=p.get("default"), minimum=p.get("minimum"), maximum=p.get("maximum"), + description=p.get("description", ""))) + pnames = {p.name for p in params} + r = raw.get("retry") or {} + retry = Retry(limit=int(r.get("limit", 3)), backoff_seconds=seconds(r.get("backoff", "30s"), f"{where} retry"), + factor=float(r.get("factor", 2))) + defs: list[StepDef] = [] + seen: set[str] = set() + for s in raw.get("steps") or []: + sname = s.get("name") + sw = f"{where} step {sname}" + if set(s) - _STEP_KEYS: + raise ValueError(f"{sw}: unknown keys {sorted(set(s) - _STEP_KEYS)}") + if sname in seen or not sname: + raise ValueError(f"{sw}: a step name must be given once") + after = tuple(s.get("after") or ()) + if set(after) - seen: + raise ValueError(f"{sw}: runs after {sorted(set(after) - seen)}, which no earlier step is") + with_param = None + if s.get("withParam") is not None: + kind, source, key = _reference(s["withParam"], sw) + if kind != "steps" or key != "items" or source not in after: + raise ValueError(f"{sw}: withParam names the `items` output of a step that it runs after") + with_param = source + inputs = {} + for iname, ref in (s.get("inputs") or {}).items(): + kind, source, key = _reference(ref, sw) + if kind != "steps" or key is None or source not in seen: + raise ValueError(f"{sw}: input {iname} names an output of an earlier step") + inputs[iname] = (source, key) + caps = {} + for k in ("parallelism", "perCluster"): + v = s.get(k) + if isinstance(v, str): + kind, pname, _ = _reference(v, sw) + if kind != "parameters" or pname not in pnames: + raise ValueError(f"{sw}: {k} is a number or {{{{parameters.}}}}") + v = pname + caps[k] = v + not_built = s.get("notBuilt") + if not_built is None and (raw["name"], sname) not in steps: + raise ValueError(f"{sw}: no function in the step library (cmapi/ops)") + defs.append(StepDef(name=sname, after=after, with_param=with_param, parallelism=caps["parallelism"], + per_cluster=caps["perCluster"], + timeout_seconds=seconds(s["timeout"], sw) if s.get("timeout") is not None else None, + inputs=inputs, not_built=not_built)) + seen.add(sname) + if not defs: + raise ValueError(f"{where}: no steps") + from cmapi.core.authz import PERMISSIONS + extra = tuple(raw.get("permissions") or ()) + if set(extra) - PERMISSIONS: + raise ValueError(f"{where}: unknown permissions {sorted(set(extra) - PERMISSIONS)}") + return OperationTemplate(name=name, description=str(raw.get("description", "")).strip(), scope=raw["scope"], + permissions=extra, parameters=tuple(params), retry=retry, steps=tuple(defs)) + + +def _reference(value: Any, where: str) -> tuple[str, str, str | None]: + m = _REFERENCE.fullmatch(str(value)) + if not m: + raise ValueError(f"{where}: {value!r} is not {{{{steps..outputs.}}}} or {{{{parameters.}}}}") + return m.group(1), m.group(2), m.group(3) + + +def load_templates() -> dict[str, OperationTemplate]: + """The templates that ship with this build (cmapi/ops/templates). A template that does not parse stops the start.""" + from cmapi.ops import STEPS + + out: dict[str, OperationTemplate] = {} + for entry in sorted(resources.files("cmapi.ops").joinpath("templates").iterdir(), key=lambda e: e.name): + if entry.name.endswith(".yaml"): + t = parse_template(yaml.safe_load(entry.read_text()), STEPS) + out[t.name] = t + return out + + +# --------------------------------------------------------------------------- engines + + +class OperationsEngine: + """docs/02's OperationsEngine, synchronous as the rest of cmapi: `available`, `submit` (the run's name) and `cancel`. The + built-in engine writes its own state, so it needs no `watch`; the Argo and Tekton adapters, not built, would add it.""" + name = "builtin" + + def available(self) -> tuple[bool, str]: + return True, "" + + def submit(self, s: Session, op: OperationRow, template: OperationTemplate) -> str: + raise NotImplementedError + + def cancel(self, s: Session, op: OperationRow) -> None: + raise NotImplementedError + + +class UnavailableEngine(OperationsEngine): + """An engine that integrations.yaml names and this build has no adapter for (Argo Workflows, Tekton). docs/02: "cmapi starts + anyway and stays ready. POST /api/v1/operations returns 503 operations-engine-unavailable"; reads still answer.""" + + def __init__(self, name: str): + self.name = name + + def available(self) -> tuple[bool, str]: + return False, (f"The {self.name} engine that integrations.yaml operations.engine names has no adapter in this build; " + "set it to builtin, which runs the same templates in the cmapi worker") + + def submit(self, s: Session, op: OperationRow, template: OperationTemplate) -> str: + raise Problem(503, "operations-engine-unavailable", self.available()[1]) + + +class BuiltinEngine(OperationsEngine): + name = "builtin" + + def __init__(self, settings: OperationsSettings, templates: Mapping[str, OperationTemplate]): + self.settings, self.templates = settings, templates + + def submit(self, s: Session, op: OperationRow, template: OperationTemplate) -> str: + advance(s, self) + return op.operation_id + + def cancel(self, s: Session, op: OperationRow) -> None: + advance(s, self) + + +# --------------------------------------------------------------------------- the scheduler + + +def lock_engine(s: Session) -> None: + """One scheduler at a time across the instance, until this transaction ends: the counts of rows in flight that the caps read + stay true while it starts rows. The order of the locks, everywhere: a step's job locks its own row, then this lock, then the + runs' rows (`advance`); a cancel takes this lock before its run's row. A scheduler pass touches no row a job holds: only + Pending rows, and Waiting rows it can lock without waiting (SKIP LOCKED).""" + s.execute(text("SELECT pg_advisory_xact_lock(:k)"), {"k": _ENGINE_LOCK}) + + +def advance(s: Session, engine: BuiltinEngine) -> None: + """Move every run that is not finished as far as it can go now: create the rows of the steps that are ready, start Pending + rows within the caps, and end a run that has nothing left in flight.""" + lock_engine(s) + s.flush() + runs = list(s.scalars(select(OperationRow).where(OperationRow.finished_at.is_(None)) + .order_by(OperationRow.started_at, OperationRow.operation_id).with_for_update())) + for op in runs: + template = engine.templates.get(op.template) + if template is None: + _finish(s, op, "Error", f"this build has no template {op.template}") + continue + _create_ready_rows(s, op, template) + s.flush() + running = s.scalar(select(func.count()).select_from(OperationStepRow).where(OperationStepRow.phase == "Running")) or 0 + for op in runs: + template = engine.templates.get(op.template) + if template is None or op.finished_at is not None: + continue + running = _start_rows(s, op, template, running, engine.settings.max_concurrent_steps) + _end_if_done(s, op, template) + + +def _rows(s: Session, op_id: str) -> list[OperationStepRow]: + return list(s.scalars(select(OperationStepRow).where(OperationStepRow.operation_id == op_id))) + + +def _create_ready_rows(s: Session, op: OperationRow, template: OperationTemplate) -> None: + rows = _rows(s, op.operation_id) + if op.cancel_requested_at is not None: + # Nothing new starts. A Pending row is Stopped now, and so is a Waiting row that no job holds: its next poll finds it + # final and does nothing. A row whose job runs now is stopped by that job (StepJob). + waiting = {(r.step, r.item) for r in s.scalars(select(OperationStepRow).where( + OperationStepRow.operation_id == op.operation_id, OperationStepRow.phase == "Waiting") + .with_for_update(skip_locked=True))} + for r in rows: + if r.phase == "Pending" or (r.phase == "Waiting" and (r.step, r.item) in waiting): + _final(r, "Stopped", note=f"stopped by {op.cancel_requested_by}") + return + by_step: dict[str, list[OperationStepRow]] = {} + for r in rows: + by_step.setdefault(r.step, []).append(r) + for step in template.steps: + if step.name in by_step: + continue + deps = [by_step.get(a) for a in step.after] + if any(d is None or any(r.phase not in DONE_OK for r in d) for d in deps): + continue # not ready, or never: a step it runs after did not succeed + if step.with_param is None: + by_step[step.name] = [_new_row(s, op, step.name, "", "", None)] + continue + source = by_step[step.with_param][0] + items = list((source.outputs or {}).get("items") or []) + if not items: + row = _new_row(s, op, step.name, "", "", None) + _final(row, "Skipped", note=f"{step.with_param} found nothing to do") + by_step[step.name] = [row] + continue + by_step[step.name] = [_new_row(s, op, step.name, str(it["item"]), str(it.get("clusterId") or ""), dict(it)) + for it in items] + + +def _new_row(s: Session, op: OperationRow, step: str, item: str, cluster_id: str, + inputs: dict[str, Any] | None) -> OperationStepRow: + row = OperationStepRow(operation_id=op.operation_id, step=step, item=item, cluster_id=cluster_id, phase="Pending", + attempts=0, inputs=inputs, outputs=None, updated_at=utcnow()) + s.add(row) + return row + + +def _start_rows(s: Session, op: OperationRow, template: OperationTemplate, running: int, limit: int) -> int: + rows = sorted(_rows(s, op.operation_id), key=lambda r: (template.order(r.step), r.item)) + flight_step: dict[str, int] = {} + flight_cluster: dict[tuple[str, str], int] = {} + for r in rows: + if r.phase in IN_FLIGHT: + flight_step[r.step] = flight_step.get(r.step, 0) + 1 + flight_cluster[(r.step, r.cluster_id)] = flight_cluster.get((r.step, r.cluster_id), 0) + 1 + jobs = JobRepo(s) + for r in rows: + if r.phase != "Pending": + continue + if running >= limit: + break + step = template.step(r.step) + parallel = template.cap(step.parallelism, op.parameters) + per_cluster = template.cap(step.per_cluster, op.parameters) + if parallel is not None and flight_step.get(r.step, 0) >= parallel: + continue + if per_cluster is not None and r.cluster_id and flight_cluster.get((r.step, r.cluster_id), 0) >= per_cluster: + continue + r.phase, r.started_at, r.updated_at = "Running", r.started_at or utcnow(), utcnow() + queue_step(jobs, r) + running += 1 + flight_step[r.step] = flight_step.get(r.step, 0) + 1 + flight_cluster[(r.step, r.cluster_id)] = flight_cluster.get((r.step, r.cluster_id), 0) + 1 + if op.phase == "Pending" and any(r.phase != "Pending" for r in rows): + op.phase = "Running" + return running + + +def queue_step(jobs: JobRepo, row: OperationStepRow, delay: float = 0) -> None: + """The job of one step row. uq_jobs_pending keeps one pending job per row: its payload's `kind` is the row's key.""" + jobs.s.flush() + jobs.enqueue(STEP_JOB, cluster_id=row.cluster_id, delay=delay, + payload={"kind": f"{row.operation_id}/{row.step}/{row.item}", "operationId": row.operation_id, + "step": row.step, "item": row.item}) + + +def _end_if_done(s: Session, op: OperationRow, template: OperationTemplate) -> None: + rows = _rows(s, op.operation_id) + if any(r.phase in ACTIVE for r in rows): + return + phases = {r.phase for r in rows} + if op.cancel_requested_at is not None: + phase = "Stopped" + elif "Error" in phases: + phase = "Error" + elif phases & {"Failed", "Stopped"} or {r.step for r in rows} != {st.name for st in template.steps}: + phase = "Failed" # a step failed, so the steps after it never ran + else: + phase = "Succeeded" + _finish(s, op, phase, None) + + +def _finish(s: Session, op: OperationRow, phase: str, error: str | None) -> None: + now = utcnow() + op.phase, op.finished_at, op.updated_at = phase, now, now + op.report = build_report(op, _rows(s, op.operation_id), error) + log.info("operation_finished", operation_id=op.operation_id, template=op.template, phase=phase) + OPERATION_RUNS.labels(op.template, op.engine, phase).inc() + + +def _final(row: OperationStepRow, phase: str, *, note: str | None = None, error: str | None = None, + outputs: Mapping[str, Any] | None = None) -> None: + now = utcnow() + row.phase, row.finished_at, row.updated_at = phase, now, now + if outputs is not None: + row.outputs = dict(outputs) + if note: + row.outputs = {**(row.outputs or {}), "note": note} + if error is not None: + row.last_error = error[:2000] + + +def build_report(op: OperationRow, rows: list[OperationStepRow], error: str | None) -> dict[str, Any]: + """What the run did, by step: how many rows ended in each phase, and each item that did not succeed with why.""" + steps: dict[str, dict[str, Any]] = {} + for r in sorted(rows, key=lambda r: (r.started_at or op.started_at, r.step, r.item)): + st = steps.setdefault(r.step, {"step": r.step, "phases": {}, "items": []}) + st["phases"][r.phase] = st["phases"].get(r.phase, 0) + 1 + # An item that did not succeed, and one that succeeded with something to read (rebuild-verify's drift). + if r.item and (r.phase != "Succeeded" or (r.outputs or {}).get("outcome") not in (None, "synced", "match")): + st["items"].append({"item": r.item, "phase": r.phase, "outcome": (r.outputs or {}).get("outcome"), + "requestId": (r.outputs or {}).get("requestId"), "note": (r.outputs or {}).get("note"), + "differenceCount": (r.outputs or {}).get("differenceCount"), "error": r.last_error}) + out: dict[str, Any] = {"steps": list(steps.values())} + if error: + out["error"] = error + return out + + +def progress(rows: list[OperationStepRow]) -> dict[str, Any]: + by: dict[str, int] = {} + for r in rows: + by[r.phase] = by.get(r.phase, 0) + 1 + return {"total": len(rows), "finished": sum(n for p, n in by.items() if p not in ACTIVE), "phases": by} + + +# --------------------------------------------------------------------------- one step's job + + +class StepRefused(Exception): + """A step that cannot succeed by trying again: the row is Failed with this text, and the template's retries are not spent.""" + + +@dataclass +class StepResult: + """What a step function returns: final (Succeeded, Skipped, Failed) or Waiting, polled again in `poll_seconds`.""" + phase: str + outputs: dict[str, Any] = field(default_factory=dict) + note: str | None = None + poll_seconds: int = 30 + + @classmethod + def done(cls, **outputs: Any) -> "StepResult": + return cls("Succeeded", outputs) + + @classmethod + def skipped(cls, note: str, **outputs: Any) -> "StepResult": + return cls("Skipped", outputs, note) + + @classmethod + def failed(cls, note: str, **outputs: Any) -> "StepResult": + return cls("Failed", outputs, note) + + @classmethod + def wait(cls, note: str, poll_seconds: int = 30, **outputs: Any) -> "StepResult": + return cls("Waiting", outputs, note, poll_seconds) + + +@dataclass +class StepContext: + """What a step function gets: the app, the job's transaction, its run, its row and the outputs of the earlier steps.""" + ctx: Any + session: Session + operation: OperationRow + template: OperationTemplate + row: OperationStepRow + + @property + def parameters(self) -> dict[str, Any]: + return dict(self.operation.parameters) + + @property + def item(self) -> dict[str, Any]: + return dict(self.row.inputs or {}) + + @property + def previous(self) -> dict[str, Any]: + """This row's outputs from its earlier runs: a poll reads the request ID it recorded.""" + return dict(self.row.outputs or {}) + + def output(self, step: str, key: str) -> Any: + row = self.session.get(OperationStepRow, (self.operation.operation_id, step, "")) + return (row.outputs or {}).get(key) if row is not None else None + + def input(self, name: str) -> Any: + step, key = self.template.step(self.row.step).inputs[name] + return self.output(step, key) + + @property + def starter(self) -> Identity: + return starter_identity(self.operation.started_by) + + @property + def actor(self) -> Identity: + """svc-cmapi-workflows with the roles of the token that started the run: a step can do no more than its starter + could (design.md, D3: delegation, RFC 8693 section 1.1, not impersonation).""" + st = self.starter + return Identity(sub=WORKFLOWS_CLIENT, username=WORKFLOWS_CLIENT, kind="service", client_id=WORKFLOWS_CLIENT, + roles=st.roles) + + @property + def requester(self) -> Requester: + """The person who started the run, sent by svc-cmapi-workflows: both are recorded (docs/02, rule 4), and the ledger + refuses the starter as an approver (docs/01, "Approval of record").""" + return Requester(person=self.starter, caller=self.actor, automated=True) + + @property + def key(self) -> str: + """The Idempotency-Key of the request this row opens: one per row, so a step that runs again finds its request.""" + return f"{self.operation.operation_id}/{self.row.step}/{self.row.item}" + + +def starter_identity(record: Mapping[str, Any]) -> Identity: + return Identity(sub=record["sub"], username=record["username"], kind=record.get("kind", "user"), + client_id=record.get("clientId", ""), email=record.get("email"), given_name=record.get("givenName"), + middle_name=record.get("middleName"), family_name=record.get("familyName"), + employee_id=record.get("employeeId"), roles=frozenset(record.get("roles") or ()), + groups=frozenset(record.get("groups") or ())) + + +def run_step(ctx: Any, s: Session, job: JobRow) -> None: + """The handler of an operation_step job: run the row's step function once and record what it returned, then advance.""" + from cmapi.ops import STEPS + + p = job.payload or {} + jobs = JobRepo(s) + row = s.scalars(select(OperationStepRow).where( + OperationStepRow.operation_id == p.get("operationId"), OperationStepRow.step == p.get("step"), + OperationStepRow.item == p.get("item", "")).with_for_update()).first() + jobs.done(job) + if row is None or row.phase not in IN_FLIGHT: + return # stopped, or a job left over from before the row ended + engine: BuiltinEngine = ctx.operations.builtin + op = s.get(OperationRow, row.operation_id) + template = engine.templates.get(op.template) + if template is None: + _final(row, "Error", error=f"this build has no template {op.template}") + advance(s, engine) + return + step = template.step(row.step) + s.refresh(op) + if op.cancel_requested_at is not None: + _final(row, "Stopped", note=f"stopped by {op.cancel_requested_by}") + advance(s, engine) + return + if step.timeout_seconds is not None and row.started_at is not None \ + and utcnow() - row.started_at > timedelta(seconds=step.timeout_seconds): + _final(row, "Failed", error=f"{row.step} did not finish within {step.timeout_seconds} seconds") + advance(s, engine) + return + sc = StepContext(ctx, s, op, template, row) + job_transaction = s.get_transaction() + try: + with s.begin_nested(): # a step that raises leaves nothing it wrote + if step.not_built: + raise StepRefused(f"{row.step} is not built yet ({step.not_built}); the steps before it ran") + result = STEPS[(template.name, row.step)](sc) + except Exception as exc: # noqa: BLE001 - a step's failure is the row's, retried as the template says + if s.get_transaction() is not job_transaction: + # Something in the step rolled back the whole transaction (RequestRepo.insert does on a lost race for the + # namespace lock): the row's lock and this job's own state went with it. Nothing of the step was kept, so the + # worker retries the job as it is (worker.py, BACKOFF), and the step runs again. + raise + if isinstance(exc, StepRefused): + _final(row, "Failed", error=str(exc)) + elif isinstance(exc, Problem) and exc.status < 500 and exc.status not in (409, 412): + _final(row, "Failed", error=f"{exc.status} {exc.code}: {exc.detail}") # the same answer again: no retry + elif isinstance(exc, Problem): + _retry_or_fail(jobs, row, template, f"{exc.status} {exc.code}: {exc.detail}") + else: + _retry_or_fail(jobs, row, template, f"{type(exc).__name__}: {exc}") + else: + row.updated_at = utcnow() + if result.phase == "Waiting": + row.phase = "Waiting" + row.outputs = {**(row.outputs or {}), **result.outputs, "note": result.note} + queue_step(jobs, row, delay=result.poll_seconds) + else: + _final(row, result.phase, note=result.note, outputs={**(row.outputs or {}), **result.outputs}) + log.info("operation_step", operation_id=row.operation_id, step=row.step, item=row.item, phase=row.phase, + attempts=row.attempts, error=(row.last_error or "")[:200] if row.phase in ("Failed", "Waiting") else None) + advance(s, engine) + + +def _retry_or_fail(jobs: JobRepo, row: OperationStepRow, template: OperationTemplate, error: str) -> None: + row.attempts += 1 + if row.attempts > template.retry.limit: + _final(row, "Failed", error=f"after {row.attempts} attempts: {error}") + return + row.phase, row.last_error, row.updated_at = "Waiting", error[:2000], utcnow() + queue_step(jobs, row, delay=template.retry.delay(row.attempts)) + + +def job_gave_up(ctx: Any, s: Session, payload: Mapping[str, Any], error: str) -> None: + """The worker's last word on an operation_step job whose own bookkeeping failed every attempt (worker.py, MAX_ATTEMPTS): + the row is Error, so the run ends instead of showing Running for ever.""" + row = s.get(OperationStepRow, (payload.get("operationId"), payload.get("step"), payload.get("item", ""))) + if row is None or row.phase not in IN_FLIGHT: + return + _final(row, "Error", error=f"the worker gave up: {error}") + advance(s, ctx.operations.builtin) + + +# --------------------------------------------------------------------------- starting and cancelling + + +def new_operation_id(now: datetime | None = None) -> str: + now = now or datetime.now(timezone.utc) + return f"op-{now:%Y%m%d}-{secrets.token_hex(4)}" + + +@dataclass +class Operations: + """What the API and the worker hold: the settings, the templates of this build, the engine that new runs start on, and the + built-in engine, which finishes the runs it started even when integrations.yaml names another engine since.""" + settings: OperationsSettings + templates: dict[str, OperationTemplate] + engine: OperationsEngine + builtin: BuiltinEngine + + @classmethod + def from_integrations(cls, raw: Mapping[str, Any] | None) -> "Operations": + settings = OperationsSettings.from_integrations(raw) + templates = load_templates() + builtin = BuiltinEngine(settings, templates) + return cls(settings, templates, builtin if settings.engine == "builtin" else UnavailableEngine(settings.engine), builtin) + + def engine_for(self, op: OperationRow) -> OperationsEngine: + return self.builtin if op.engine == "builtin" else self.engine + + def template(self, name: str) -> OperationTemplate: + t = self.templates.get(name) + if t is None: + raise Problem.unprocessable("operation-template-unknown", f"No operation template {name!r}; this build has " + f"{sorted(self.templates)}", templates=sorted(self.templates)) + return t + + def check_available(self) -> None: + ok, why = self.engine.available() + if not ok: + raise Problem(503, "operations-engine-unavailable", why) diff --git a/cmapi/src/cmapi/core/pipeline.py b/cmapi/src/cmapi/core/pipeline.py index 583278e1..c348f0bb 100644 --- a/cmapi/src/cmapi/core/pipeline.py +++ b/cmapi/src/cmapi/core/pipeline.py @@ -236,6 +236,11 @@ def _read_folder(self, cluster_id: str, ns: str) -> tuple[dict[str, str], str]: raise folder_not_yaml(ns, errors) return files, sha + def read_folder(self, cluster_id: str, ns: str) -> tuple[dict[str, str], str]: + """The namespace's folder on the default branch and its head: the files a plan starts from, checked as a plan checks + them (502 git-unavailable, 409 folder-not-utf8 or folder-not-yaml).""" + return self._read_folder(cluster_id, ns) + def removable_folder(self, cluster_id: str, ns: str, ref: str) -> dict[str, str]: """Every path a delete of the namespace removes: each file of its folder at ref, at any depth, whatever made it (#616). A submodule is refused: its removal also changes .gitmodules at the repository's root, outside the folder, which the @@ -266,15 +271,18 @@ def workload_counts(self, cluster_id: str, ns: str) -> tuple[int, int]: # ---- plan a create or update def plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any], *, action: str, - if_match: str | None = None, reason: str | None = None) -> Plan: + if_match: str | None = None, reason: str | None = None, requester: Requester | None = None) -> Plan: + """`requester`: who the request is for, when the caller already knows it (an operation's step: the person who started + the run, sent by svc-cmapi-workflows, docs/02 rule 4). Otherwise it is resolved from `who` and `onBehalfOf`.""" try: - return self._plan_namespace(who, cluster_id, body, action=action, if_match=if_match, reason=reason) + return self._plan_namespace(who, cluster_id, body, action=action, if_match=if_match, reason=reason, + requester=requester) except Problem as exc: count_refusal(exc) raise def _plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any], *, action: str, - if_match: str | None = None, reason: str | None = None) -> Plan: + if_match: str | None = None, reason: str | None = None, requester: Requester | None = None) -> Plan: st = self.registry.writable(cluster_id) env = st.policy.environment self.check_env_served(env) @@ -285,7 +293,7 @@ def _plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any if action == "create": check_name(ns, self.reserved) check_not_unmanaged(ns, cache.namespace(ns)) - requester = self.requester_for(who, body.get("onBehalfOf")) + requester = requester or self.requester_for(who, body.get("onBehalfOf")) if action == "create": # The label is only written at create; refuse here, not as a 422 from the API server at apply. The refusal is # explicit: a ValueError that escapes a route is the service's fault, 500 internal-error (#648). diff --git a/cmapi/src/cmapi/core/ports.py b/cmapi/src/cmapi/core/ports.py index 9c76bd75..bb6fb330 100644 --- a/cmapi/src/cmapi/core/ports.py +++ b/cmapi/src/cmapi/core/ports.py @@ -167,10 +167,14 @@ def status(self, cluster_id: str) -> AppStatus: ... @runtime_checkable class OperationsEngine(Protocol): - """builtin (worker steps, default), Argo Workflows or Tekton.""" - def start(self, template: str, parameters: Mapping[str, Any], started_by: Identity) -> str: ... - def status(self, operation_id: str) -> Mapping[str, Any]: ... - def cancel(self, operation_id: str) -> None: ... + """builtin (worker steps, default), Argo Workflows or Tekton: docs/02's OperationsEngine, synchronous as the rest of cmapi + (core/operations.py). `available` says whether it can take a run, and why not; `submit` starts the run whose operations row + the caller wrote, in the caller's transaction, and returns the run's name on the engine; `cancel` stops it. The built-in + engine keeps its state in that row and its operation_steps, so it needs no `watch`; an Argo or Tekton adapter adds it.""" + name: str + def available(self) -> tuple[bool, str]: ... + def submit(self, session: Any, operation: Any, template: Any) -> str: ... + def cancel(self, session: Any, operation: Any) -> None: ... @runtime_checkable diff --git a/cmapi/src/cmapi/core/problem_docs.py b/cmapi/src/cmapi/core/problem_docs.py index f46c066c..ce86bd98 100644 --- a/cmapi/src/cmapi/core/problem_docs.py +++ b/cmapi/src/cmapi/core/problem_docs.py @@ -90,6 +90,7 @@ "plugin-disabled": "Ask the platform team. `plugins.yaml` turns this kind of write off for the environment.", "reserved-namespace": "Use a name that matches no reserved pattern.", "invalid-namespace-name": "Use a DNS-1123 label: lower-case letters, digits and `-`, at most 63 characters.", + "operation-template-unknown": "Use one of the templates that `templates` lists.", "no-change": "Do nothing. The object already has the values of the request.", "identity-incomplete": "Ask the identity team. The token does not have a claim that cmapi requires, for example `employee_id`.", "unknown-user": "Use the employee ID of an enabled user.", @@ -119,6 +120,9 @@ "capacity-service-unavailable": "Try again later. The capacity service did not answer.", "git-unavailable": "Try again later. The Git host did not answer.", "validator-unavailable": "Try again later. The manifest validator did not start.", + "operations-engine-unavailable": "Ask the platform team to set integrations.yaml `operations.engine` to an engine this " + "build has (`builtin`), or to bring the configured engine back. Nothing was started; " + "the reads of the operations still answer.", "validator-busy": "Wait for the number of seconds in `Retry-After`, then send the request again. Nothing was done: every " "slot of this pod for the policy check (kubeconform and Kyverno) was taken. The platform team can raise " "the slots with the pod's memory (docs/18, \"The validator's slots\").", diff --git a/cmapi/src/cmapi/jobs/__init__.py b/cmapi/src/cmapi/jobs/__init__.py index 61aca13f..2e59d8ab 100644 --- a/cmapi/src/cmapi/jobs/__init__.py +++ b/cmapi/src/cmapi/jobs/__init__.py @@ -4,7 +4,8 @@ Delivery (#286) is a chain of jobs with one external effect each (jobs/delivery.py): push_branch, open_pr, pr_checks, apply (apply mode), merge, then watch_sync or prune as before, and git_cleanup at the end. git_reconcile runs every 15 minutes. expire_check runs daily: the expiry notices, grace and the delete request after grace (#263). capacity_snapshot runs every -capacity.yaml snapshotInterval: each cluster's capacity snapshot (#21).""" +capacity.yaml snapshotInterval: each cluster's capacity snapshot (#21). operation_step runs one step of an operation on the +built-in engine (#26, core/operations.py).""" from __future__ import annotations from cmapi.jobs.apply import apply @@ -22,6 +23,7 @@ from cmapi.jobs.token_renew import TOKEN_RENEW_EVERY, token_renew from cmapi.jobs.usage_sweep import USAGE_SWEEP_EVERY, usage_sweep from cmapi.jobs.watch_sync import prune, watch_sync +from cmapi.core.operations import STEP_JOB, run_step HANDLERS = { "push_branch": push_branch, @@ -41,6 +43,7 @@ "usage_sweep": usage_sweep, "expire_check": expire_check, "capacity_snapshot": capacity_snapshot, + STEP_JOB: run_step, # one step of an operation on the built-in engine (#26, core/operations.py) } RECURRING = {"approval_timeout": APPROVAL_TIMEOUT_EVERY, "git_reconcile": GIT_RECONCILE_EVERY, diff --git a/cmapi/src/cmapi/main.py b/cmapi/src/cmapi/main.py index 3fa4357f..32a1a8b3 100644 --- a/cmapi/src/cmapi/main.py +++ b/cmapi/src/cmapi/main.py @@ -42,7 +42,7 @@ from cmapi.core.problem_docs import problem_html, problems_index_html from cmapi.core.observability import configure_logging, instrument, log, start_metrics from cmapi.core.tiers import TierError -from cmapi.routers import EXAMPLE_CLUSTER, admin, health, me, rate_limit, requests +from cmapi.routers import EXAMPLE_CLUSTER, admin, health, me, operations, rate_limit, requests from cmapi.settings import Settings, settings STATIC = Path(os.environ.get("CMAPI_STATIC_DIR", "/opt/app-root/static")) @@ -201,7 +201,7 @@ def api_app(cfg: InstanceConfig, issuer: str, lifespan: Any = None, app.include_router(health.router) app.include_router(health.version_router) # The core routers always, then the router of each plugin that plugins.yaml enables (core/plugins.py). - authed_routers = (me.router, requests.router, admin.router, *cfg.plugins.routers()) + authed_routers = (me.router, requests.router, operations.router, admin.router, *cfg.plugins.routers()) # Each route that takes a token takes one from its caller's bucket, after the sign-in (routers/__init__.py, rate_limit; # #689). The routes with no token (the version, health, the problem pages, the docs) have no caller to count. for r in authed_routers: diff --git a/cmapi/src/cmapi/ops/__init__.py b/cmapi/src/cmapi/ops/__init__.py new file mode 100644 index 00000000..3fbbe9dd --- /dev/null +++ b/cmapi/src/cmapi/ops/__init__.py @@ -0,0 +1,317 @@ +"""The operation step library (docs/02, "One step library, any engine"): one function per step of each template in +templates/, keyed by (template, step). The built-in engine (core/operations.py) calls them in the worker, in the job's +transaction; each returns a StepResult, or raises StepRefused for a step that cannot succeed by trying again. Any other +exception, and a 5xx, 409 or 412 problem, is retried as the template's retry block says. + +Every step can run again: a worker that dies mid-step leaves its job to another worker, and the step starts from what its row +committed. A step that opens a request finds the one it opened before by its Idempotency-Key (StepContext.key), and a step that +waits reads the request ID from its own outputs. Steps change managed objects only through cmapi's request path (docs/02, +rule 1): the plan, the approval rules and the pull request, as for a person's request. +""" +from __future__ import annotations + +from typing import Any, Callable + +from sqlalchemy import select + +from cmapi.core.db.models import ChangeRequestRow +from cmapi.core.db.repo import AuditRepo, JobRepo, RequestRepo, SwitchRepo, fingerprint +from cmapi.core.errors import Problem +from cmapi.core.operations import WORKFLOWS_CLIENT, StepContext, StepRefused, StepResult +from cmapi.core.render.manifests import objects_of, own_quota + +STEPS: dict[tuple[str, str], Callable[[StepContext], StepResult]] = {} +# Checks a template makes when a run is started, beyond its parameters' types: (ctx, parameters) -> None, or a Problem. +START_CHECKS: dict[str, Callable[[Any, dict[str, Any]], None]] = {} +RERENDER_REASON = "operation:tiers-rerender" +# A request's final states, as the step that waits on it ends (design.md, D7). synced is the request done. rejected, cancelled +# and timeout end on the approval path, a decision or its absence: the item is Skipped, and the report names the outcome. +# failed, superseded and reverted are the delivery's failures: the item is Failed. Every other state is open: wait. +REQUEST_SKIPPED = ("rejected", "cancelled", "timeout") +REQUEST_FAILED = ("failed", "superseded", "reverted") + + +def step(template: str, name: str) -> Callable[[Callable[[StepContext], StepResult]], Callable[[StepContext], StepResult]]: + def deco(fn: Callable[[StepContext], StepResult]) -> Callable[[StepContext], StepResult]: + STEPS[(template, name)] = fn + return fn + return deco + + +def wait_for_request(sc: StepContext, request_id: str) -> StepResult: + """docs/02, rule 3: "a step that needs approval opens a cmapi request and polls it, and people approve in the PR".""" + row = RequestRepo(sc.session).get(request_id) + status = row.status + if status == "synced": + return StepResult.done(requestId=request_id, outcome=status) + if status in REQUEST_SKIPPED: + return StepResult.skipped(f"request {request_id} ended {status}", requestId=request_id, outcome=status) + if status in REQUEST_FAILED: + return StepResult.failed(f"request {request_id} ended {status}", requestId=request_id, outcome=status) + return StepResult.wait(f"request {request_id} is {status}", requestId=request_id, outcome=status) + + +def _matches(labels: dict[str, str], selector: dict[str, Any] | None) -> bool: + want = (selector or {}).get("matchLabels") or {} + return all(labels.get(k) == v for k, v in want.items()) + + +# --------------------------------------------------------------------------- tiers-rerender + + +def _check_rerender(ctx: Any, p: dict[str, Any]) -> None: + for env in p["environments"]: + ctx.cfg.tiers.resolve(env, p["tier"]) # TierError: 422 tier-unknown or tier-not-offered + + +START_CHECKS["tiers-rerender"] = _check_rerender + + +@step("tiers-rerender", "select-outdated") +def select_outdated(sc: StepContext) -> StepResult: + """Each managed namespace on `tier`, in the environments and clusters asked for, whose rendered ResourceQuota carries a + cmapi.net/tier-hash that is not the catalog's: what GET /api/v1/quotas shows as tierOutdated, read from the same watch + cache. A cluster that cannot be read now is retried, never taken as having none (docs/02: nothing confirmed unread).""" + ctx, p = sc.ctx, sc.parameters + tier, envs = p["tier"], set(p["environments"]) + items, clusters, unread = [], [], [] + for cid in sorted(ctx.registry.clusters): + st = ctx.registry.clusters[cid] + policy = st.policy + if policy is None or not policy.writes or policy.environment not in envs or not _matches(policy.labels, + p.get("clusterSelector")): + continue + cache = st.cache + if st.status != "connected" or cache is None: + unread.append(f"{cid} is {st.status}") + continue + clusters.append(cid) + quotas: dict[str, list[dict[str, Any]]] = {} + for q in cache.all("ResourceQuota"): + quotas.setdefault(q["metadata"].get("namespace", ""), []).append(q) + for ns in sorted(cache.all("Namespace"), key=lambda o: o["metadata"]["name"]): + labels = ns["metadata"].get("labels") or {} + name = ns["metadata"]["name"] + if labels.get("cmapi.net/managed") != "true" or labels.get("cmapi.net/tier") != tier: + continue + rq = own_quota(quotas.get(name, []), name) + if rq is None: + continue # nothing of the catalog is rendered there (an adopted quota, D9) + rendered = (rq["metadata"].get("annotations") or {}).get("cmapi.net/tier-hash") + if ctx.cfg.tiers.is_outdated(policy.environment, tier, rendered): + items.append({"item": f"{cid}/{name}", "clusterId": cid, "namespace": name, "renderedHash": rendered}) + if unread: + raise RuntimeError("cannot read every cluster asked for: " + "; ".join(unread)) + return StepResult.done(items=items, count=len(items), clusters=clusters, + catalogHash={env: ctx.cfg.tiers.resolve(env, tier).hash for env in sorted(envs)}) + + +@step("tiers-rerender", "rerender-namespace") +def rerender_namespace(sc: StepContext) -> StepResult: + """docs/02, "Changing a tier": "one ordinary update request per outdated namespace: the plan diff shows old and new values, + increases go through the capacity check and reserve the delta, a decrease below current use is skipped and listed in the + operation report, and the approval rules apply as for any quota change".""" + ctx, s, item = sc.ctx, sc.session, sc.item + cid, ns, tier = item["clusterId"], item["namespace"], sc.parameters["tier"] + repo = RequestRepo(s) + request_id = sc.previous.get("requestId") + if request_id is None: + mine = repo.by_idempotency(WORKFLOWS_CLIENT, sc.key) # opened by a run of this step that did not record it + request_id = mine.request_id if mine is not None else None + if request_id is not None: + return wait_for_request(sc, request_id) + holder = repo.open_for(cid, ns) + if holder is not None: + # docs/07: "cmapi's per-object lock still answers 409 for a duplicate; the step treats 409 as wait and retry". + return StepResult.wait(f"{holder.request_id} holds {ns}; waiting for it to end", holder=holder.request_id) + files, _ = ctx.pipeline.read_folder(cid, ns) + from cmapi.core.pipeline import folder_etag + try: + plan = ctx.pipeline.plan_namespace(sc.actor, cid, {"namespace": ns}, action="update", + if_match=f'"{folder_etag(files)}"', reason=RERENDER_REASON, + requester=sc.requester) + except Problem as exc: + if exc.code == "no-change": + return StepResult.skipped("Git already holds it rendered from the current catalog", outcome="current") + raise + if plan.spec is None or plan.spec.tier != tier: + return StepResult.skipped(f"it is on tier {plan.spec.tier if plan.spec else None} now, not {tier}", outcome="moved") + below = _below_use(ctx, plan, cid, ns) + if below: + return StepResult.skipped(f"the new quota is below what its pods request now: {', '.join(below)}", + outcome="below-use", keys=below) + row = ctx.pipeline.submit(sc.actor, plan, repo, JobRepo(s), idempotency_key=sc.key, + body_fingerprint=fingerprint({"operation": sc.key}), + justification=f"Operation {sc.operation.operation_id}: tiers-rerender of tier {tier}") + return StepResult.wait(f"request {row.request_id} is {row.status}", requestId=row.request_id, outcome=row.status) + + +def _below_use(ctx: Any, plan: Any, cluster_id: str, ns: str) -> list[str]: + """The sizable keys whose new hard value is below what the namespace's pods request now (the live quota's status.used).""" + new = own_quota(objects_of(plan.files, "ResourceQuota"), ns) + old = own_quota(objects_of(plan.prev, "ResourceQuota"), ns) + live = own_quota([q for q in ctx.registry.cache(cluster_id).all("ResourceQuota") + if q["metadata"].get("namespace") == ns], ns) + used = ((live or {}).get("status") or {}).get("used") or {} + if new is None or not used: + return [] + change = ctx.cfg.tiers.compare(plan.env, plan.spec.tier, ((old or {}).get("spec") or {}).get("hard") or {}, + plan.spec.tier, new["spec"]["hard"], used=used) + return list(change.below_used) + + +# --------------------------------------------------------------------------- rebuild-verify + + +def _check_known_cluster(ctx: Any, p: dict[str, Any]) -> None: + ctx.registry.get(p["cluster-id"]) # 404 cluster-not-found + + +START_CHECKS["rebuild-verify"] = _check_known_cluster + + +@step("rebuild-verify", "list-folders") +def list_folders(sc: StepContext) -> StepResult: + """Each namespace folder of the cluster on the default branch: clusters//namespaces//.""" + cid = sc.parameters["cluster-id"] + base = f"clusters/{cid}/namespaces/" + from cmapi.core.git.base import GitUnavailable + try: + listed, sha = sc.ctx.git.list_folder(base) + except GitUnavailable as exc: + raise RuntimeError(f"git-unavailable: {exc}") from exc + names = sorted({p[len(base):].split("/", 1)[0] for p in listed if p.startswith(base) and "/" in p[len(base):]}) + return StepResult.done(items=[{"item": n, "clusterId": cid, "namespace": n} for n in names], count=len(names), commit=sha) + + +@step("rebuild-verify", "verify-namespace") +def verify_namespace(sc: StepContext) -> StepResult: + """The folder in Git against the live cluster, by the read that ends a request (#751): each label and annotation, each + quota, LimitRange and grant. A difference is reported, never changed (read-only, docs/07).""" + from cmapi.core.plan_read import read_plan + from cmapi.jobs.watch_sync import _live, _rules + + ctx, item = sc.ctx, sc.item + cid, ns = item["clusterId"], item["namespace"] + files, sha = ctx.pipeline.read_folder(cid, ns) + if not files: + return StepResult.skipped("the folder holds no manifest", outcome="empty") + read = read_plan(_live(ctx.registry.cache(cid)), ns, files, None, **_rules(ctx)) + differences = [d.view() for d in read.differences] + return StepResult.done(outcome="match" if read.ok else "drift", compared=read.compared, commit=sha, + differences=differences[:50], differenceCount=len(differences)) + + +# --------------------------------------------------------------------------- reconcile + + +@step("reconcile", "pause-auto-approval") +def pause_auto_approval(sc: StepContext) -> StepResult: + """docs/01, "Database recovery": "After a restore the auto-approval kill switch starts paused". An admin resumes it + (POST /api/v1/admin/auto-approval:resume) once the report is read.""" + from cmapi.core.observability import AUTO_PAUSED + + switches = SwitchRepo(sc.session) + current = switches.value("auto-approval") or {} + if current.get("paused"): + return StepResult.skipped("auto-approval was paused already", reason=current.get("reason")) + reason = f"operation {sc.operation.operation_id}: reconcile after a restore" + switches.set("auto-approval", {"paused": True, "reason": reason}, sc.starter.username) + AuditRepo(sc.session).record(sc.starter, "auto-approval.pause", "instance", + {"reason": reason, "operationId": sc.operation.operation_id}) + AUTO_PAUSED.set(1) + return StepResult.done(paused=True, reason=reason) + + +@step("reconcile", "find-unrecorded") +def find_unrecorded(sc: StepContext) -> StepResult: + """Each bot branch and open pull request of every cluster (cmapi//...) whose request ID, its last segment as + git_reconcile reads it, the database does not hold.""" + from cmapi.core.git.base import GitUnavailable + from cmapi.core.git.workspace import BRANCH_PREFIX + + ctx, s = sc.ctx, sc.session + found = [] + for cid in sorted(ctx.registry.clusters): + prefix = f"{BRANCH_PREFIX}{cid}/" + try: + prs = ctx.git.list_open(prefix) + branches = ctx.git.list_branches(prefix) + except GitUnavailable as exc: + raise RuntimeError(f"git-unavailable: {exc}") from exc + names = {p.branch for p in prs} | set(branches) + ids = {b: b.rsplit("/", 1)[-1] for b in names} + held = set(s.scalars(select(ChangeRequestRow.request_id).where(ChangeRequestRow.request_id.in_(set(ids.values()))))) + for branch in sorted(names): + if ids[branch] not in held: + pr = next((p for p in prs if p.branch == branch), None) + found.append({"clusterId": cid, "branch": branch, "requestId": ids[branch], + "pr": pr.number if pr else None, "url": pr.url if pr else None}) + return StepResult.done(unrecorded=found, count=len(found)) + + +@step("reconcile", "rebuild-requests") +def rebuild_requests(sc: StepContext) -> StepResult: + count = sc.output("find-unrecorded", "count") or 0 + if not count: + return StepResult.done(note="every bot branch and pull request has its request in the database") + raise StepRefused(f"{count} bot branch(es) or pull request(s) have no request in the database (find-unrecorded lists them): " + "rebuilding a request from its pull request is not built yet (#762). Auto-approval stays paused") + + +# --------------------------------------------------------------------------- cluster-onboard + + +def _check_cluster_id(ctx: Any, p: dict[str, Any]) -> None: + from cmapi.core.operations import valid_cluster_id + if not valid_cluster_id(p["cluster-id"]): + raise Problem(422, "validation-failed", "cluster-id is not a cluster ID", + [{"field": "parameters.cluster-id", "code": "invalid_value", + "message": "1 to 63 letters, digits, '-', '_' or '.', starting and ending with a letter or digit"}]) + + +START_CHECKS["cluster-onboard"] = _check_cluster_id + + +@step("cluster-onboard", "wait-import") +def wait_import(sc: StepContext) -> StepResult: + """docs/02, step 1: "the import Secret appears and the cluster connects". Polled every minute until the step's timeout.""" + cid = sc.parameters["cluster-id"] + st = sc.ctx.registry.clusters.get(cid) + if st is None or st.status != "connected": + status = st.status if st is not None else "not-imported" + return StepResult.wait(f"{cid} is {status}", poll_seconds=60, status=status) + return StepResult.done(status=st.status, serverVersion=st.server_version) + + +@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.""" + 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) + + +@step("cluster-onboard", "propose-registry") +def propose_registry(sc: StepContext) -> StepResult: + cid = sc.parameters["cluster-id"] + st = sc.ctx.registry.get(cid) + if st.policy is not None: + return StepResult.skipped(f"clusters.yaml names {cid} already ({st.policy.environment})", outcome="registered") + raise StepRefused(f"clusters.yaml does not name {cid}, and the step that proposes its entry needs " + "POST /api/v1/admin/clusters:propose, which is not built yet (#761). Until then add the entry by hand, " + "as docs/13 says, and start the operation again") + + +@step("cluster-onboard", "wait-request") +def wait_request(sc: StepContext) -> StepResult: + request_id = sc.input("request-id") + if request_id is None: + return StepResult.skipped("propose-registry opened no request", outcome="registered") + return wait_for_request(sc, request_id) diff --git a/cmapi/src/cmapi/ops/templates/cluster-onboard.yaml b/cmapi/src/cmapi/ops/templates/cluster-onboard.yaml new file mode 100644 index 00000000..130248ed --- /dev/null +++ b/cmapi/src/cmapi/ops/templates/cluster-onboard.yaml @@ -0,0 +1,19 @@ +# 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 +# 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 +# clean up. +name: cluster-onboard +description: Onboard a cluster whose baseline is applied - wait for its import, check it, propose its clusters.yaml entry. +scope: new-cluster +parameters: + - {name: cluster-id, type: string, required: true, description: "The ID the import Secret's cmapi.net/cluster-id names"} +retry: {limit: 3, backoff: 30s, factor: 2} +steps: + - {name: wait-import, timeout: 24h} + - {name: preflight, after: [wait-import]} + - {name: propose-registry, after: [preflight]} + - {name: wait-request, after: [propose-registry], + inputs: {request-id: "{{steps.propose-registry.outputs.request-id}}"}} + - {name: smoke-test, after: [wait-request], notBuilt: "#765"} diff --git a/cmapi/src/cmapi/ops/templates/rebuild-verify.yaml b/cmapi/src/cmapi/ops/templates/rebuild-verify.yaml new file mode 100644 index 00000000..7cfaed46 --- /dev/null +++ b/cmapi/src/cmapi/ops/templates/rebuild-verify.yaml @@ -0,0 +1,15 @@ +# docs/07, the template catalogue: after a rebuild, "Fan out per namespace folder: Git against live [...]; drift report". +# Read-only: each namespace folder of the cluster in Git is read against the live cluster with the read that ends a request +# (core/plan_read.py, #751), and each difference goes into the report. Nothing is written to Git or to the cluster. +name: rebuild-verify +description: Read every namespace folder of one cluster in Git against the live cluster and report each difference. +scope: cluster +parameters: + - {name: cluster-id, type: string, required: true, description: "The cluster that was rebuilt"} + - {name: parallelism, type: integer, default: 10, minimum: 1, maximum: 100, + description: "At most this many namespaces read at once"} +retry: {limit: 3, backoff: 30s, factor: 2} +steps: + - {name: list-folders} + - {name: verify-namespace, after: [list-folders], withParam: "{{steps.list-folders.outputs.items}}", + parallelism: "{{parameters.parallelism}}"} diff --git a/cmapi/src/cmapi/ops/templates/reconcile.yaml b/cmapi/src/cmapi/ops/templates/reconcile.yaml new file mode 100644 index 00000000..2aadd8d3 --- /dev/null +++ b/cmapi/src/cmapi/ops/templates/reconcile.yaml @@ -0,0 +1,16 @@ +# docs/02, Worker jobs: "reconcile | After a restore, or on demand | Rebuilds open requests from bot PRs; auto-approval starts +# paused". docs/01, "Database recovery": after a restore "the auto-approval kill switch starts paused, and a reconcile job +# rebuilds requests already in Git (pr_open and later) from the bot's branches and PR bodies". This run pauses auto-approval, +# finds each bot branch and pull request whose request the database does not hold, and stops at the rebuild, which is not +# built yet: the report names each one to rebuild by hand. +name: reconcile +description: After a database restore, pause auto-approval and find the bot pull requests whose requests the database lacks. +scope: instance +# Pausing auto-approval is an admin's switch (approvals:pause, routers/admin.py): the starter holds it too. +permissions: [approvals:pause] +parameters: [] +retry: {limit: 3, backoff: 30s, factor: 2} +steps: + - {name: pause-auto-approval} + - {name: find-unrecorded, after: [pause-auto-approval]} + - {name: rebuild-requests, after: [find-unrecorded]} diff --git a/cmapi/src/cmapi/ops/templates/tiers-rerender.yaml b/cmapi/src/cmapi/ops/templates/tiers-rerender.yaml new file mode 100644 index 00000000..cc7f36bc --- /dev/null +++ b/cmapi/src/cmapi/ops/templates/tiers-rerender.yaml @@ -0,0 +1,19 @@ +# docs/02, "Changing a tier": after a PR to tiers.yaml, the namespaces rendered from the older catalog are tier-outdated. This +# run opens one ordinary update request per outdated namespace, in batches, through the normal approval rules, and waits for +# each to reach a final state. A decrease below what the namespace's pods request now is skipped and listed in the report. +name: tiers-rerender +description: Re-render the namespaces of one tier whose cmapi.net/tier-hash is not the catalog's, one update request each. +scope: environments +parameters: + - {name: tier, type: string, required: true, description: "The tier whose namespaces are rendered again"} + - {name: environments, type: list, required: true, description: "The environments to re-render it in"} + - {name: clusterSelector, type: selector, description: "Only the clusters whose labels match: {matchLabels: {...}}"} + - {name: batchSize, type: integer, default: 20, minimum: 1, maximum: 200, + description: "At most this many requests of the run open at once"} + - {name: maxOpenPerCluster, type: integer, default: 5, minimum: 1, maximum: 50, + description: "At most this many requests of the run open at once on one cluster"} +retry: {limit: 3, backoff: 30s, factor: 2} +steps: + - {name: select-outdated} + - {name: rerender-namespace, after: [select-outdated], withParam: "{{steps.select-outdated.outputs.items}}", + parallelism: "{{parameters.batchSize}}", perCluster: "{{parameters.maxOpenPerCluster}}"} diff --git a/cmapi/src/cmapi/routers/operations.py b/cmapi/src/cmapi/routers/operations.py new file mode 100644 index 00000000..d8a7c04b --- /dev/null +++ b/cmapi/src/cmapi/routers/operations.py @@ -0,0 +1,317 @@ +"""The operations router (docs/02, routers/operations.py; story #26, criterion 3): start a template, list the runs, read one as +the status of record, and cancel one. "The same on every engine" (docs/02): the engine named in integrations.yaml runs the +steps; this build has the built-in engine, which runs them in the cmapi worker with their state in PostgreSQL. + +Each route needs `operations:run` where the run acts: in each environment a tiers-rerender names, in the environment of the +cluster that rebuild-verify or cluster-onboard names, and in every environment (an unrestricted grant) for a run of the whole +instance or of a cluster that clusters.yaml does not name yet, as `:probe` asks for an import with no environment (routers/me.py). +""" +from __future__ import annotations + +from datetime import datetime +from typing import Annotated, Any, Literal + +from fastapi import Depends, Header, Path, Query +from pydantic import Field +from sqlalchemy import select +from starlette.convertors import StringConvertor, register_url_convertor + +from cmapi import __version__ +from cmapi.core.config import environment_not_served +from cmapi.core.context import AppContext +from cmapi.core.db.models import OperationRow, OperationStepRow +from cmapi.core.db.repo import AuditRepo, fingerprint, utcnow +from cmapi.core.docs import DocumentedRouter +from cmapi.core.errors import Problem +from cmapi.core.identity.claims import Identity +from cmapi.core.listquery import ListQuery +from cmapi.core.models import Api, PageInfo, RequestBody +from cmapi.core.observability import AUTHZ_DENIED +from cmapi.core.operations import FINAL_RUN, OperationTemplate, lock_engine, new_operation_id, progress +from cmapi.routers import Cursor, Limit, ctx, require + +PERMISSION = "operations:run" + +router = DocumentedRouter("operations", prefix="/api/v1", version=__version__, group="Operations", + description="Operations: runs of a template of steps (tiers-rerender, rebuild-verify, reconcile, " + "cluster-onboard) that report each step's progress, retry a step that fails, and open " + "ordinary requests, approved as any request is, for every change they make.") + +RunPhase = Literal["Pending", "Running", "Succeeded", "Failed", "Error", "Stopped"] +StepPhase = Literal["Pending", "Running", "Waiting", "Succeeded", "Skipped", "Failed", "Error", "Stopped"] +OperationId = Annotated[str, Path(description="The operation's ID, as the start returned it.", examples=["op-20261201-3f9a1c2e"])] + + +class OperationIdConvertor(StringConvertor): + """An operation ID in a path: never a colon, which starts a custom method (Google AIP-136), as RequestIdConvertor + (routers/requests.py) keeps `:cancel` from reading as an ID.""" + regex = "[^/:]+" + + +register_url_convertor("operation_id", OperationIdConvertor()) + + +class OperationStart(RequestBody): + template: str = Field(description="The template to run: `tiers-rerender`, `rebuild-verify`, `reconcile` or " + "`cluster-onboard`", examples=["tiers-rerender"]) + parameters: dict[str, Any] = Field(default_factory=dict, + description="The template's parameters. tiers-rerender: `tier`, `environments`, and " + "optionally `clusterSelector` ({matchLabels}), `batchSize` (default 20) and " + "`maxOpenPerCluster` (default 5). rebuild-verify: `cluster-id`, and " + "optionally `parallelism` (default 10). cluster-onboard: `cluster-id`. " + "reconcile: none", + examples=[{"tier": "small", "environments": ["dev"]}]) + + +class OperationStep(Api): + step: str = Field(description="The step's name in its template", examples=["rerender-namespace"]) + item: str = Field(description="The fan-out item, such as `/`; empty for a step that is not fanned out", + examples=["CRC/payments-dev"]) + cluster_id: str = Field(description="The item's cluster; empty when the step is not about one cluster", examples=["CRC"]) + phase: StepPhase = Field(description="Pending (not started), Running (queued or running now), Waiting (for a request, an " + "import or a retry's backoff), or final: Succeeded, Skipped, Failed, Error (the " + "engine failed) or Stopped (cancelled)", examples=["Waiting"]) + attempts: int = Field(description="Failed attempts so far; the template's retry block retries until its limit", + examples=[0]) + outputs: dict[str, Any] | None = Field(description="What the step recorded: a request it opened (`requestId`), its " + "`outcome`, a `note`, and the step's own results", + examples=[{"requestId": "req-20261201-0001", "outcome": "pending_approval", + "note": "request req-20261201-0001 is pending_approval"}]) + last_error: str | None = Field(description="The last failure, with the problem code where there is one", + examples=[None]) + started_at: datetime | None = Field(description="When the step first ran", examples=["2026-12-01T10:00:00Z"]) + finished_at: datetime | None = Field(description="When it reached a final phase", examples=[None]) + + +class OperationProgress(Api): + total: int = Field(description="Step rows so far: a fan-out step has one per item", examples=[4]) + finished: int = Field(description="Rows in a final phase", examples=[1]) + phases: dict[str, int] = Field(description="Rows in each phase", examples=[{"Succeeded": 1, "Waiting": 3}]) + + +class OperationLinks(Api): + self: str = Field(description="This operation", examples=["/api/v1/operations/op-20261201-3f9a1c2e"]) + cancel: str = Field(description="Where to cancel it", examples=["/api/v1/operations/op-20261201-3f9a1c2e:cancel"]) + + +class OperationSummary(Api): + operation_id: str = Field(description="The operation's ID", examples=["op-20261201-3f9a1c2e"]) + template: str = Field(description="The template it runs", examples=["tiers-rerender"]) + engine: str = Field(description="The engine that runs it", examples=["builtin"]) + run_name: str = Field(description="The run's name on its engine: the operation's ID on the built-in engine", + examples=["op-20261201-3f9a1c2e"]) + phase: RunPhase = Field(description="Pending, Running, or final: Succeeded, Failed (a step failed), Error (the engine " + "failed) or Stopped (cancelled)", examples=["Running"]) + parameters: dict[str, Any] = Field(description="The parameters it was started with, with their defaults", + examples=[{"tier": "small", "environments": ["dev"], "batchSize": 20, + "maxOpenPerCluster": 5}]) + environments: list[str] | None = Field(description="Where it acts; null for the whole instance", examples=[["dev"]]) + started_by: str = Field(description="The username of the person who started it", examples=["opal"]) + started_at: datetime = Field(description="When it started", examples=["2026-12-01T10:00:00Z"]) + finished_at: datetime | None = Field(description="When it ended", examples=[None]) + cancel_requested_by: str | None = Field(description="Who asked to cancel it", examples=[None]) + cancel_requested_at: datetime | None = Field(description="When", examples=[None]) + progress: OperationProgress = Field(description="Its step rows, counted by phase") + links: OperationLinks = Field(description="Links") + + +class Operation(OperationSummary): + steps: list[OperationStep] = Field(description="Every step row, in the template's order") + report: dict[str, Any] | None = Field(description="Once it ended: each step's rows by phase, and each item that did not " + "succeed, or that found something, with why", + examples=[None]) + + +class OperationPage(Api): + items: list[OperationSummary] = Field(description="One page of operations, newest first") + page: PageInfo = Field(description="Paging") + letters: dict[str, int] = Field(description="Rows per first letter of the template", examples=[{"T": 2}]) + + +def start_key(idempotency_key: str | None = Header(default=None, alias="Idempotency-Key", + examples=["0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10"], + description="A new random value for each new operation, such as a UUID, " + "of at most 100 characters. Required. The same caller sending " + "the same body with the same key gets the operation it " + "started, in its current state, for as long as the operation " + "is kept; the same key with another body is 409 " + "`idempotency-replay`.")) -> str: + if not idempotency_key: + raise Problem.bad_request("idempotency-key-required", "Idempotency-Key header is required on writes") + if len(idempotency_key) > 100: + raise Problem.bad_request("idempotency-key-required", "Idempotency-Key is at most 100 characters") + return idempotency_key + + +def _require(c: AppContext, who: Identity, permission: str, environments: list[str] | None) -> None: + """The permission in each environment where the run acts; for a run with none named, an unrestricted grant (env "").""" + try: + for env in environments or [""]: + if not c.cfg.roles.allowed(who, permission, env): + if env and c.cfg.roles.allowed(who, permission): + c.cfg.roles.require(who, permission, env) # 403 environment-forbidden, naming where it holds + raise Problem.forbidden(f"Missing permission {permission} " + + (f"in {env}" if env else "in every environment: this operation acts on the " + "whole instance or on a cluster with no environment"), + code="environment-forbidden" if c.cfg.roles.allowed(who, permission) else "forbidden") + except Problem: + AUTHZ_DENIED.labels(permission).inc() + raise + + +def _environments(c: AppContext, template: OperationTemplate, p: dict[str, Any]) -> list[str] | None: + """Where a run of this template acts, from its parameters: what the permission is checked in.""" + if template.scope == "environments": + for env in p["environments"]: + if env not in c.cfg.allowed_environments: + raise environment_not_served(c.cfg, env) + return sorted(p["environments"]) + if template.scope in ("cluster", "new-cluster"): + st = c.registry.clusters.get(p["cluster-id"]) + if st is None and template.scope == "cluster": + c.registry.get(p["cluster-id"]) # 404 cluster-not-found + return [st.environment] if st is not None and st.environment else None + return None + + +def view(row: OperationRow, steps: list[OperationStepRow] | None) -> dict[str, Any]: + out = {"operationId": row.operation_id, "template": row.template, "engine": row.engine, "runName": row.run_name, + "phase": row.phase, "parameters": row.parameters, "environments": row.environments, + "startedBy": row.started_by.get("username"), "startedAt": row.started_at, "finishedAt": row.finished_at, + "cancelRequestedBy": row.cancel_requested_by, "cancelRequestedAt": row.cancel_requested_at, + "links": {"self": f"/api/v1/operations/{row.operation_id}", + "cancel": f"/api/v1/operations/{row.operation_id}:cancel"}} + return out if steps is None else {**out, "steps": [_step_view(r) for r in steps]} + + +def _step_view(r: OperationStepRow) -> dict[str, Any]: + return {"step": r.step, "item": r.item, "clusterId": r.cluster_id, "phase": r.phase, "attempts": r.attempts, + "outputs": r.outputs, "lastError": r.last_error, "startedAt": r.started_at, "finishedAt": r.finished_at} + + +def _full(c: AppContext, s: Any, row: OperationRow) -> dict[str, Any]: + template = c.operations.templates.get(row.template) + rows = list(s.scalars(select(OperationStepRow).where(OperationStepRow.operation_id == row.operation_id))) + order = {st.name: i for i, st in enumerate(template.steps)} if template else {} + rows.sort(key=lambda r: (order.get(r.step, len(order)), r.item)) + return {**view(row, rows), "progress": progress(rows), "report": row.report} + + +def _get(s: Any, operation_id: str, *, lock: bool = False) -> OperationRow: + q = select(OperationRow).where(OperationRow.operation_id == operation_id) + row = s.scalars(q.with_for_update() if lock else q).first() + if row is None: + raise Problem(404, "object-not-found", f"No operation {operation_id}") + return row + + +@router.write("/operations", summary="Start an operation", + returns="The operation, started: its first steps are queued for the worker. `links.self` is its status.", + permission=PERMISSION, response_model=Operation, + problems=["operation-template-unknown", "validation-failed", "environment-forbidden", "environment-not-served", + "cluster-not-found", "policy-violation", "idempotency-key-required", + "idempotency-replay", "operations-engine-unavailable"]) +def start(body: OperationStart, key: str = Depends(start_key), who: Identity = Depends(require(PERMISSION)), + c: AppContext = Depends(ctx)) -> dict: + """Starts a run of a template on the engine that integrations.yaml names. The answer comes before any step runs; read + `GET /api/v1/operations/{id}` for its progress. A step that changes a namespace opens an ordinary request, which the + approval rules decide as any other: the run waits for each one, and the person who started the run cannot approve them. + Runs start only through this call (docs/02, rule 2).""" + from cmapi.ops import START_CHECKS + + c.operations.check_available() + template = c.operations.template(body.template) + params = template.validate(body.parameters) + environments = _environments(c, template, params) + for permission in (PERMISSION, *template.permissions): + _require(c, who, permission, environments) + if template.name in START_CHECKS: + START_CHECKS[template.name](c, params) + sent = fingerprint({"template": body.template, "parameters": body.parameters}) + with c.db.session() as s: + held = s.scalars(select(OperationRow).where(OperationRow.started_by_sub == who.sub, + OperationRow.idempotency_key == key)).first() + if held is not None: + if held.idempotency_fingerprint != sent: + raise Problem.conflict("idempotency-replay", "Idempotency-Key was used for a different operation", + operationId=held.operation_id) + return _full(c, s, held) + op_id = new_operation_id() + row = OperationRow(operation_id=op_id, template=template.name, parameters=params, engine=c.operations.engine.name, + run_name=op_id, phase="Pending", environments=environments, started_by_sub=who.sub, + started_by={**who.record(), "roles": sorted(who.roles), "groups": sorted(who.groups)}, + idempotency_key=key, idempotency_fingerprint=sent, updated_at=utcnow()) + s.add(row) + s.flush() + row.run_name = c.operations.engine.submit(s, row, template) + AuditRepo(s).record(who, "operation.start", op_id, {"template": template.name, "parameters": params}) + return _full(c, s, row) + + +@router.read("/operations", summary="List operations", + returns="One page of operations, newest first, each with its progress.", + permission=PERMISSION, response_model=OperationPage, + problems=["invalid-cursor", "invalid-limit", "validation-failed"]) +def list_operations( + template: str | None = Query(default=None, examples=["tiers-rerender"], description="Only the runs of this template."), + phase: RunPhase | None = Query(default=None, examples=["Running"], description="Only the runs in this phase."), + limit: Limit = 50, + cursor: Cursor = None, + who: Identity = Depends(require(PERMISSION)), c: AppContext = Depends(ctx)) -> dict: + """The operations that the caller may run where they act, newest first, with each one's progress.""" + with c.db.session() as s: + q = select(OperationRow) + if template: + q = q.where(OperationRow.template == template) + if phase: + q = q.where(OperationRow.phase == phase) + rows = [r for r in s.scalars(q) if all(c.cfg.roles.allowed(who, PERMISSION, e) for e in (r.environments or [""]))] + counts: dict[str, list[OperationStepRow]] = {r.operation_id: [] for r in rows} + if rows: + for st in s.scalars(select(OperationStepRow).where(OperationStepRow.operation_id.in_(list(counts)))): + counts[st.operation_id].append(st) + # The shared sort "newest" breaks a tie by name, then by clusterId: here the operation's ID, so the order is total. + paging = [{"name": r.template, "clusterId": r.operation_id, "_created": r.started_at.timestamp(), "_row": r} + for r in rows] + page = c.lister.page(paging, ListQuery(q="", sort="newest", limit=limit, cursor=cursor, + context={"template": template or "", "phase": phase or ""})) + page["items"] = [{**view(it["_row"], None), "progress": progress(counts[it["_row"].operation_id])} + for it in page["items"]] + return page + + +@router.read("/operations/{operation_id:operation_id}", summary="Get an operation", + returns="The operation with every step row: its phase, attempts, outputs and last error; and its report once " + "it ended.", + permission=PERMISSION, response_model=Operation, problems=["object-not-found", "environment-forbidden"]) +def get_operation(operation_id: OperationId, who: Identity = Depends(require(PERMISSION)), c: AppContext = Depends(ctx)) -> dict: + """The status of record of one operation (docs/02): each step row with its phase, the requests it opened and why any + did not succeed.""" + with c.db.session() as s: + row = _get(s, operation_id) + _require(c, who, PERMISSION, row.environments) + return _full(c, s, row) + + +@router.write("/operations/{operation_id}:cancel", summary="Cancel an operation", + returns="The operation: no new step starts, the steps not started and the steps waiting are Stopped, and it " + "ends Stopped once the step that runs now ends.", + permission=PERMISSION, response_model=Operation, status_code=200, + problems=["object-not-found", "invalid-transition", "environment-forbidden"]) +def cancel(operation_id: OperationId, who: Identity = Depends(require(PERMISSION)), c: AppContext = Depends(ctx)) -> dict: + """Stops a run that has not ended. A request that a step opened is not cancelled with it: it is an ordinary request, + which its requester or an operator cancels on its own (`POST /api/v1/requests/{id}:cancel`); the report lists it. A + second cancel returns the operation as it is.""" + with c.db.session() as s: + # The engine's lock before the run's row, in the order every scheduler pass takes them (a step's job takes the engine's + # lock, then the runs' rows): the other order would deadlock with a step of this run that ends now. + lock_engine(s) + row = _get(s, operation_id, lock=True) + _require(c, who, PERMISSION, row.environments) + if row.phase in FINAL_RUN: + raise Problem.conflict("invalid-transition", f"{operation_id} ended {row.phase}", state=row.phase) + if row.cancel_requested_at is None: + row.cancel_requested_by, row.cancel_requested_at, row.updated_at = who.username, utcnow(), utcnow() + AuditRepo(s).record(who, "operation.cancel", operation_id, None) + c.operations.engine_for(row).cancel(s, row) + return _full(c, s, row) diff --git a/cmapi/src/cmapi/worker.py b/cmapi/src/cmapi/worker.py index f9761f64..0258384a 100644 --- a/cmapi/src/cmapi/worker.py +++ b/cmapi/src/cmapi/worker.py @@ -34,6 +34,7 @@ from cmapi.core.git.oplog import git_context from cmapi.core.kpi import register_collectors from cmapi.core.lifecycle import Event as E, State as S +from cmapi.core.operations import STEP_JOB, job_gave_up from cmapi.core.observability import (JOB_FAILURES, JOBS_PENDING, OPEN_REQUEST_AGE, REQUESTS_IN_STATE, configure_logging, log, start_metrics) from cmapi.jobs import HANDLERS, RECURRING @@ -148,6 +149,8 @@ def _record_failure(self, job_id: int, kind: str, request_id: str | None, attemp JobRepo(s).assert_lease(job_id, self.worker_id, generation) if attempts >= MAX_ATTEMPTS or kind in RECURRING: jobs.done(job) + if kind == STEP_JOB: + job_gave_up(self.ctx, s, job.payload or {}, err) # the step's row ends Error, and its run with it (#26) if request_id and kind not in RECURRING: row = repo.get(request_id) repo.event(row, "error", "worker", err[:300]) diff --git a/cmapi/tests/service/conftest.py b/cmapi/tests/service/conftest.py index fbab1a4b..1ce62b96 100644 --- a/cmapi/tests/service/conftest.py +++ b/cmapi/tests/service/conftest.py @@ -495,9 +495,10 @@ def database() -> Database: @pytest.fixture def fresh_db(database: Database) -> Database: with database.engine.begin() as c: - # The usage tables of #310 are truncated where the migrations made them: a run of an older src (the before-run of a - # fix) migrates to its own head, without them. - usage = [t for t in ("analysis_sweeps", "namespace_verdicts", "capacity_snapshots", "capacity_reservations") + # The usage tables of #310, and the operations tables of #26, are truncated where the migrations made them: a run of + # an older src (the before-run of a fix) migrates to its own head, without them. + usage = [t for t in ("analysis_sweeps", "namespace_verdicts", "capacity_snapshots", "capacity_reservations", + "operation_steps", "operations") if c.execute(text("SELECT to_regclass(:t)"), {"t": t}).scalar() is not None] c.execute(text("TRUNCATE change_requests, request_events, approvals, jobs, audit_events, admin_switches, " "approval_notifications, expiration_notices, policy_rejections" diff --git a/cmapi/tests/service/test_api_samples.py b/cmapi/tests/service/test_api_samples.py index 7a735dd0..1a820a4b 100644 --- a/cmapi/tests/service/test_api_samples.py +++ b/cmapi/tests/service/test_api_samples.py @@ -119,15 +119,17 @@ def differences(a: Any, b: Any, path: str = "") -> list[str]: REQUEST_ID = re.compile(r"req-\d{8}-\d{4}") +OPERATION_ID = re.compile(r"op-\d{8}-[0-9a-f]{8}") def fixed(sample: dict[str, Any]) -> dict[str, Any]: """What a sample must keep exactly from one run to the next (#183): the method, the path, the status, the media type and, for a problem, its type, title, status and code, and for a create's dry run its metadata: each final value with its source, - the same at each run (#479, R9). A request ID in the path has the date and a counter, so it is made neutral. + the same at each run (#479, R9). A request ID in the path has the date and a counter, and an operation ID the date and a + random part (#26), so each is made neutral. The other values differ at each run (IDs, times, etags, cursors) and are held by their shape only.""" request, response = sample["request"], sample["response"] - out = {"method": request["method"], "path": REQUEST_ID.sub("req-", request["path"]), + out = {"method": request["method"], "path": OPERATION_ID.sub("op-", REQUEST_ID.sub("req-", request["path"])), "status": response["status"], "contentType": response["contentType"]} if request["method"] == "POST" and request["path"].endswith("/namespaces?dryRun=true") and response["status"] == 200: out["metadata"] = response["body"]["metadata"] @@ -486,6 +488,20 @@ def etag_of(ns: str) -> str: rec.call("adoption_adopt", "POST", f"{adopt_url}?dryRun=true", ola, json_body={"labels": {"company.net/lob": "other"}}) # 422 adoption-key-held + # ---- operations (story #26, criterion 3): a tiers-rerender started, listed, read and cancelled on the built-in engine + started = rec.call("operations_start", "POST", "/api/v1/operations", opal, key=True, + json_body={"template": "tiers-rerender", "parameters": {"tier": "small", "environments": ["dev"]}}) + assert started.status_code == 202, started.text + op_url = f"/api/v1/operations/{started.json()['operationId']}" + rec.call("operations_list_operations", "GET", "/api/v1/operations?template=tiers-rerender", opal) + cancelled = rec.call("operations_cancel", "POST", f"{op_url}:cancel", opal) + assert cancelled.status_code == 200, cancelled.text + run_jobs(ctx) + rec.call("operations_get_operation", "GET", op_url, opal) + rec.call("operations_cancel", "POST", f"{op_url}:cancel", opal) # 409 ended + rec.call("operations_start", "POST", "/api/v1/operations", opal, key=True, + json_body={"template": "tier-rerender", "parameters": {}}) # 422 unknown template + data = {"operations": dict(sorted(rec.operations.items())), "problems": dict(sorted(rec.problems.items())), "operationProblems": dict(sorted(rec.operation_problems.items()))} spec = client.get("/openapi.json").json() diff --git a/cmapi/tests/service/test_operations_26.py b/cmapi/tests/service/test_operations_26.py new file mode 100644 index 00000000..f5613f8e --- /dev/null +++ b/cmapi/tests/service/test_operations_26.py @@ -0,0 +1,492 @@ +"""Story #26, criterion 3: "Built-in cluster-onboard, rebuild-verify, reconcile and tier re-render operations report progress, +survive retries and honor approvals; optional workflow engines are not required." + +The built-in engine (core/operations.py) runs each template's steps (cmapi/ops) in the worker, with their state in PostgreSQL: +nothing here runs Argo Workflows or Tekton. Each test drives the API and the worker's jobs end to end with the suite's fakes. +""" +from __future__ import annotations + +import shutil +import uuid + +import pytest +import yaml +from sqlalchemy import select, text, update + +from cmapi.core.db.models import ChangeRequestRow, JobRow, OperationRow +from cmapi.core.db.repo import JobRepo, SwitchRepo, utcnow +from cmapi.core.git.workspace import BRANCH_PREFIX +from cmapi.jobs import HANDLERS +from conftest import build_world +from test_flow import AMY, NS, OLA, OPAL, auth, run_jobs +from test_review_h_tools_migrate import empty_schema, migrate # noqa: F401 (empty_schema is a fixture) + +URL = "/api/v1/operations" +ADMIN = dict(roles=["cmapi-admin"], groups=["/cmapi/app-cmapi-rbac-admin"]) +VIEWER = dict(roles=["cmapi-viewer"], groups=[]) +SMALL_CPU = "8" # the nonprod catalog's tier small (examples/instances/nonprod/tiers.yaml) + + +def created(world, name: str) -> None: + """A namespace on tier small, created, merged and synced (auto-approved in dev).""" + client, ctx, git, kube, validator, keys = world + r = client.post("/api/v1/clusters/CRC/namespaces", json={**NS, "namespace": name}, headers=auth(keys, "ola", **OLA)) + assert r.status_code == 202, r.text + run_jobs(ctx) + assert client.get(f"/api/v1/requests/{r.json()['requestId']}", headers=auth(keys, "ola", **OLA)).json()["status"] == "synced" + + +def outdated(world, name: str, cpu: str, used_cpu: str | None = None) -> None: + """Git and the cluster hold -quota as an older catalog rendered it: requests.cpu `cpu` and another tier hash. The watch + cache is relisted, and from then on follows each apply as a watch event (FakeKube.live_watch), so the read that ends each + request of the run sees what the delivery applied. `used_cpu`: what the namespace's pods request now.""" + client, ctx, git, kube, validator, keys = world + kube.live_watch = True + path = f"clusters/CRC/namespaces/{name}/resourcequota-{name}-quota.yaml" + rq = yaml.safe_load(git.branches["main"][path]) + rq["spec"]["hard"]["requests.cpu"] = cpu + rq["metadata"]["annotations"]["cmapi.net/tier-hash"] = "0123456789ab" + git.branches["main"][path] = yaml.safe_dump(rq, sort_keys=False) + git._sha("main") + live = kube.apply(rq) + if used_cpu is not None: + live["status"]["used"]["requests.cpu"] = used_cpu + ctx.registry.cache("CRC")._list("Namespace") + ctx.registry.cache("CRC")._list("ResourceQuota") + + +def start(world, template: str, parameters: dict, who=("opal", OPAL), key: str | None = None): + client, ctx, git, kube, validator, keys = world + headers = auth(keys, who[0], **who[1]) + if key: + headers["Idempotency-Key"] = key + return client.post(URL, json={"template": template, "parameters": parameters}, headers=headers) + + +def get(world, op_id: str, who=("opal", OPAL)) -> dict: + client, ctx, git, kube, validator, keys = world + r = client.get(f"{URL}/{op_id}", headers=auth(keys, who[0], **who[1])) + assert r.status_code == 200, r.text + return r.json() + + +def polls_due(ctx) -> None: + """Make the waiting steps' next polls due now, as the 30 seconds of a poll would.""" + with ctx.db.session() as s: + s.execute(update(JobRow).where(JobRow.kind == "operation_step", JobRow.done_at.is_(None)).values(run_after=utcnow())) + + +def drive(ctx, rounds: int = 6) -> None: + for _ in range(rounds): + polls_due(ctx) + if not run_jobs(ctx, limit=50): + break + + +def rows_of(view: dict, step: str) -> list[dict]: + return [r for r in view["steps"] if r["step"] == step] + + +# --------------------------------------------------------------------------- tiers-rerender + + +def test_tiers_rerender_reports_progress_and_honours_the_approval_rules(world): + """Two outdated namespaces: one whose re-render raises its quota by 300% (quotaIncreasePct > 100 adds approver-platform), + one by 33% (a change needs no approval in dev). One current namespace is not selected. The run waits on the first until a + platform approver approves it; the person who started the run is its requester and is recorded with the step's client.""" + client, ctx, git, kube, validator, keys = world + for name in ("big-raise", "small-raise", "current"): + created(world, name) + outdated(world, "big-raise", "2") + outdated(world, "small-raise", "6") + + r = start(world, "tiers-rerender", {"tier": "small", "environments": ["dev"]}) + assert r.status_code == 202, r.text + op = r.json() + assert op["phase"] == "Running" and op["engine"] == "builtin" and op["startedBy"] == "opal" + assert op["parameters"] == {"tier": "small", "environments": ["dev"], "batchSize": 20, "maxOpenPerCluster": 5} + assert [(s["step"], s["phase"]) for s in op["steps"]] == [("select-outdated", "Running")] + op_id = op["operationId"] + + drive(ctx) + view = get(world, op_id) + select_row = rows_of(view, "select-outdated")[0] + assert select_row["phase"] == "Succeeded" and select_row["outputs"]["count"] == 2, select_row + items = {r["item"]: r for r in rows_of(view, "rerender-namespace")} + assert set(items) == {"CRC/big-raise", "CRC/small-raise"} + # small-raise needed no approval and synced; big-raise waits for approver-platform. + assert items["CRC/small-raise"]["phase"] == "Succeeded" and items["CRC/small-raise"]["outputs"]["outcome"] == "synced" + waiting = items["CRC/big-raise"] + assert waiting["phase"] == "Waiting" and waiting["outputs"]["outcome"] == "pending_approval", waiting + assert view["phase"] == "Running" and view["progress"]["phases"] == {"Succeeded": 2, "Waiting": 1} + + rid = waiting["outputs"]["requestId"] + req = client.get(f"/api/v1/requests/{rid}", headers=auth(keys, "amy", **AMY)).json() + assert req["status"] == "pending_approval" and req["reason"] == "operation:tiers-rerender" + with ctx.db.session() as s: + row = s.get(ChangeRequestRow, rid) + # docs/02, rule 4: the request records the step's client and the person who started the run. + assert (row.requester_username, row.requester_sub, row.requester_kind, row.requester_client) == \ + ("opal", "sub-opal", "service", "svc-cmapi-workflows") + assert row.requester["submittedByClient"] == "svc-cmapi-workflows" and row.requester["automated"] is True + + drive(ctx) # nothing moves without the approval + assert rows_of(get(world, op_id), "rerender-namespace")[0]["phase"] == "Waiting" + r = client.post(f"/api/v1/requests/{rid}:approve", json={"comment": "catalog raise"}, headers=auth(keys, "amy", **AMY)) + assert r.status_code == 200 and r.json()["status"] == "approved", r.text + drive(ctx) + view = get(world, op_id) + assert view["phase"] == "Succeeded", view + assert {r["item"]: r["phase"] for r in rows_of(view, "rerender-namespace")} == \ + {"CRC/big-raise": "Succeeded", "CRC/small-raise": "Succeeded"} + assert view["report"]["steps"][1]["phases"] == {"Succeeded": 2} + quota = yaml.safe_load(git.branches["main"]["clusters/CRC/namespaces/big-raise/resourcequota-big-raise-quota.yaml"]) + assert quota["spec"]["hard"]["requests.cpu"] == SMALL_CPU + assert quota["metadata"]["annotations"]["cmapi.net/tier-hash"] != "0123456789ab" + + +def test_a_decrease_below_current_use_is_skipped_and_listed(world): + """docs/02: "a decrease below current use is skipped and listed in the operation report".""" + client, ctx, git, kube, validator, keys = world + created(world, "busy") + outdated(world, "busy", "16", used_cpu="12") # the catalog's 8 is below the 12 cores its pods request + op_id = start(world, "tiers-rerender", {"tier": "small", "environments": ["dev"]}).json()["operationId"] + drive(ctx) + view = get(world, op_id) + row = rows_of(view, "rerender-namespace")[0] + assert row["phase"] == "Skipped" and row["outputs"]["outcome"] == "below-use" and row["outputs"]["keys"] == ["requests.cpu"] + assert view["phase"] == "Succeeded" + assert view["report"]["steps"][1]["items"][0]["outcome"] == "below-use" + with ctx.db.session() as s: + assert s.scalar(select(ChangeRequestRow.request_id).where(ChangeRequestRow.reason == "operation:tiers-rerender")) is None + + +def test_a_rejected_request_is_reported_and_the_run_goes_on(world): + client, ctx, git, kube, validator, keys = world + created(world, "big-raise") + outdated(world, "big-raise", "2") + op_id = start(world, "tiers-rerender", {"tier": "small", "environments": ["dev"]}).json()["operationId"] + drive(ctx) + rid = rows_of(get(world, op_id), "rerender-namespace")[0]["outputs"]["requestId"] + r = client.post(f"/api/v1/requests/{rid}:reject", json={"comment": "not now"}, headers=auth(keys, "amy", **AMY)) + assert r.status_code == 200, r.text + drive(ctx) + view = get(world, op_id) + row = rows_of(view, "rerender-namespace")[0] + assert row["phase"] == "Skipped" and row["outputs"]["outcome"] == "rejected" + assert view["phase"] == "Succeeded" and view["report"]["steps"][1]["items"][0]["requestId"] == rid + + +def test_a_step_that_fails_is_retried_with_backoff_and_then_succeeds(world): + """The template's retry block: the Git host down when the step reads the folder is a 502, retried; the row shows the + attempt and the error, and the run carries on once the host answers.""" + client, ctx, git, kube, validator, keys = world + created(world, "small-raise") + outdated(world, "small-raise", "6") + op_id = start(world, "tiers-rerender", {"tier": "small", "environments": ["dev"]}).json()["operationId"] + assert run_jobs(ctx, limit=1) == ["operation_step"] # select-outdated, which queues the item's step + git.down = True + polls_due(ctx) + run_jobs(ctx) + row = rows_of(get(world, op_id), "rerender-namespace")[0] + assert row["phase"] == "Waiting" and row["attempts"] == 1 and "git-unavailable" in row["lastError"], row + with ctx.db.session() as s: + job = s.scalars(select(JobRow).where(JobRow.kind == "operation_step", JobRow.done_at.is_(None))).one() + assert 25 <= (job.run_after - utcnow()).total_seconds() <= 31 # backoff 30s, the first retry + git.down = False + drive(ctx) + view = get(world, op_id) + assert view["phase"] == "Succeeded" and rows_of(view, "rerender-namespace")[0]["attempts"] == 1 + + +def test_a_step_out_of_retries_fails_the_run(world): + client, ctx, git, kube, validator, keys = world + created(world, "small-raise") + outdated(world, "small-raise", "6") + op_id = start(world, "tiers-rerender", {"tier": "small", "environments": ["dev"]}).json()["operationId"] + assert run_jobs(ctx, limit=1) == ["operation_step"] + git.down = True + drive(ctx, rounds=8) + view = get(world, op_id) + row = rows_of(view, "rerender-namespace")[0] + # limit 3: "the maximum number of total attempts will be limit + 1" (Argo Workflows, RetryStrategy.Limit) + assert row["phase"] == "Failed" and row["attempts"] == 4 and row["lastError"].startswith("after 4 attempts"), row + assert view["phase"] == "Failed" and view["report"]["steps"][1]["items"][0]["phase"] == "Failed" + + +def test_a_worker_that_dies_mid_step_leaves_the_step_to_the_next_worker_and_one_request_is_opened(world): + """A worker claims the step's job, opens the request, and dies before its transaction commits. Its lease runs out, another + worker claims the same job, and the step runs again from what was committed: one request, never two.""" + client, ctx, git, kube, validator, keys = world + created(world, "small-raise") + outdated(world, "small-raise", "6") + op_id = start(world, "tiers-rerender", {"tier": "small", "environments": ["dev"]}).json()["operationId"] + assert run_jobs(ctx, limit=1) == ["operation_step"] # select-outdated, which queues the item's step + with ctx.db.session() as s: + job = JobRepo(s).claim("worker-that-dies", lease_seconds=300) + assert job.kind == "operation_step" and job.payload["step"] == "rerender-namespace" + job_id = job.job_id + s = ctx.db._sessions() + try: + handled = s.get(JobRow, job_id) + HANDLERS["operation_step"](ctx, s, handled) + assert s.scalar(select(ChangeRequestRow.request_id).where(ChangeRequestRow.reason == "operation:tiers-rerender")) + finally: + s.rollback() # the pod dies: nothing of that transaction is committed + s.close() + view = get(world, op_id) + assert rows_of(view, "rerender-namespace")[0]["phase"] == "Running" and view["phase"] == "Running" + assert run_jobs(ctx) == [] # the dead worker's lease still holds the job + with ctx.db.session() as s: + s.execute(update(JobRow).where(JobRow.job_id == job_id).values(locked_until=text("now() - interval '1 second'"))) + drive(ctx) + view = get(world, op_id) + assert view["phase"] == "Succeeded", view + with ctx.db.session() as s: + opened = list(s.scalars(select(ChangeRequestRow).where(ChangeRequestRow.reason == "operation:tiers-rerender"))) + assert len(opened) == 1 and opened[0].status == "synced" + assert s.get(JobRow, job_id).attempts == 2 + + +def test_batch_size_and_cancel(world): + """batchSize 1: one request open at a time, the next item Pending. A cancel stops the Pending and Waiting rows at once, + ends the run Stopped, and leaves the request that a step opened to its own lifecycle.""" + client, ctx, git, kube, validator, keys = world + for name in ("raise-a", "raise-b"): + created(world, name) + outdated(world, name, "2") + op_id = start(world, "tiers-rerender", {"tier": "small", "environments": ["dev"], "batchSize": 1}).json()["operationId"] + drive(ctx) + items = {r["item"]: r for r in rows_of(get(world, op_id), "rerender-namespace")} + assert items["CRC/raise-a"]["phase"] == "Waiting" and items["CRC/raise-b"]["phase"] == "Pending" + rid = items["CRC/raise-a"]["outputs"]["requestId"] + + r = client.post(f"{URL}/{op_id}:cancel", headers=auth(keys, "opal", **OPAL)) + assert r.status_code == 200, r.text + view = r.json() + assert view["phase"] == "Stopped" and view["cancelRequestedBy"] == "opal" + assert {r["item"]: r["phase"] for r in rows_of(view, "rerender-namespace")} == {"CRC/raise-a": "Stopped", + "CRC/raise-b": "Stopped"} + assert {i["item"]: i["requestId"] for i in view["report"]["steps"][1]["items"]} == {"CRC/raise-a": rid, "CRC/raise-b": None} + assert client.get(f"/api/v1/requests/{rid}", headers=auth(keys, "amy", **AMY)).json()["status"] == "pending_approval" + drive(ctx) + assert get(world, op_id)["phase"] == "Stopped" + again = client.post(f"{URL}/{op_id}:cancel", headers=auth(keys, "opal", **OPAL)) + assert again.status_code == 409 and again.json()["code"] == "invalid-transition" + + +# --------------------------------------------------------------------------- the API + + +def test_operations_run_is_needed_to_start_read_and_cancel(world): + client, ctx, git, kube, validator, keys = world + body = {"template": "tiers-rerender", "parameters": {"tier": "small", "environments": ["dev"]}} + r = client.post(URL, json=body, headers=auth(keys, "ola", **OLA)) # cmapi-requester holds no operations:run + assert r.status_code == 403 and r.json()["code"] == "forbidden", r.text + assert client.get(URL, headers=auth(keys, "vi", **VIEWER)).status_code == 403 + op_id = start(world, "tiers-rerender", {"tier": "small", "environments": ["dev"]}).json()["operationId"] + assert client.get(f"{URL}/{op_id}", headers=auth(keys, "ola", **OLA)).status_code == 403 + assert client.post(f"{URL}/{op_id}:cancel", headers=auth(keys, "ola", **OLA)).status_code == 403 + listed = client.get(URL, headers=auth(keys, "opal", **OPAL)).json() + assert "items" in listed, listed + assert [i["operationId"] for i in listed["items"]] == [op_id] and listed["items"][0]["progress"]["total"] == 1 + assert client.get(f"{URL}/op-nope", headers=auth(keys, "opal", **OPAL)).json()["code"] == "object-not-found" + # reconcile pauses auto-approval: it also needs approvals:pause, which an operator does not hold + r = start(world, "reconcile", {}) + assert r.status_code == 403, r.text + + +def test_an_operator_limited_to_rnd_cannot_run_or_read_a_dev_operation(test_config, fresh_db, keys, monkeypatch, tmp_path): + config = tmp_path / "config" + shutil.copytree(test_config, config) + (config / "authz-roles.yaml").write_text("roles:\n cmapi-operator-rnd:\n inherits: [cmapi-operator]\n" + " environments: [rnd]\n") + with build_world(config, keys, monkeypatch) as w: + client, ctx, git, kube, validator, keys = w + rnd_op = dict(roles=["cmapi-operator-rnd"], groups=[]) + r = start(w, "tiers-rerender", {"tier": "small", "environments": ["dev"]}, who=("rio", rnd_op)) + assert r.status_code == 403 and r.json()["code"] == "environment-forbidden", r.text + op_id = start(w, "tiers-rerender", {"tier": "small", "environments": ["dev"]}).json()["operationId"] + assert client.get(f"{URL}/{op_id}", headers=auth(keys, "rio", **rnd_op)).status_code == 403 + assert client.get(URL, headers=auth(keys, "rio", **rnd_op)).json()["items"] == [] + + +def test_refusals_at_start(world): + client, ctx, git, kube, validator, keys = world + r = start(world, "tier-rerender", {}) + assert r.status_code == 422 and r.json()["code"] == "operation-template-unknown" and "tiers-rerender" in r.json()["templates"] + r = start(world, "tiers-rerender", {"tier": "small", "batchSize": 0, "colour": "red"}) + assert r.status_code == 422 and r.json()["code"] == "validation-failed" + assert {e["field"] for e in r.json()["errors"]} == {"parameters.environments", "parameters.batchSize", "parameters.colour"} + r = start(world, "tiers-rerender", {"tier": "small", "environments": ["qa"]}) + assert r.status_code == 422 and r.json()["code"] == "environment-not-served" + r = start(world, "tiers-rerender", {"tier": "huge", "environments": ["dev"]}) + assert r.status_code == 422 and r.json()["code"] == "policy-violation" + r = start(world, "rebuild-verify", {"cluster-id": "OCP_NOPE"}) + assert r.status_code == 404 and r.json()["code"] == "cluster-not-found" + r = client.post(URL, json={"template": "reconcile"}, headers={"Authorization": auth(keys, "opal", **OPAL)["Authorization"]}) + assert r.status_code == 400 and r.json()["code"] == "idempotency-key-required" + with ctx.db.session() as s: + assert s.scalar(select(OperationRow.operation_id)) is None + + +def test_the_same_idempotency_key_returns_the_run_it_started(world): + key = str(uuid.uuid4()) + first = start(world, "rebuild-verify", {"cluster-id": "CRC"}, key=key) + assert first.status_code == 202, first.text + again = start(world, "rebuild-verify", {"cluster-id": "CRC"}, key=key) + assert again.status_code == 202 and again.json()["operationId"] == first.json()["operationId"] + other = start(world, "rebuild-verify", {"cluster-id": "CRC", "parallelism": 2}, key=key) + assert other.status_code == 409 and other.json()["code"] == "idempotency-replay" + + +def test_an_engine_with_no_adapter_is_503_and_reads_still_answer(test_config, fresh_db, keys, monkeypatch, tmp_path): + """docs/02: "If the configured engine is unreachable at startup, cmapi starts anyway and stays ready. POST + /api/v1/operations returns 503 operations-engine-unavailable until the engine comes back." This build has no Argo + Workflows adapter, so that engine is never available.""" + config = tmp_path / "config" + shutil.copytree(test_config, config) + (config / "integrations.yaml").write_text((config / "integrations.yaml").read_text() + + "operations:\n engine: argo-workflows\n") + with build_world(config, keys, monkeypatch) as w: + client, ctx, git, kube, validator, keys = w + assert client.get("/readyz").status_code == 200 + r = start(w, "rebuild-verify", {"cluster-id": "CRC"}) + assert r.status_code == 503 and r.json()["code"] == "operations-engine-unavailable", r.text + assert client.get(URL, headers=auth(keys, "opal", **OPAL)).status_code == 200 + + +def test_an_engine_that_integrations_cannot_hold_stops_the_start(tmp_path): + from cmapi.core.operations import OperationsSettings + with pytest.raises(ValueError, match="operations.engine"): + OperationsSettings.from_integrations({"operations": {"engine": "airflow"}}) + with pytest.raises(ValueError, match="maxConcurrentSteps"): + OperationsSettings.from_integrations({"operations": {"builtin": {"maxConcurrentSteps": 0}}}) + + +def test_max_concurrent_steps_holds_the_steps_of_every_run(test_config, fresh_db, keys, monkeypatch, tmp_path): + """integrations.yaml operations.builtin.maxConcurrentSteps: 1. Two runs started together: the second's first step stays + Pending until the first run's step ends, so operations never fill the queue ahead of the request jobs.""" + config = tmp_path / "config" + shutil.copytree(test_config, config) + (config / "integrations.yaml").write_text((config / "integrations.yaml").read_text() + + "operations:\n builtin:\n maxConcurrentSteps: 1\n") + with build_world(config, keys, monkeypatch) as w: + client, ctx, git, kube, validator, keys = w + one = start(w, "rebuild-verify", {"cluster-id": "CRC"}).json() + two = start(w, "rebuild-verify", {"cluster-id": "CRC"}).json() + assert one["steps"][0]["phase"] == "Running" and two["steps"][0]["phase"] == "Pending" + drive(ctx) + assert get(w, one["operationId"])["phase"] == "Succeeded" and get(w, two["operationId"])["phase"] == "Succeeded" + + +# --------------------------------------------------------------------------- rebuild-verify, reconcile, cluster-onboard + + +def test_rebuild_verify_reads_every_folder_against_the_cluster_and_reports_drift(world): + client, ctx, git, kube, validator, keys = world + for name in ("kept", "drifted"): + created(world, name) + live = kube.objects[("Namespace", "", "drifted")] + live["metadata"]["labels"] = {**live["metadata"]["labels"], "cmapi.net/team": "someone-else"} + ctx.registry.cache("CRC")._list("Namespace") + applied = list(kube.applied) + op_id = start(world, "rebuild-verify", {"cluster-id": "CRC"}).json()["operationId"] + drive(ctx) + view = get(world, op_id) + assert view["phase"] == "Succeeded" + rows = {r["item"]: r for r in rows_of(view, "verify-namespace")} + assert rows["kept"]["outputs"]["outcome"] == "match" + assert rows["drifted"]["outputs"]["outcome"] == "drift" and rows["drifted"]["outputs"]["differenceCount"] == 1 + assert rows["drifted"]["outputs"]["differences"][0]["field"] == "label cmapi.net/team" + assert [i["item"] for i in view["report"]["steps"][1]["items"]] == ["drifted"] + assert kube.applied == applied # read-only + + +def test_reconcile_pauses_auto_approval_and_stops_at_the_rebuild_it_lacks(world): + client, ctx, git, kube, validator, keys = world + orphan = f"{BRANCH_PREFIX}CRC/req-20990101-0001" + git.branches[orphan] = dict(git.branches["main"]) + git._sha(orphan) + op_id = start(world, "reconcile", {}, who=("adam", ADMIN)).json()["operationId"] + drive(ctx) + view = get(world, op_id, who=("adam", ADMIN)) + phases = {r["step"]: r["phase"] for r in view["steps"]} + assert phases == {"pause-auto-approval": "Succeeded", "find-unrecorded": "Succeeded", "rebuild-requests": "Failed"} + found = rows_of(view, "find-unrecorded")[0]["outputs"]["unrecorded"] + assert [f["requestId"] for f in found] == ["req-20990101-0001"] + assert "#762" in rows_of(view, "rebuild-requests")[0]["lastError"] and view["phase"] == "Failed" + with ctx.db.session() as s: + assert SwitchRepo(s).value("auto-approval")["paused"] is True + # an operator, not an admin, cannot read a run of the whole instance only when the grant is limited; opal's is not + assert client.get(f"{URL}/{op_id}", headers=auth(keys, "opal", **OPAL)).status_code == 200 + + +def test_reconcile_with_nothing_unrecorded_succeeds(world): + client, ctx, git, kube, validator, keys = world + op_id = start(world, "reconcile", {}, who=("adam", ADMIN)).json()["operationId"] + drive(ctx) + assert get(world, op_id, who=("adam", ADMIN))["phase"] == "Succeeded" + + +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).""" + client, ctx, git, kube, validator, keys = world + op_id = start(world, "cluster-onboard", {"cluster-id": "CRC"}).json()["operationId"] + drive(ctx) + view = get(world, op_id) + phases = {r["step"]: r["phase"] for r in view["steps"]} + 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"] + + +def test_cluster_onboard_waits_for_an_import_that_is_not_there(world): + """A cluster that no import Secret names yet: an unrestricted operator may start it, and wait-import waits.""" + client, ctx, git, kube, validator, keys = world + op = start(world, "cluster-onboard", {"cluster-id": "OCP_NEW"}) + assert op.status_code == 202, op.text + drive(ctx) + row = rows_of(get(world, op.json()["operationId"]), "wait-import")[0] + assert row["phase"] == "Waiting" and row["outputs"]["status"] == "not-imported" + bad = start(world, "cluster-onboard", {"cluster-id": "not a cluster!"}) + assert bad.status_code == 422 and bad.json()["code"] == "validation-failed" + + +# --------------------------------------------------------------------------- migration 0013 + + +def test_0013_roundtrip_and_its_constraints(empty_schema): # noqa: F811 + """0013 makes the two tables with the constraints the engine relies on, and its downgrade drops them, leaving 0012.""" + import psycopg + + def run(*args): + proc = migrate(empty_schema, *args) + output = proc.communicate()[0] + assert proc.returncode == 0, output[-1500:] + + run("0013") + row = ("INSERT INTO operations (operation_id, template, parameters, engine, run_name, phase, started_by_sub, started_by, " + "finished_at, idempotency_key, idempotency_fingerprint) VALUES (%s, 't', '{}', 'builtin', %s, %s, 's', '{}', %s, %s, %s)") + with psycopg.connect(empty_schema, autocommit=True) as conn: + conn.execute(row, ("op-1", "op-1", "Running", None, "k", "f")) + for bad in (("op-2", "op-2", "Done", None, None, None), # ck_op_phase + ("op-3", "op-3", "Succeeded", None, None, None), # ck_op_finished: a final run has finished_at + ("op-4", "op-4", "Running", None, "k", None), # ck_op_idempotency + ("op-5", "op-5", "Running", None, "k", "g")): # uq_op_idempotency: one run per key and caller + with pytest.raises(psycopg.errors.IntegrityError): + conn.execute(row, bad) + step = "INSERT INTO operation_steps (operation_id, step, item, phase, finished_at) VALUES (%s, 'a', %s, %s, %s)" + conn.execute(step, ("op-1", "", "Waiting", None)) + for bad in (("op-1", "", "Pending", None), # the primary key: one row per step and item + ("op-1", "x", "Succeeded", None), # ck_opstep_finished + ("op-nope", "", "Pending", None)): # the run must exist + with pytest.raises(psycopg.errors.IntegrityError): + conn.execute(step, bad) + run("0012", "--downgrade") + assert conn.execute("SELECT to_regclass('operations'), to_regclass('operation_steps')").fetchone() == (None, None) + assert conn.execute("SELECT to_regclass('capacity_snapshots')").fetchone() != (None,) + run("head") + assert conn.execute("SELECT count(*) FROM operations").fetchone() == (0,) From 703da75d90220c7907adf19d9787c0f2f2568be9 Mon Sep 17 00:00:00 2001 From: ephico2real2 Date: Tue, 1 Dec 2026 09:49:40 -0600 Subject: [PATCH 2/4] #26: operations docs, design record, contract, samples and portal API types docs/reviews/2026-12-01-issue-26-operations/design.md records the decisions the design left open, with their sources. docs/02, 14, 16, 18, GLOSSARY and the build tracker say what is built. contract/openapi.json, samples.json, docs/04 and the portal's generated API types are regenerated. --- build-tracker.md | 5 +- .../src/api/permissions.generated.ts | 4 + cmapi-portal-ui/src/api/schema.generated.ts | 1660 +- cmapi/contract/openapi.json | 19567 +++++++++------- docs/02-technical-design-v2.md | 30 +- docs/04-api-examples.md | 718 +- docs/14-authorization.md | 20 +- docs/16-data-model.md | 100 +- docs/18-configuration.md | 6 +- docs/21-usage-from-thanos.md | 8 +- docs/GLOSSARY.md | 10 +- docs/citations.lock.json | 28 +- .../2026-12-01-issue-26-operations/design.md | 210 + 13 files changed, 13065 insertions(+), 9301 deletions(-) create mode 100644 docs/reviews/2026-12-01-issue-26-operations/design.md diff --git a/build-tracker.md b/build-tracker.md index e41055fd..adcefdd0 100644 --- a/build-tracker.md +++ b/build-tracker.md @@ -64,6 +64,7 @@ Each closes after its CRC proof and the owner's approval. | Capacity snapshots and safe placement, **migration 0012** | #21, #303 | PR #738: two reviewers ruled, main merged in, CI running | | docs/21: how cmapi reads Thanos, with every permission of the reader account and a figure | (#22) | PR #740: its citations need relocation after #738. Page: https://claude.ai/artifact/NJeNjAMqos6nGVgMFkBhpd | | Self-service adoption: supply the missing metadata at adoption, and add it later from the same screen | #739 | Being built. The owner's decision, 2026-11-26, is on #26 | +| The built-in operations engine and the Operations API: tiers-rerender, rebuild-verify, reconcile, cluster-onboard; **migration 0013** (#26 criterion 3, first slice) | #26 | Draft PR. Not built: #761, #762, #763, #765; the Argo Workflows and Tekton adapters | **Backlog, batched:** #736 (adoption follow-ups B-1 to B-10) and #737 (placement follow-ups B1 to B7). The earlier list is in the handover. @@ -462,8 +463,8 @@ needs 3, Wave 5 needs 2 to 4, and Waves 6 and 7 need 5. ### Not built, by area (`docs/08` section 4) - **Service:** config hot reload, most KPIs, metadata plugin, OpenTelemetry, route rate limits, the LDAP directory provider. -- **Endpoints:** expirations, tiers, quota writes beyond the namespace PATCH, metadata, service accounts, grants, SCC grants, tokens, policies, cluster import, capacity and placement, adoption, reports, operations, admin reload. -- **Worker jobs:** `expire_check`, `reservation_expiry`, `policy_report_sweep`, `import_clusters`, `reconcile`, `kpi_export`, `outbox_publish`, `operations`. +- **Endpoints:** expirations, tiers, quota writes beyond the namespace PATCH, metadata, service accounts, grants, SCC grants, tokens, policies, cluster import, capacity and placement, adoption, reports, admin reload. (Operations: built on the built-in engine, #26.) +- **Worker jobs:** `expire_check`, `reservation_expiry`, `policy_report_sweep`, `import_clusters`, `reconcile` (the operation is built, #26; its rebuild is #762), `kpi_export`, `outbox_publish`, `operations` (built on the built-in engine, #26). - **`cmapi-capacity`:** all of it. - **Portal:** every API call, sign-in, its Containerfile. - **CLI and SDK:** not started. diff --git a/cmapi-portal-ui/src/api/permissions.generated.ts b/cmapi-portal-ui/src/api/permissions.generated.ts index 860bf3c5..b1bb5111 100644 --- a/cmapi-portal-ui/src/api/permissions.generated.ts +++ b/cmapi-portal-ui/src/api/permissions.generated.ts @@ -18,6 +18,8 @@ export const PERMISSION = { "GET /api/v1/directory/users/{username}": "objects:read", "GET /api/v1/expirations": "objects:read", "GET /api/v1/metadata-keys": "objects:read", + "GET /api/v1/operations": "operations:run", + "GET /api/v1/operations/{operation_id}": "operations:run", "GET /api/v1/policies/rejections": "requests:read", "GET /api/v1/policies/results": "objects:read", "GET /api/v1/quotas": "objects:read", @@ -40,6 +42,8 @@ export const PERMISSION = { "POST /api/v1/clusters/{cluster_id}/namespaces/{ns}/expiration:set": "namespaces:write", "POST /api/v1/clusters/{cluster_id}/namespaces/{ns}:adopt": "namespaces:write", "POST /api/v1/clusters/{id}:probe": "operations:run", + "POST /api/v1/operations": "operations:run", + "POST /api/v1/operations/{operation_id}:cancel": "operations:run", "POST /api/v1/requests/{request_id}:approve": "requests:approve", "POST /api/v1/requests/{request_id}:cancel": "requests:cancel", "POST /api/v1/requests/{request_id}:reject": "requests:reject", diff --git a/cmapi-portal-ui/src/api/schema.generated.ts b/cmapi-portal-ui/src/api/schema.generated.ts index 34deaf86..3ac9e84b 100644 --- a/cmapi-portal-ui/src/api/schema.generated.ts +++ b/cmapi-portal-ui/src/api/schema.generated.ts @@ -766,6 +766,84 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/operations": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List operations + * @description The operations that the caller may run where they act, newest first, with each one's progress. + * + * **Requires** `operations:run`. + */ + get: operations["operations_list_operations"]; + put?: never; + /** + * Start an operation + * @description Starts a run of a template on the engine that integrations.yaml names. The answer comes before any step runs; read + * `GET /api/v1/operations/{id}` for its progress. A step that changes a namespace opens an ordinary request, which the + * approval rules decide as any other: the run waits for each one, and the person who started the run cannot approve them. + * Runs start only through this call (docs/02, rule 2). + * + * **Requires** `operations:run`. + */ + post: operations["operations_start"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/operations/{operation_id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Get an operation + * @description The status of record of one operation (docs/02): each step row with its phase, the requests it opened and why any + * did not succeed. + * + * **Requires** `operations:run`. + */ + get: operations["operations_get_operation"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/operations/{operation_id}:cancel": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Cancel an operation + * @description Stops a run that has not ended. A request that a step opened is not cancelled with it: it is an ordinary request, + * which its requester or an operator cancels on its own (`POST /api/v1/requests/{id}:cancel`); the report lists it. A + * second cancel returns the operation as it is. + * + * **Requires** `operations:run`. + */ + post: operations["operations_cancel"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/policies/rejections": { parameters: { query?: never; @@ -3674,6 +3752,350 @@ export interface components { */ status: "pending_approval" | "approved" | "pr_open" | "merged" | "awaiting_prune" | "rejected" | "synced" | "failed" | "sync_failed" | "superseded" | "cancelled" | "timeout" | "reverted" | "applied" | "merge_failed"; }; + /** Operation */ + Operation: { + /** + * Cancelrequestedat + * @description When + * @example null + */ + cancelRequestedAt: string | null; + /** + * Cancelrequestedby + * @description Who asked to cancel it + * @example null + */ + cancelRequestedBy: string | null; + /** + * Engine + * @description The engine that runs it + * @example builtin + */ + engine: string; + /** + * Environments + * @description Where it acts; null for the whole instance + * @example [ + * "dev" + * ] + */ + environments: string[] | null; + /** + * Finishedat + * @description When it ended + * @example null + */ + finishedAt: string | null; + /** @description Links */ + links: components["schemas"]["OperationLinks"]; + /** + * Operationid + * @description The operation's ID + * @example op-20261201-3f9a1c2e + */ + operationId: string; + /** + * Parameters + * @description The parameters it was started with, with their defaults + * @example { + * "batchSize": 20, + * "environments": [ + * "dev" + * ], + * "maxOpenPerCluster": 5, + * "tier": "small" + * } + */ + parameters: { + [key: string]: unknown; + }; + /** + * Phase + * @description Pending, Running, or final: Succeeded, Failed (a step failed), Error (the engine failed) or Stopped (cancelled) + * @example Running + * @enum {string} + */ + phase: "Pending" | "Running" | "Succeeded" | "Failed" | "Error" | "Stopped"; + /** @description Its step rows, counted by phase */ + progress: components["schemas"]["OperationProgress"]; + /** + * Report + * @description Once it ended: each step's rows by phase, and each item that did not succeed, or that found something, with why + * @example null + */ + report: { + [key: string]: unknown; + } | null; + /** + * Runname + * @description The run's name on its engine: the operation's ID on the built-in engine + * @example op-20261201-3f9a1c2e + */ + runName: string; + /** + * Startedat + * Format: date-time + * @description When it started + * @example 2026-12-01T10:00:00Z + */ + startedAt: string; + /** + * Startedby + * @description The username of the person who started it + * @example opal + */ + startedBy: string; + /** + * Steps + * @description Every step row, in the template's order + */ + steps: components["schemas"]["OperationStep"][]; + /** + * Template + * @description The template it runs + * @example tiers-rerender + */ + template: string; + }; + /** OperationLinks */ + OperationLinks: { + /** + * Cancel + * @description Where to cancel it + * @example /api/v1/operations/op-20261201-3f9a1c2e:cancel + */ + cancel: string; + /** + * Self + * @description This operation + * @example /api/v1/operations/op-20261201-3f9a1c2e + */ + self: string; + }; + /** OperationPage */ + OperationPage: { + /** + * Items + * @description One page of operations, newest first + */ + items: components["schemas"]["OperationSummary"][]; + /** + * Letters + * @description Rows per first letter of the template + * @example { + * "T": 2 + * } + */ + letters: { + [key: string]: number; + }; + /** @description Paging */ + page: components["schemas"]["PageInfo"]; + }; + /** OperationProgress */ + OperationProgress: { + /** + * Finished + * @description Rows in a final phase + * @example 1 + */ + finished: number; + /** + * Phases + * @description Rows in each phase + * @example { + * "Succeeded": 1, + * "Waiting": 3 + * } + */ + phases: { + [key: string]: number; + }; + /** + * Total + * @description Step rows so far: a fan-out step has one per item + * @example 4 + */ + total: number; + }; + /** OperationStart */ + OperationStart: { + /** + * Parameters + * @description The template's parameters. tiers-rerender: `tier`, `environments`, and optionally `clusterSelector` ({matchLabels}), `batchSize` (default 20) and `maxOpenPerCluster` (default 5). rebuild-verify: `cluster-id`, and optionally `parallelism` (default 10). cluster-onboard: `cluster-id`. reconcile: none + * @example { + * "environments": [ + * "dev" + * ], + * "tier": "small" + * } + */ + parameters?: { + [key: string]: unknown; + }; + /** + * Template + * @description The template to run: `tiers-rerender`, `rebuild-verify`, `reconcile` or `cluster-onboard` + * @example tiers-rerender + */ + template: string; + }; + /** OperationStep */ + OperationStep: { + /** + * Attempts + * @description Failed attempts so far; the template's retry block retries until its limit + * @example 0 + */ + attempts: number; + /** + * Clusterid + * @description The item's cluster; empty when the step is not about one cluster + * @example CRC + */ + clusterId: string; + /** + * Finishedat + * @description When it reached a final phase + * @example null + */ + finishedAt: string | null; + /** + * Item + * @description The fan-out item, such as `/`; empty for a step that is not fanned out + * @example CRC/payments-dev + */ + item: string; + /** + * Lasterror + * @description The last failure, with the problem code where there is one + * @example null + */ + lastError: string | null; + /** + * Outputs + * @description What the step recorded: a request it opened (`requestId`), its `outcome`, a `note`, and the step's own results + * @example { + * "note": "request req-20261201-0001 is pending_approval", + * "outcome": "pending_approval", + * "requestId": "req-20261201-0001" + * } + */ + outputs: { + [key: string]: unknown; + } | null; + /** + * Phase + * @description Pending (not started), Running (queued or running now), Waiting (for a request, an import or a retry's backoff), or final: Succeeded, Skipped, Failed, Error (the engine failed) or Stopped (cancelled) + * @example Waiting + * @enum {string} + */ + phase: "Pending" | "Running" | "Waiting" | "Succeeded" | "Skipped" | "Failed" | "Error" | "Stopped"; + /** + * Startedat + * @description When the step first ran + * @example 2026-12-01T10:00:00Z + */ + startedAt: string | null; + /** + * Step + * @description The step's name in its template + * @example rerender-namespace + */ + step: string; + }; + /** OperationSummary */ + OperationSummary: { + /** + * Cancelrequestedat + * @description When + * @example null + */ + cancelRequestedAt: string | null; + /** + * Cancelrequestedby + * @description Who asked to cancel it + * @example null + */ + cancelRequestedBy: string | null; + /** + * Engine + * @description The engine that runs it + * @example builtin + */ + engine: string; + /** + * Environments + * @description Where it acts; null for the whole instance + * @example [ + * "dev" + * ] + */ + environments: string[] | null; + /** + * Finishedat + * @description When it ended + * @example null + */ + finishedAt: string | null; + /** @description Links */ + links: components["schemas"]["OperationLinks"]; + /** + * Operationid + * @description The operation's ID + * @example op-20261201-3f9a1c2e + */ + operationId: string; + /** + * Parameters + * @description The parameters it was started with, with their defaults + * @example { + * "batchSize": 20, + * "environments": [ + * "dev" + * ], + * "maxOpenPerCluster": 5, + * "tier": "small" + * } + */ + parameters: { + [key: string]: unknown; + }; + /** + * Phase + * @description Pending, Running, or final: Succeeded, Failed (a step failed), Error (the engine failed) or Stopped (cancelled) + * @example Running + * @enum {string} + */ + phase: "Pending" | "Running" | "Succeeded" | "Failed" | "Error" | "Stopped"; + /** @description Its step rows, counted by phase */ + progress: components["schemas"]["OperationProgress"]; + /** + * Runname + * @description The run's name on its engine: the operation's ID on the built-in engine + * @example op-20261201-3f9a1c2e + */ + runName: string; + /** + * Startedat + * Format: date-time + * @description When it started + * @example 2026-12-01T10:00:00Z + */ + startedAt: string; + /** + * Startedby + * @description The username of the person who started it + * @example opal + */ + startedBy: string; + /** + * Template + * @description The template it runs + * @example tiers-rerender + */ + template: string; + }; /** PageInfo */ PageInfo: { /** @@ -5708,7 +6130,7 @@ export interface operations { * @example { * "paused": true, * "reason": "incident 1234", - * "setAt": "2026-11-27T20:59:01.388335+00:00", + * "setAt": "2026-12-01T15:13:07.995528+00:00", * "setBy": "ada" * } */ @@ -5840,7 +6262,7 @@ export interface operations { * @example { * "paused": false, * "reason": "incident 1234 closed", - * "setAt": "2026-11-27T20:59:01.394640+00:00", + * "setAt": "2026-12-01T15:13:07.918684+00:00", * "setBy": "ada" * } */ @@ -5962,7 +6384,7 @@ export interface operations { /** * @example { * "log": [ - * "80f4f1ba Merge cmapi/CRC/req-20261127-0001", + * "513f40b0 Merge cmapi/CRC/req-20261201-0001", * "aaaaaaaa initial" * ] * } @@ -6172,18 +6594,18 @@ export interface operations { * "cpuThrottledPeriods": null, * "cpuThrottledSeconds": null, * "cpuUsageSeconds": null, - * "measuredAt": 1795813135.55039, + * "measuredAt": 1796137976.883476, * "memoryBytes": null, * "memoryLimitBytes": null * } * ], * "database": { - * "connections": 9, + * "connections": 13, * "connectionsMax": 100, * "oldestTransactionSeconds": 0, * "poolInUse": 0, * "poolSize": 5, - * "sizeBytes": 10173463, + * "sizeBytes": 9018391, * "walBytes": 83886080 * }, * "instance": "nonprod", @@ -6195,7 +6617,7 @@ export interface operations { * "target": "under 10 min", * "targetStatus": "proposed", * "unit": "seconds", - * "value": 0.332343 + * "value": 0.27096 * }, * { * "id": "lead-time-approved-p90", @@ -6362,6 +6784,13 @@ export interface operations { * "core": true, * "disabledEnvironments": [], * "enabled": true, + * "name": "operations", + * "version": "0.2.0" + * }, + * { + * "core": true, + * "disabledEnvironments": [], + * "enabled": true, * "name": "requests", * "version": "0.2.0" * }, @@ -6516,7 +6945,7 @@ export interface operations { * "approval": { * "approvals": [ * { - * "at": "2026-11-27T20:59:06.043703Z", + * "at": "2026-12-01T15:13:18.601698Z", * "comment": "", * "relayedBy": null, * "sub": "sub-amy", @@ -6540,77 +6969,77 @@ export interface operations { * ], * "timeoutHours": 8 * }, - * "baseSha": "479aab8dca85cfbd40e9c4c4b791535b8a69d428", + * "baseSha": "4afd09a1a70bbf2c03d8d2253e817b57a5812c0a", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:59:05.959028Z", + * "createdAt": "2026-12-01T15:13:18.496644Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:59:05.969036Z", + * "at": "2026-12-01T15:13:18.510655Z", * "by": "ola", * "event": "plan_needs_approval", * "note": "waiting for [('approver-platform', 1)]", * "status": "pending_approval" * }, * { - * "at": "2026-11-27T20:59:06.061082Z", + * "at": "2026-12-01T15:13:18.626143Z", * "by": "amy", * "event": "approval", * "note": "", * "status": "pending_approval" * }, * { - * "at": "2026-11-27T20:59:06.073368Z", + * "at": "2026-12-01T15:13:18.644510Z", * "by": "amy", * "event": "approved", * "note": "approval count met", * "status": "approved" * }, * { - * "at": "2026-11-27T20:59:06.208729Z", + * "at": "2026-12-01T15:13:18.898838Z", * "by": "cmapi-bot", * "event": "branch_pushed", - * "note": "cmapi/CRC/req-20261127-0008 at a539f2ec on 479aab8d (created)", + * "note": "cmapi/CRC/req-20261201-0008 at f33469a0 on 4afd09a1 (created)", * "status": "approved" * }, * { - * "at": "2026-11-27T20:59:06.335675Z", + * "at": "2026-12-01T15:13:19.140751Z", * "by": "cmapi-bot", * "event": "pr_opened", - * "note": "cmapi/CRC/req-20261127-0008 #7", + * "note": "cmapi/CRC/req-20261201-0008 #7", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:59:06.426044Z", + * "at": "2026-12-01T15:13:19.339159Z", * "by": "ci", * "event": "ci", * "note": "kubeconform: pass; kyverno: pass; cmapi check: pass", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:59:06.516666Z", + * "at": "2026-12-01T15:13:19.519914Z", * "by": "worker", * "event": "merge_verified", - * "note": "merged a539f2ec; the folder at it is the plan's", + * "note": "merged f33469a0; the folder at it is the plan's", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:59:06.526607Z", + * "at": "2026-12-01T15:13:19.535474Z", * "by": "cmapi-bot", * "event": "merged", - * "note": "merged a539f2ec", + * "note": "merged f33469a0", * "status": "merged" * }, * { - * "at": "2026-11-27T20:59:06.642678Z", + * "at": "2026-12-01T15:13:19.737680Z", * "by": "cmapi-deliverer", * "event": "prune_pending", * "note": "Prune=confirm: waiting for an operator to confirm the prune", * "status": "awaiting_prune" * }, * { - * "at": "2026-11-27T20:59:07.179743Z", + * "at": "2026-12-01T15:13:20.879794Z", * "by": "opal", * "event": "prune_confirm", * "note": "operator confirmed the prune", @@ -6627,22 +7056,22 @@ export interface operations { * "instance": "nonprod", * "justification": null, * "links": { - * "events": "/api/v1/requests/req-20261127-0008/events", + * "events": "/api/v1/requests/req-20261201-0008/events", * "pr": "https://git.test/pulls/7", - * "self": "/api/v1/requests/req-20261127-0008" + * "self": "/api/v1/requests/req-20261201-0008" * }, - * "mergeSha": "a539f2ec", + * "mergeSha": "f33469a0", * "namespace": "search-dev", * "planHash": "c490196334dad591c3196aa59224d119861392145360aee1d428c93109235dbe", * "plugin": "namespaces", * "pr": { - * "branch": "cmapi/CRC/req-20261127-0008", - * "head": "a539f2ec", + * "branch": "cmapi/CRC/req-20261201-0008", + * "head": "f33469a0", * "number": 7, * "url": "https://git.test/pulls/7" * }, * "reason": null, - * "requestId": "req-20261127-0008", + * "requestId": "req-20261201-0008", * "requester": { * "automated": false, * "requester": { @@ -6660,7 +7089,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "awaiting_prune", - * "updatedAt": "2026-11-27T20:59:07.078985Z" + * "updatedAt": "2026-12-01T15:13:20.605642Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; @@ -6809,7 +7238,7 @@ export interface operations { * @example { * "clusters": [ * { - * "asOf": "2026-11-27T20:59:00Z", + * "asOf": "2026-12-01T15:13:00Z", * "basis": "simulated", * "boundBy": "cpu", * "clusterId": "CRC", @@ -7104,7 +7533,7 @@ export interface operations { content: { /** * @example { - * "asOf": "2026-11-27T20:59:13Z", + * "asOf": "2026-12-01T15:13:31Z", * "clusterId": null, * "excluded": [], * "expiresAt": null, @@ -7137,7 +7566,7 @@ export interface operations { * }, * "reserved": false, * "score": 39, - * "snapshotAt": "2026-11-27T20:30:00Z" + * "snapshotAt": "2026-12-01T15:00:00Z" * } * ], * "request": { @@ -7166,11 +7595,11 @@ export interface operations { content: { /** * @example { - * "asOf": "2026-11-27T20:59:13Z", + * "asOf": "2026-12-01T15:13:31Z", * "clusterId": "CRC", * "excluded": [], - * "expiresAt": "2026-11-27T21:14:13.469598Z", - * "placementId": "pl-20261127-7658a163", + * "expiresAt": "2026-12-01T15:28:31.965297Z", + * "placementId": "pl-20261201-52bb3c04", * "ranked": [ * { * "basis": "simulated", @@ -7199,7 +7628,7 @@ export interface operations { * }, * "reserved": true, * "score": 29, - * "snapshotAt": "2026-11-27T20:30:00Z" + * "snapshotAt": "2026-12-01T15:00:00Z" * } * ], * "request": { @@ -7323,7 +7752,7 @@ export interface operations { * @example { * "items": [ * { - * "checkedAt": "2026-11-27T20:58:53.069187Z", + * "checkedAt": "2026-12-01T15:12:54.018046Z", * "clusterId": "CRC", * "environment": "dev", * "findingDetails": [], @@ -7332,11 +7761,11 @@ export interface operations { * "labels": { * "region": "us-central" * }, - * "lastProbeAt": "2026-11-27T20:58:53.069187Z", + * "lastProbeAt": "2026-12-01T15:12:54.018046Z", * "secretName": "cmapi-cluster-crc", * "serverVersion": "v1.35.6-fake", * "status": "connected", - * "statusSince": "2026-11-27T20:58:53.069187Z", + * "statusSince": "2026-12-01T15:12:54.018046Z", * "tokenExpiresAt": null, * "trust": { * "downgrade": false, @@ -7777,7 +8206,7 @@ export interface operations { * "detail": null, * "source": "api", * "state": "ok", - * "takenAt": "2026-11-27T20:30:00Z" + * "takenAt": "2026-12-01T15:00:00Z" * }, * "staleAfterSeconds": 3600 * } @@ -8028,7 +8457,7 @@ export interface operations { * "annotations": { * "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", * "cmapi.net/instance": "nonprod", - * "cmapi.net/request-id": "req-20261127-0001", + * "cmapi.net/request-id": "req-20261201-0001", * "cmapi.net/requested-by": "ola@ephico2real.com", * "cmapi.net/team-dl": "payments-team@ephico2real.com" * }, @@ -8341,11 +8770,11 @@ export interface operations { * "baseSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:58:54.441022Z", + * "createdAt": "2026-12-01T15:12:55.670320Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:58:54.488801Z", + * "at": "2026-12-01T15:12:55.724895Z", * "by": "ola", * "event": "plan_auto_approved", * "note": "auto:baseline-rnd-namespace", @@ -8362,16 +8791,16 @@ export interface operations { * "instance": "nonprod", * "justification": "Payments service dev namespace", * "links": { - * "events": "/api/v1/requests/req-20261127-0001/events", - * "self": "/api/v1/requests/req-20261127-0001" + * "events": "/api/v1/requests/req-20261201-0001/events", + * "self": "/api/v1/requests/req-20261201-0001" * }, * "mergeSha": null, * "namespace": "payments-dev", - * "planHash": "9fed510537c2c36b3dc18a5b461ebfac4c2f1b7dfc2a61a394afd47b96624c09", + * "planHash": "4e9af3fc1f212f0387b6958adccca82242cc53b7fd67192be64529da18a31563", * "plugin": "namespaces", * "pr": null, * "reason": null, - * "requestId": "req-20261127-0001", + * "requestId": "req-20261201-0001", * "requester": { * "automated": false, * "requester": { @@ -8389,7 +8818,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "approved", - * "updatedAt": "2026-11-27T20:58:54.385979Z" + * "updatedAt": "2026-12-01T15:12:55.450056Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; @@ -8558,19 +8987,19 @@ export interface operations { * "annotations": { * "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", * "cmapi.net/instance": "nonprod", - * "cmapi.net/request-id": "req-20261127-0001", + * "cmapi.net/request-id": "req-20261201-0001", * "cmapi.net/requested-by": "ola@ephico2real.com", * "cmapi.net/team-dl": "payments-team@ephico2real.com" * }, * "clusterId": "CRC", * "env": "dev", - * "etag": "d71165fa38f59dd4", + * "etag": "1b59766bf9a3bbe7", * "expiresAt": null, * "git": { * "annotations": { * "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", * "cmapi.net/instance": "nonprod", - * "cmapi.net/request-id": "req-20261127-0001", + * "cmapi.net/request-id": "req-20261201-0001", * "cmapi.net/requested-by": "ola@ephico2real.com", * "cmapi.net/team-dl": "payments-team@ephico2real.com" * }, @@ -8864,7 +9293,7 @@ export interface operations { * "clusters/CRC/namespaces/search-dev/resourcequota-search-dev-quota.yaml": "removed", * "clusters/CRC/namespaces/search-dev/token-issuer-rolebinding.yaml": "removed" * }, - * "etag": "2482d135c8aae7da", + * "etag": "ca777167c63ddb5e", * "files": {}, * "findings": [], * "metadata": null, @@ -8925,14 +9354,14 @@ export interface operations { * ], * "timeoutHours": 8 * }, - * "baseSha": "479aab8dca85cfbd40e9c4c4b791535b8a69d428", + * "baseSha": "4afd09a1a70bbf2c03d8d2253e817b57a5812c0a", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:59:05.959028Z", + * "createdAt": "2026-12-01T15:13:18.496644Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:59:05.969036Z", + * "at": "2026-12-01T15:13:18.510655Z", * "by": "ola", * "event": "plan_needs_approval", * "note": "waiting for [('approver-platform', 1)]", @@ -8949,8 +9378,8 @@ export interface operations { * "instance": "nonprod", * "justification": null, * "links": { - * "events": "/api/v1/requests/req-20261127-0008/events", - * "self": "/api/v1/requests/req-20261127-0008" + * "events": "/api/v1/requests/req-20261201-0008/events", + * "self": "/api/v1/requests/req-20261201-0008" * }, * "mergeSha": null, * "namespace": "search-dev", @@ -8958,7 +9387,7 @@ export interface operations { * "plugin": "namespaces", * "pr": null, * "reason": null, - * "requestId": "req-20261127-0008", + * "requestId": "req-20261201-0008", * "requester": { * "automated": false, * "requester": { @@ -8976,7 +9405,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "pending_approval", - * "updatedAt": "2026-11-27T20:59:05.871308Z" + * "updatedAt": "2026-12-01T15:13:18.239084Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; @@ -9199,7 +9628,7 @@ export interface operations { * "clusters/CRC/namespaces/payments-dev/namespace.yaml": "changed", * "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "changed" * }, - * "etag": "d71165fa38f59dd4", + * "etag": "1b59766bf9a3bbe7", * "files": { * "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-cpu\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: medium\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 44fd85f2d7cb\nspec:\n limits:\n - type: Container\n defaultRequest:\n cpu: 100m\n default:\n cpu: 500m\n max:\n cpu: '4'\n", * "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-memory\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: medium\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 44fd85f2d7cb\nspec:\n limits:\n - type: Container\n defaultRequest:\n memory: 256Mi\n default:\n memory: 512Mi\n max:\n memory: 8Gi\n", @@ -9224,7 +9653,7 @@ export interface operations { * } * } * }, - * "planHash": "13472056b96785ab1172af6108e4ab3bda9d07c0663fd117bcb98fe6d7c3c4d8", + * "planHash": "3409c7cab6683ab5c6280d06452d63623f90b3231e915bb31b5b4efee19b9adc", * "requester": { * "automated": false, * "requester": { @@ -9309,14 +9738,14 @@ export interface operations { * ], * "timeoutHours": 8 * }, - * "baseSha": "80f4f1badad17a36a1e6c5d25834f76fef11435b", + * "baseSha": "513f40b0ee251859ba80791976ccc3addcfdf1ba", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:58:55.923726Z", + * "createdAt": "2026-12-01T15:12:57.455807Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:58:56.005112Z", + * "at": "2026-12-01T15:12:57.536560Z", * "by": "ola", * "event": "plan_needs_approval", * "note": "waiting for [('approver-platform', 1)]", @@ -9333,16 +9762,16 @@ export interface operations { * "instance": "nonprod", * "justification": "Load test next sprint", * "links": { - * "events": "/api/v1/requests/req-20261127-0002/events", - * "self": "/api/v1/requests/req-20261127-0002" + * "events": "/api/v1/requests/req-20261201-0002/events", + * "self": "/api/v1/requests/req-20261201-0002" * }, * "mergeSha": null, * "namespace": "payments-dev", - * "planHash": "df5602a2038007a6de28e19adf060fd6b5f8fb3d5b86637f790b31efdc510039", + * "planHash": "7aebcbffedf4cef6b095bd7594ab08df7c4f3964ede6f8138b15048c990b9ed3", * "plugin": "namespaces", * "pr": null, * "reason": null, - * "requestId": "req-20261127-0002", + * "requestId": "req-20261201-0002", * "requester": { * "automated": false, * "requester": { @@ -9360,7 +9789,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "pending_approval", - * "updatedAt": "2026-11-27T20:58:55.904486Z" + * "updatedAt": "2026-12-01T15:12:57.263260Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; @@ -9599,9 +10028,9 @@ export interface operations { * "changes": { * "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed" * }, - * "etag": "073bd8faea2248ce", + * "etag": "917c7a62361f9e08", * "files": { - * "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: sprint-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2026-12-31'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" + * "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: sprint-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2027-01-04'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" * }, * "findings": [], * "metadata": null, @@ -9609,7 +10038,7 @@ export interface operations { * "annotations": {}, * "labels": {} * }, - * "planHash": "45af0b7fd4a2f76619cf99f889c9d19edb65d059722e4e459866be1859ec697b", + * "planHash": "1f9cb50d801c839f9d81f17c0bdfa248ec47c1aa58de25faff503e675da9a4f6", * "requester": { * "automated": false, * "requester": { @@ -9654,14 +10083,14 @@ export interface operations { * "slots": [], * "timeoutHours": 8 * }, - * "baseSha": "3e8ad5005d0b72c1869d34e49299f12f1b03b5b5", + * "baseSha": "fff48c23f20c46278e17f5d0f1143fbe488baf9f", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:58:59.299718Z", + * "createdAt": "2026-12-01T15:13:04.324648Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:58:59.374768Z", + * "at": "2026-12-01T15:13:04.427407Z", * "by": "ola", * "event": "plan_auto_approved", * "note": "none-required", @@ -9678,16 +10107,16 @@ export interface operations { * "instance": "nonprod", * "justification": "Another sprint", * "links": { - * "events": "/api/v1/requests/req-20261127-0004/events", - * "self": "/api/v1/requests/req-20261127-0004" + * "events": "/api/v1/requests/req-20261201-0004/events", + * "self": "/api/v1/requests/req-20261201-0004" * }, * "mergeSha": null, * "namespace": "sprint-dev", - * "planHash": "fd55be2f5fa99dbc2d1abb18df09cb134f778a075ba88a80375fd4004efd3024", + * "planHash": "94647a196d1eadd68a6e7f32e52ece621b84b432d66fe07079e993d28f81f1a4", * "plugin": "namespaces", * "pr": null, * "reason": "expiration:extend", - * "requestId": "req-20261127-0004", + * "requestId": "req-20261201-0004", * "requester": { * "automated": false, * "requester": { @@ -9705,7 +10134,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "approved", - * "updatedAt": "2026-11-27T20:58:59.274371Z" + * "updatedAt": "2026-12-01T15:13:04.155474Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; @@ -9955,7 +10384,7 @@ export interface operations { * "changes": { * "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed" * }, - * "etag": "073bd8faea2248ce", + * "etag": "917c7a62361f9e08", * "files": { * "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: sprint-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" * }, @@ -9965,7 +10394,7 @@ export interface operations { * "annotations": {}, * "labels": {} * }, - * "planHash": "4e2f1ef26fab90b27dc41e0fd496b8e8006b2742bc192f09a8dea81ffefb031b", + * "planHash": "70bbacf492d9d66211a7592e0a14a89dcac6317e2376b7674bc0ee2f01e6b85f", * "requester": { * "automated": false, * "requester": { @@ -10022,14 +10451,14 @@ export interface operations { * ], * "timeoutHours": 8 * }, - * "baseSha": "ac1e81f58836d7f8a36ae1cdff67fe152c02fd02", + * "baseSha": "feb3ec3f7d9810aff0adcce6cd4aa4a92b85fefd", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:59:12.604388Z", + * "createdAt": "2026-12-01T15:13:30.640365Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:59:12.676330Z", + * "at": "2026-12-01T15:13:30.783091Z", * "by": "ola", * "event": "plan_needs_approval", * "note": "waiting for [('approver-platform', 1)]", @@ -10046,16 +10475,16 @@ export interface operations { * "instance": "nonprod", * "justification": "In production use", * "links": { - * "events": "/api/v1/requests/req-20261127-0013/events", - * "self": "/api/v1/requests/req-20261127-0013" + * "events": "/api/v1/requests/req-20261201-0013/events", + * "self": "/api/v1/requests/req-20261201-0013" * }, * "mergeSha": null, * "namespace": "sprint-dev", - * "planHash": "b2e28a66559008829930431df326dc1a91864514d67474024f7fae04298cdfd0", + * "planHash": "7e351d77c635272d0628a10556f6e2a86b180aac067848e44417651013b36b00", * "plugin": "namespaces", * "pr": null, * "reason": "expiration:makePermanent", - * "requestId": "req-20261127-0013", + * "requestId": "req-20261201-0013", * "requester": { * "automated": false, * "requester": { @@ -10073,7 +10502,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "pending_approval", - * "updatedAt": "2026-11-27T20:59:12.577772Z" + * "updatedAt": "2026-12-01T15:13:30.497696Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; @@ -10266,7 +10695,7 @@ export interface operations { /** * @example { * "justification": "A load test this sprint", - * "until": "2026-12-18" + * "until": "2026-12-22" * } */ "application/json": components["schemas"]["SetBody"]; @@ -10312,9 +10741,9 @@ export interface operations { * "changes": { * "clusters/CRC/namespaces/notes-dev/namespace.yaml": "changed" * }, - * "etag": "2763b4eb2ce407b5", + * "etag": "fc99df943d89d3a5", * "files": { - * "clusters/CRC/namespaces/notes-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: notes-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2026-12-18'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" + * "clusters/CRC/namespaces/notes-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: notes-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2026-12-22'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" * }, * "findings": [], * "metadata": null, @@ -10322,7 +10751,7 @@ export interface operations { * "annotations": {}, * "labels": {} * }, - * "planHash": "38d5d19ff384c206da94f3e9d1844ceeb7e15bedcd639467c71f7677117614a3", + * "planHash": "9c1158dfa0d79c5c9f0c241dec6a32d5b2a292a37433713da86353035f89f39e", * "requester": { * "automated": false, * "requester": { @@ -10367,14 +10796,14 @@ export interface operations { * "slots": [], * "timeoutHours": 8 * }, - * "baseSha": "2b2f51e093acbd69fb6b2fb05c5acbef76ecb749", + * "baseSha": "efebfc8bb689241a62f847984e2721f3262dc61f", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:59:11.598086Z", + * "createdAt": "2026-12-01T15:13:28.971548Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:59:11.671849Z", + * "at": "2026-12-01T15:13:29.129136Z", * "by": "ola", * "event": "plan_auto_approved", * "note": "none-required", @@ -10391,16 +10820,16 @@ export interface operations { * "instance": "nonprod", * "justification": "A load test this sprint", * "links": { - * "events": "/api/v1/requests/req-20261127-0012/events", - * "self": "/api/v1/requests/req-20261127-0012" + * "events": "/api/v1/requests/req-20261201-0012/events", + * "self": "/api/v1/requests/req-20261201-0012" * }, * "mergeSha": null, * "namespace": "notes-dev", - * "planHash": "9b232cebe5e7f6c7322d8707f3ec6242b41b2249fb7589b4e77ef7413540258c", + * "planHash": "e03939885c418d98170f15ddf95c7ff62ccfa9557329000845f1b4171c55cc30", * "plugin": "namespaces", * "pr": null, * "reason": "expiration:set", - * "requestId": "req-20261127-0012", + * "requestId": "req-20261201-0012", * "requester": { * "automated": false, * "requester": { @@ -10418,7 +10847,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "approved", - * "updatedAt": "2026-11-27T20:59:11.573014Z" + * "updatedAt": "2026-12-01T15:13:28.855961Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; @@ -10975,7 +11404,7 @@ export interface operations { * ], * "timeoutHours": 8 * }, - * "baseSha": "ca16e8cc000b1d1f2305f2259948a58c6035e62a", + * "baseSha": "e33ccf390a5fc196bb270e81c03752e59a2385f7", * "beyondTier": { * "approvals": [ * { @@ -10993,11 +11422,11 @@ export interface operations { * ] * }, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:59:16.210356Z", + * "createdAt": "2026-12-01T15:13:36.361990Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:59:16.232805Z", + * "at": "2026-12-01T15:13:36.396117Z", * "by": "ola", * "event": "plan_needs_approval", * "note": "waiting for [('approver-platform', 3)]", @@ -11013,16 +11442,16 @@ export interface operations { * "instance": "nonprod", * "justification": "Bring abc-rnd under cmapi", * "links": { - * "events": "/api/v1/requests/req-20261127-0016/events", - * "self": "/api/v1/requests/req-20261127-0016" + * "events": "/api/v1/requests/req-20261201-0016/events", + * "self": "/api/v1/requests/req-20261201-0016" * }, * "mergeSha": null, * "namespace": "abc-rnd", - * "planHash": "7630777637466bdb231a248db34b6e67aafe718082ab15403db130f4b28b73ee", + * "planHash": "49c73db929d9a990a0acdf6bd9c262076939964693858d51f17c7de254db4939", * "plugin": "adoption", * "pr": null, * "reason": null, - * "requestId": "req-20261127-0016", + * "requestId": "req-20261201-0016", * "requester": { * "automated": false, * "requester": { @@ -11040,7 +11469,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "pending_approval", - * "updatedAt": "2026-11-27T20:59:16.134586Z" + * "updatedAt": "2026-12-01T15:13:36.123405Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; @@ -11202,7 +11631,7 @@ export interface operations { content: { /** * @example { - * "checkedAt": "2026-11-27T20:58:53.587291Z", + * "checkedAt": "2026-12-01T15:12:54.578527Z", * "clusterId": "CRC", * "environment": "dev", * "findingDetails": [], @@ -11211,11 +11640,11 @@ export interface operations { * "labels": { * "region": "us-central" * }, - * "lastProbeAt": "2026-11-27T20:58:53.587291Z", + * "lastProbeAt": "2026-12-01T15:12:54.578527Z", * "secretName": "cmapi-cluster-crc", * "serverVersion": "v1.35.6-fake", * "status": "connected", - * "statusSince": "2026-11-27T20:58:53.069187Z", + * "statusSince": "2026-12-01T15:12:54.018046Z", * "tokenExpiresAt": null, * "trust": { * "downgrade": false, @@ -11592,11 +12021,11 @@ export interface operations { * ], * "app": null, * "clusterId": "CRC", - * "created": "2026-11-27", + * "created": "2026-12-01", * "daysLeft": 21, * "env": "dev", - * "expiresAt": "2026-12-18", - * "graceEnds": "2026-12-25", + * "expiresAt": "2026-12-22", + * "graceEnds": "2026-12-29", * "lifetimeDays": 21, * "name": "notes-dev", * "noticesSent": 0, @@ -11611,15 +12040,15 @@ export interface operations { * ], * "app": null, * "clusterId": "CRC", - * "created": "2026-11-27", + * "created": "2026-12-01", * "daysLeft": 27, * "env": "dev", - * "expiresAt": "2026-12-24", - * "graceEnds": "2026-12-31", + * "expiresAt": "2026-12-28", + * "graceEnds": "2027-01-04", * "lifetimeDays": 27, * "name": "sprint-dev", * "noticesSent": 0, - * "openRequest": "req-20261127-0013", + * "openRequest": "req-20261201-0013", * "state": "active", * "team": "payments" * }, @@ -11629,7 +12058,7 @@ export interface operations { * ], * "app": null, * "clusterId": "CRC", - * "created": "2026-11-27", + * "created": "2026-12-01", * "daysLeft": null, * "env": "dev", * "expiresAt": null, @@ -11637,7 +12066,7 @@ export interface operations { * "lifetimeDays": null, * "name": "payments-dev", * "noticesSent": 0, - * "openRequest": "req-20261127-0002", + * "openRequest": "req-20261201-0002", * "state": "permanent", * "team": "payments" * } @@ -11667,7 +12096,7 @@ export interface operations { * ] * } * }, - * "today": "2026-11-27" + * "today": "2026-12-01" * } */ "application/json": components["schemas"]["ExpirationPage"]; @@ -12243,6 +12672,725 @@ export interface operations { }; }; }; + operations_list_operations: { + parameters: { + query?: { + /** @description Only the runs of this template. */ + template?: string | null; + /** @description Only the runs in this phase. */ + phase?: ("Pending" | "Running" | "Succeeded" | "Failed" | "Error" | "Stopped") | null; + /** @description The number of rows in one page: 25, 50 or 100, and never more than 200. A larger result is not cut: `page.nextCursor` gives the next page. */ + limit?: number; + /** @description `page.nextCursor` or `page.prevCursor` of an earlier page of the same filters and sort. A cursor of other filters returns 400 `invalid-cursor`. */ + cursor?: string | null; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description One page of operations, newest first, each with its progress. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "items": [ + * { + * "cancelRequestedAt": null, + * "cancelRequestedBy": null, + * "engine": "builtin", + * "environments": [ + * "dev" + * ], + * "finishedAt": null, + * "links": { + * "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + * "self": "/api/v1/operations/op-20261201-7fead487" + * }, + * "operationId": "op-20261201-7fead487", + * "parameters": { + * "batchSize": 20, + * "environments": [ + * "dev" + * ], + * "maxOpenPerCluster": 5, + * "tier": "small" + * }, + * "phase": "Running", + * "progress": { + * "finished": 0, + * "phases": { + * "Running": 1 + * }, + * "total": 1 + * }, + * "runName": "op-20261201-7fead487", + * "startedAt": "2026-12-01T15:13:36.696696Z", + * "startedBy": "opal", + * "template": "tiers-rerender" + * } + * ], + * "letters": { + * "T": 1 + * }, + * "page": { + * "from": 1, + * "limit": 50, + * "nextCursor": null, + * "prevCursor": null, + * "to": 1, + * "total": 1 + * } + * } + */ + "application/json": components["schemas"]["OperationPage"]; + }; + }; + /** + * @description A header or a parameter that cmapi reads first is missing or not valid. + * + * Codes: `invalid-cursor`, `invalid-limit`. + */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description No token, or the token is not valid. + * + * Codes: `unauthenticated`. + */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description The caller may not do this, or not in this environment. + * + * Codes: `forbidden`. + */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`. + * + * Codes: `validation-failed`. + */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done. + * + * Codes: `rate-limited`. + */ + 429: { + headers: { + /** @description The seconds to wait before the next call: the same number as `retryAfter`. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when. + * + * Codes: `idp-unavailable`. + */ + 503: { + headers: { + /** @description The seconds to wait before the next call: the same number as `retryAfter`. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + }; + }; + operations_start: { + parameters: { + query?: never; + header?: { + /** @description A new random value for each new operation, such as a UUID, of at most 100 characters. Required. The same caller sending the same body with the same key gets the operation it started, in its current state, for as long as the operation is kept; the same key with another body is 409 `idempotency-replay`. */ + "Idempotency-Key"?: string | null; + }; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + /** + * @example { + * "parameters": { + * "environments": [ + * "dev" + * ], + * "tier": "small" + * }, + * "template": "tiers-rerender" + * } + */ + "application/json": components["schemas"]["OperationStart"]; + }; + }; + responses: { + /** @description The operation, started: its first steps are queued for the worker. `links.self` is its status. */ + 202: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "cancelRequestedAt": null, + * "cancelRequestedBy": null, + * "engine": "builtin", + * "environments": [ + * "dev" + * ], + * "finishedAt": null, + * "links": { + * "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + * "self": "/api/v1/operations/op-20261201-7fead487" + * }, + * "operationId": "op-20261201-7fead487", + * "parameters": { + * "batchSize": 20, + * "environments": [ + * "dev" + * ], + * "maxOpenPerCluster": 5, + * "tier": "small" + * }, + * "phase": "Running", + * "progress": { + * "finished": 0, + * "phases": { + * "Running": 1 + * }, + * "total": 1 + * }, + * "report": null, + * "runName": "op-20261201-7fead487", + * "startedAt": "2026-12-01T15:13:36.696696Z", + * "startedBy": "opal", + * "steps": [ + * { + * "attempts": 0, + * "clusterId": "", + * "finishedAt": null, + * "item": "", + * "lastError": null, + * "outputs": null, + * "phase": "Running", + * "startedAt": "2026-12-01T15:13:36.480026Z", + * "step": "select-outdated" + * } + * ], + * "template": "tiers-rerender" + * } + */ + "application/json": components["schemas"]["Operation"]; + }; + }; + /** + * @description A header or a parameter that cmapi reads first is missing or not valid. + * + * Codes: `idempotency-key-required`, `dry-run-not-supported`. + */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description No token, or the token is not valid. + * + * Codes: `unauthenticated`. + */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description The caller may not do this, or not in this environment. + * + * Codes: `forbidden`, `environment-forbidden`. + */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description What the path names is not known. + * + * Codes: `cluster-not-found`. + */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description It conflicts with the current state of the object, of an open request or of the Idempotency-Key. + * + * Codes: `idempotency-replay`. + */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done. + * + * Codes: `content-too-large`. + */ + 413: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`. + * + * Codes: `operation-template-unknown`, `validation-failed`, `environment-not-served`, `policy-violation`. + */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done. + * + * Codes: `rate-limited`. + */ + 429: { + headers: { + /** @description The seconds to wait before the next call: the same number as `retryAfter`. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when. + * + * Codes: `operations-engine-unavailable`, `idp-unavailable`. + */ + 503: { + headers: { + /** @description The seconds to wait before the next call: the same number as `retryAfter`. Sent with `idp-unavailable`. */ + "Retry-After"?: number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + }; + }; + operations_get_operation: { + parameters: { + query?: never; + header?: never; + path: { + /** @description The operation's ID, as the start returned it. */ + operation_id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The operation with every step row: its phase, attempts, outputs and last error; and its report once it ended. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "cancelRequestedAt": "2026-12-01T15:13:36.705960Z", + * "cancelRequestedBy": "opal", + * "engine": "builtin", + * "environments": [ + * "dev" + * ], + * "finishedAt": "2026-12-01T15:13:36.995319Z", + * "links": { + * "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + * "self": "/api/v1/operations/op-20261201-7fead487" + * }, + * "operationId": "op-20261201-7fead487", + * "parameters": { + * "batchSize": 20, + * "environments": [ + * "dev" + * ], + * "maxOpenPerCluster": 5, + * "tier": "small" + * }, + * "phase": "Stopped", + * "progress": { + * "finished": 1, + * "phases": { + * "Stopped": 1 + * }, + * "total": 1 + * }, + * "report": { + * "steps": [ + * { + * "items": [], + * "phases": { + * "Stopped": 1 + * }, + * "step": "select-outdated" + * } + * ] + * }, + * "runName": "op-20261201-7fead487", + * "startedAt": "2026-12-01T15:13:36.696696Z", + * "startedBy": "opal", + * "steps": [ + * { + * "attempts": 0, + * "clusterId": "", + * "finishedAt": "2026-12-01T15:13:36.968745Z", + * "item": "", + * "lastError": null, + * "outputs": { + * "note": "stopped by opal" + * }, + * "phase": "Stopped", + * "startedAt": "2026-12-01T15:13:36.480026Z", + * "step": "select-outdated" + * } + * ], + * "template": "tiers-rerender" + * } + */ + "application/json": components["schemas"]["Operation"]; + }; + }; + /** + * @description No token, or the token is not valid. + * + * Codes: `unauthenticated`. + */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description The caller may not do this, or not in this environment. + * + * Codes: `forbidden`, `environment-forbidden`. + */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description What the path names is not known. + * + * Codes: `object-not-found`. + */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`. + * + * Codes: `validation-failed`. + */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done. + * + * Codes: `rate-limited`. + */ + 429: { + headers: { + /** @description The seconds to wait before the next call: the same number as `retryAfter`. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when. + * + * Codes: `idp-unavailable`. + */ + 503: { + headers: { + /** @description The seconds to wait before the next call: the same number as `retryAfter`. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + }; + }; + operations_cancel: { + parameters: { + query?: never; + header?: never; + path: { + /** @description The operation's ID, as the start returned it. */ + operation_id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The operation: no new step starts, the steps not started and the steps waiting are Stopped, and it ends Stopped once the step that runs now ends. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "cancelRequestedAt": "2026-12-01T15:13:36.705960Z", + * "cancelRequestedBy": "opal", + * "engine": "builtin", + * "environments": [ + * "dev" + * ], + * "finishedAt": null, + * "links": { + * "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + * "self": "/api/v1/operations/op-20261201-7fead487" + * }, + * "operationId": "op-20261201-7fead487", + * "parameters": { + * "batchSize": 20, + * "environments": [ + * "dev" + * ], + * "maxOpenPerCluster": 5, + * "tier": "small" + * }, + * "phase": "Running", + * "progress": { + * "finished": 0, + * "phases": { + * "Running": 1 + * }, + * "total": 1 + * }, + * "report": null, + * "runName": "op-20261201-7fead487", + * "startedAt": "2026-12-01T15:13:36.696696Z", + * "startedBy": "opal", + * "steps": [ + * { + * "attempts": 0, + * "clusterId": "", + * "finishedAt": null, + * "item": "", + * "lastError": null, + * "outputs": null, + * "phase": "Running", + * "startedAt": "2026-12-01T15:13:36.480026Z", + * "step": "select-outdated" + * } + * ], + * "template": "tiers-rerender" + * } + */ + "application/json": components["schemas"]["Operation"]; + }; + }; + /** + * @description A header or a parameter that cmapi reads first is missing or not valid. + * + * Codes: `dry-run-not-supported`. + */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description No token, or the token is not valid. + * + * Codes: `unauthenticated`. + */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description The caller may not do this, or not in this environment. + * + * Codes: `forbidden`, `environment-forbidden`. + */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description What the path names is not known. + * + * Codes: `object-not-found`. + */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description It conflicts with the current state of the object, of an open request or of the Idempotency-Key. + * + * Codes: `invalid-transition`. + */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`. + * + * Codes: `validation-failed`. + */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done. + * + * Codes: `rate-limited`. + */ + 429: { + headers: { + /** @description The seconds to wait before the next call: the same number as `retryAfter`. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + /** + * @description A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when. + * + * Codes: `idp-unavailable`. + */ + 503: { + headers: { + /** @description The seconds to wait before the next call: the same number as `retryAfter`. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetail"]; + }; + }; + }; + }; policies_rejections: { parameters: { query?: { @@ -12281,7 +13429,7 @@ export interface operations { content: { /** * @example { - * "from": "2026-11-20T20:59:12.816211Z", + * "from": "2026-11-24T15:13:31.152927Z", * "items": [ * { * "action": "create", @@ -12300,9 +13448,9 @@ export interface operations { * "source": "cmapi" * } * ], - * "firstAt": "2026-11-27T20:59:09.886777Z", + * "firstAt": "2026-12-01T15:13:26.735685Z", * "id": "rej-2", - * "lastAt": "2026-11-27T20:59:09.886777Z", + * "lastAt": "2026-12-01T15:13:26.735685Z", * "namespace": "kube-tools", * "outcome": "refused", * "plugin": "namespaces", @@ -12320,7 +13468,7 @@ export interface operations { * "findings": [ * { * "kyvernoRule": null, - * "message": "the head moved from 479aab8d to 9df23668 after the pull request was opened", + * "message": "the head moved from 4afd09a1 to 00ee2444 after the pull request was opened", * "path": null, * "policy": "cmapi-check", * "rule": null, @@ -12328,14 +13476,14 @@ export interface operations { * "source": "cmapi" * } * ], - * "firstAt": "2026-11-27T20:59:03.193672Z", + * "firstAt": "2026-12-01T15:13:12.465909Z", * "id": "rej-1", - * "lastAt": "2026-11-27T20:59:03.193672Z", + * "lastAt": "2026-12-01T15:13:12.465909Z", * "namespace": "search-dev", * "outcome": "refused", * "plugin": "namespaces", * "problem": null, - * "requestId": "req-20261127-0007", + * "requestId": "req-20261201-0007", * "stage": "ci", * "username": "ola" * } @@ -12479,7 +13627,7 @@ export interface operations { * @example { * "clusters": [ * { - * "asOf": "2026-11-27T20:59:12.694710Z", + * "asOf": "2026-12-01T15:13:30.959859Z", * "bundle": { * "actionsDiffer": [], * "actionsDifferTotal": 0, @@ -13770,14 +14918,14 @@ export interface operations { * ], * "timeoutHours": 8 * }, - * "baseSha": "80f4f1badad17a36a1e6c5d25834f76fef11435b", + * "baseSha": "513f40b0ee251859ba80791976ccc3addcfdf1ba", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:58:55.923726Z", + * "createdAt": "2026-12-01T15:12:57.455807Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:58:56.005112Z", + * "at": "2026-12-01T15:12:57.536560Z", * "by": "ola", * "event": "plan_needs_approval", * "note": "waiting for [('approver-platform', 1)]", @@ -13794,16 +14942,16 @@ export interface operations { * "instance": "nonprod", * "justification": "Load test next sprint", * "links": { - * "events": "/api/v1/requests/req-20261127-0002/events", - * "self": "/api/v1/requests/req-20261127-0002" + * "events": "/api/v1/requests/req-20261201-0002/events", + * "self": "/api/v1/requests/req-20261201-0002" * }, * "mergeSha": null, * "namespace": "payments-dev", - * "planHash": "df5602a2038007a6de28e19adf060fd6b5f8fb3d5b86637f790b31efdc510039", + * "planHash": "7aebcbffedf4cef6b095bd7594ab08df7c4f3964ede6f8138b15048c990b9ed3", * "plugin": "namespaces", * "pr": null, * "reason": null, - * "requestId": "req-20261127-0002", + * "requestId": "req-20261201-0002", * "requester": { * "automated": false, * "requester": { @@ -13821,7 +14969,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "pending_approval", - * "updatedAt": "2026-11-27T20:58:55.904486Z" + * "updatedAt": "2026-12-01T15:12:57.263260Z" * } * ], * "letters": { @@ -13962,67 +15110,67 @@ export interface operations { * "baseSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:58:54.441022Z", + * "createdAt": "2026-12-01T15:12:55.670320Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:58:54.488801Z", + * "at": "2026-12-01T15:12:55.724895Z", * "by": "ola", * "event": "plan_auto_approved", * "note": "auto:baseline-rnd-namespace", * "status": "approved" * }, * { - * "at": "2026-11-27T20:58:54.586895Z", + * "at": "2026-12-01T15:12:55.840600Z", * "by": "cmapi-bot", * "event": "branch_pushed", - * "note": "cmapi/CRC/req-20261127-0001 at 80f4f1ba on aaaaaaaa (created)", + * "note": "cmapi/CRC/req-20261201-0001 at 513f40b0 on aaaaaaaa (created)", * "status": "approved" * }, * { - * "at": "2026-11-27T20:58:54.636706Z", + * "at": "2026-12-01T15:12:55.901812Z", * "by": "cmapi-bot", * "event": "pr_opened", - * "note": "cmapi/CRC/req-20261127-0001 #1", + * "note": "cmapi/CRC/req-20261201-0001 #1", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:58:54.677782Z", + * "at": "2026-12-01T15:12:55.945117Z", * "by": "ci", * "event": "ci", * "note": "kubeconform: pass; kyverno: pass; cmapi check: pass", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:58:54.757184Z", + * "at": "2026-12-01T15:12:56.052717Z", * "by": "cmapi-deliverer", * "event": "apply_started", - * "note": "applying 80f4f1ba before the merge", + * "note": "applying 513f40b0 before the merge", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:58:54.799387Z", + * "at": "2026-12-01T15:12:56.124941Z", * "by": "cmapi-deliverer", * "event": "applied", - * "note": "5 objects from cmapi/CRC/req-20261127-0001 at 80f4f1ba, before the merge, confirmed by a read: 1 Namespace, 1 ResourceQuota and 2 LimitRanges match the plan", + * "note": "5 objects from cmapi/CRC/req-20261201-0001 at 513f40b0, before the merge, confirmed by a read: 1 Namespace, 1 ResourceQuota and 2 LimitRanges match the plan, as do 1 RoleBinding", * "status": "applied" * }, * { - * "at": "2026-11-27T20:58:54.850841Z", + * "at": "2026-12-01T15:12:56.188647Z", * "by": "worker", * "event": "merge_verified", - * "note": "merged 80f4f1ba; the folder at it is the plan's", + * "note": "merged 513f40b0; the folder at it is the plan's", * "status": "applied" * }, * { - * "at": "2026-11-27T20:58:54.864833Z", + * "at": "2026-12-01T15:12:56.204485Z", * "by": "cmapi-bot", * "event": "merged", - * "note": "merged 80f4f1ba", + * "note": "merged 513f40b0", * "status": "merged" * }, * { - * "at": "2026-11-27T20:58:54.881820Z", + * "at": "2026-12-01T15:12:56.223876Z", * "by": "cmapi-deliverer", * "event": "synced", * "note": "applied and confirmed by a read before the merge", @@ -14039,22 +15187,22 @@ export interface operations { * "instance": "nonprod", * "justification": "Payments service dev namespace", * "links": { - * "events": "/api/v1/requests/req-20261127-0001/events", + * "events": "/api/v1/requests/req-20261201-0001/events", * "pr": "https://git.test/pulls/1", - * "self": "/api/v1/requests/req-20261127-0001" + * "self": "/api/v1/requests/req-20261201-0001" * }, - * "mergeSha": "80f4f1ba", + * "mergeSha": "513f40b0", * "namespace": "payments-dev", - * "planHash": "9fed510537c2c36b3dc18a5b461ebfac4c2f1b7dfc2a61a394afd47b96624c09", + * "planHash": "4e9af3fc1f212f0387b6958adccca82242cc53b7fd67192be64529da18a31563", * "plugin": "namespaces", * "pr": { - * "branch": "cmapi/CRC/req-20261127-0001", - * "head": "80f4f1ba", + * "branch": "cmapi/CRC/req-20261201-0001", + * "head": "513f40b0", * "number": 1, * "url": "https://git.test/pulls/1" * }, * "reason": null, - * "requestId": "req-20261127-0001", + * "requestId": "req-20261201-0001", * "requester": { * "automated": false, * "requester": { @@ -14072,7 +15220,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "synced", - * "updatedAt": "2026-11-27T20:58:54.780441Z" + * "updatedAt": "2026-12-01T15:12:55.949790Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; @@ -14183,8 +15331,8 @@ export interface operations { /** * @example { * "approved": true, - * "planHash": "9fed510537c2c36b3dc18a5b461ebfac4c2f1b7dfc2a61a394afd47b96624c09", - * "requestId": "req-20261127-0001", + * "planHash": "4e9af3fc1f212f0387b6958adccca82242cc53b7fd67192be64529da18a31563", + * "requestId": "req-20261201-0001", * "status": "synced" * } */ @@ -14297,70 +15445,70 @@ export interface operations { * @example { * "events": [ * { - * "at": "2026-11-27T20:58:54.488801Z", + * "at": "2026-12-01T15:12:55.724895Z", * "by": "ola", * "event": "plan_auto_approved", * "note": "auto:baseline-rnd-namespace", * "status": "approved" * }, * { - * "at": "2026-11-27T20:58:54.586895Z", + * "at": "2026-12-01T15:12:55.840600Z", * "by": "cmapi-bot", * "event": "branch_pushed", - * "note": "cmapi/CRC/req-20261127-0001 at 80f4f1ba on aaaaaaaa (created)", + * "note": "cmapi/CRC/req-20261201-0001 at 513f40b0 on aaaaaaaa (created)", * "status": "approved" * }, * { - * "at": "2026-11-27T20:58:54.636706Z", + * "at": "2026-12-01T15:12:55.901812Z", * "by": "cmapi-bot", * "event": "pr_opened", - * "note": "cmapi/CRC/req-20261127-0001 #1", + * "note": "cmapi/CRC/req-20261201-0001 #1", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:58:54.677782Z", + * "at": "2026-12-01T15:12:55.945117Z", * "by": "ci", * "event": "ci", * "note": "kubeconform: pass; kyverno: pass; cmapi check: pass", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:58:54.757184Z", + * "at": "2026-12-01T15:12:56.052717Z", * "by": "cmapi-deliverer", * "event": "apply_started", - * "note": "applying 80f4f1ba before the merge", + * "note": "applying 513f40b0 before the merge", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:58:54.799387Z", + * "at": "2026-12-01T15:12:56.124941Z", * "by": "cmapi-deliverer", * "event": "applied", - * "note": "5 objects from cmapi/CRC/req-20261127-0001 at 80f4f1ba, before the merge, confirmed by a read: 1 Namespace, 1 ResourceQuota and 2 LimitRanges match the plan", + * "note": "5 objects from cmapi/CRC/req-20261201-0001 at 513f40b0, before the merge, confirmed by a read: 1 Namespace, 1 ResourceQuota and 2 LimitRanges match the plan, as do 1 RoleBinding", * "status": "applied" * }, * { - * "at": "2026-11-27T20:58:54.850841Z", + * "at": "2026-12-01T15:12:56.188647Z", * "by": "worker", * "event": "merge_verified", - * "note": "merged 80f4f1ba; the folder at it is the plan's", + * "note": "merged 513f40b0; the folder at it is the plan's", * "status": "applied" * }, * { - * "at": "2026-11-27T20:58:54.864833Z", + * "at": "2026-12-01T15:12:56.204485Z", * "by": "cmapi-bot", * "event": "merged", - * "note": "merged 80f4f1ba", + * "note": "merged 513f40b0", * "status": "merged" * }, * { - * "at": "2026-11-27T20:58:54.881820Z", + * "at": "2026-12-01T15:12:56.223876Z", * "by": "cmapi-deliverer", * "event": "synced", * "note": "applied and confirmed by a read before the merge", * "status": "synced" * } * ], - * "requestId": "req-20261127-0001", + * "requestId": "req-20261201-0001", * "status": "synced" * } */ @@ -14484,7 +15632,7 @@ export interface operations { * "approval": { * "approvals": [ * { - * "at": "2026-11-27T20:58:56.181147Z", + * "at": "2026-12-01T15:12:57.737114Z", * "comment": "sizing reviewed", * "relayedBy": null, * "sub": "sub-amy", @@ -14509,28 +15657,28 @@ export interface operations { * ], * "timeoutHours": 8 * }, - * "baseSha": "80f4f1badad17a36a1e6c5d25834f76fef11435b", + * "baseSha": "513f40b0ee251859ba80791976ccc3addcfdf1ba", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:58:55.923726Z", + * "createdAt": "2026-12-01T15:12:57.455807Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:58:56.005112Z", + * "at": "2026-12-01T15:12:57.536560Z", * "by": "ola", * "event": "plan_needs_approval", * "note": "waiting for [('approver-platform', 1)]", * "status": "pending_approval" * }, * { - * "at": "2026-11-27T20:58:56.208815Z", + * "at": "2026-12-01T15:12:57.766421Z", * "by": "amy", * "event": "approval", * "note": "sizing reviewed", * "status": "pending_approval" * }, * { - * "at": "2026-11-27T20:58:56.231666Z", + * "at": "2026-12-01T15:12:57.795342Z", * "by": "amy", * "event": "approved", * "note": "approval count met", @@ -14547,16 +15695,16 @@ export interface operations { * "instance": "nonprod", * "justification": "Load test next sprint", * "links": { - * "events": "/api/v1/requests/req-20261127-0002/events", - * "self": "/api/v1/requests/req-20261127-0002" + * "events": "/api/v1/requests/req-20261201-0002/events", + * "self": "/api/v1/requests/req-20261201-0002" * }, * "mergeSha": null, * "namespace": "payments-dev", - * "planHash": "df5602a2038007a6de28e19adf060fd6b5f8fb3d5b86637f790b31efdc510039", + * "planHash": "7aebcbffedf4cef6b095bd7594ab08df7c4f3964ede6f8138b15048c990b9ed3", * "plugin": "namespaces", * "pr": null, * "reason": null, - * "requestId": "req-20261127-0002", + * "requestId": "req-20261201-0002", * "requester": { * "automated": false, * "requester": { @@ -14574,7 +15722,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "approved", - * "updatedAt": "2026-11-27T20:58:56.128756Z" + * "updatedAt": "2026-12-01T15:12:57.519349Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; @@ -14748,21 +15896,21 @@ export interface operations { * ], * "timeoutHours": 8 * }, - * "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + * "baseSha": "f33469a0b99e67100557d4172703299def66403b", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:59:00.839033Z", + * "createdAt": "2026-12-01T15:13:07.269501Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:59:00.869605Z", + * "at": "2026-12-01T15:13:07.303276Z", * "by": "ola", * "event": "plan_needs_approval", * "note": "waiting for [('approver-platform', 1)]", * "status": "pending_approval" * }, * { - * "at": "2026-11-27T20:59:01.284709Z", + * "at": "2026-12-01T15:13:07.829553Z", * "by": "ola", * "event": "cancel", * "note": "", @@ -14779,16 +15927,16 @@ export interface operations { * "instance": "nonprod", * "justification": "Payments service dev namespace", * "links": { - * "events": "/api/v1/requests/req-20261127-0005/events", - * "self": "/api/v1/requests/req-20261127-0005" + * "events": "/api/v1/requests/req-20261201-0005/events", + * "self": "/api/v1/requests/req-20261201-0005" * }, * "mergeSha": null, * "namespace": "ledger-dev", - * "planHash": "872bc285608555d97234f8f6f440473a920a3da01e2e5509a176628b51d35ac3", + * "planHash": "ce7e669a03e55261cb76f1ec4054133e9985c1ab51a26c1edf7bfb18ea4bf918", * "plugin": "namespaces", * "pr": null, * "reason": null, - * "requestId": "req-20261127-0005", + * "requestId": "req-20261201-0005", * "requester": { * "automated": false, * "requester": { @@ -14806,7 +15954,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "cancelled", - * "updatedAt": "2026-11-27T20:59:01.183312Z" + * "updatedAt": "2026-12-01T15:13:07.554237Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; @@ -14976,21 +16124,21 @@ export interface operations { * ], * "timeoutHours": 8 * }, - * "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + * "baseSha": "f33469a0b99e67100557d4172703299def66403b", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:59:01.025136Z", + * "createdAt": "2026-12-01T15:13:07.467592Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:59:01.059924Z", + * "at": "2026-12-01T15:13:07.523173Z", * "by": "ola", * "event": "plan_needs_approval", * "note": "waiting for [('approver-platform', 1)]", * "status": "pending_approval" * }, * { - * "at": "2026-11-27T20:59:01.177791Z", + * "at": "2026-12-01T15:13:07.689889Z", * "by": "amy", * "event": "rejected", * "note": "Use the medium tier", @@ -15007,16 +16155,16 @@ export interface operations { * "instance": "nonprod", * "justification": "Payments service dev namespace", * "links": { - * "events": "/api/v1/requests/req-20261127-0006/events", - * "self": "/api/v1/requests/req-20261127-0006" + * "events": "/api/v1/requests/req-20261201-0006/events", + * "self": "/api/v1/requests/req-20261201-0006" * }, * "mergeSha": null, * "namespace": "billing-dev", - * "planHash": "83fbdd10e46eb59ab7a8469389ca3be081d6248b68e498bd28f9b5553b7d319b", + * "planHash": "2dc6e0f17a140f4c9b54f8ba3f3438767816ea38ea0e7288d30ad08d61977635", * "plugin": "namespaces", * "pr": null, * "reason": null, - * "requestId": "req-20261127-0006", + * "requestId": "req-20261201-0006", * "requester": { * "automated": false, * "requester": { @@ -15034,7 +16182,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "rejected", - * "updatedAt": "2026-11-27T20:59:01.074654Z" + * "updatedAt": "2026-12-01T15:13:07.412997Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; @@ -15198,70 +16346,70 @@ export interface operations { * "slots": [], * "timeoutHours": 8 * }, - * "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + * "baseSha": "f33469a0b99e67100557d4172703299def66403b", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:59:02.774593Z", + * "createdAt": "2026-12-01T15:13:11.695133Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:59:02.805919Z", + * "at": "2026-12-01T15:13:11.739486Z", * "by": "ola", * "event": "plan_auto_approved", * "note": "auto:baseline-rnd-namespace", * "status": "approved" * }, * { - * "at": "2026-11-27T20:59:02.926517Z", + * "at": "2026-12-01T15:13:12.002993Z", * "by": "cmapi-bot", * "event": "branch_pushed", - * "note": "cmapi/CRC/req-20261127-0007 at 479aab8d on a539f2ec (created)", + * "note": "cmapi/CRC/req-20261201-0007 at 4afd09a1 on f33469a0 (created)", * "status": "approved" * }, * { - * "at": "2026-11-27T20:59:03.034663Z", + * "at": "2026-12-01T15:13:12.223049Z", * "by": "cmapi-bot", * "event": "pr_opened", - * "note": "cmapi/CRC/req-20261127-0007 #5", + * "note": "cmapi/CRC/req-20261201-0007 #5", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:59:03.202028Z", + * "at": "2026-12-01T15:13:12.476559Z", * "by": "ci", * "event": "ci", * "note": "kubeconform: pass; kyverno: pass; cmapi check: fail", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:59:03.221341Z", + * "at": "2026-12-01T15:13:12.503772Z", * "by": "ci", * "event": "head_moved", - * "note": "PR head moved from 479aab8d to 9df23668 after approval", + * "note": "PR head moved from 4afd09a1 to 00ee2444 after approval", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:59:03.235587Z", + * "at": "2026-12-01T15:13:12.524707Z", * "by": "ci", * "event": "pr_failed", * "note": "checks failed", * "status": "failed" * }, * { - * "at": "2026-11-27T20:59:03.235646Z", + * "at": "2026-12-01T15:13:12.524778Z", * "by": "worker", * "event": "pr_closed", * "note": "#5: its checks failed; the request is failed and may be retried", * "status": "failed" * }, * { - * "at": "2026-11-27T20:59:03.337967Z", + * "at": "2026-12-01T15:13:12.722929Z", * "by": "worker", * "event": "branch_deleted", - * "note": "cmapi/CRC/req-20261127-0007 at 9df23668", + * "note": "cmapi/CRC/req-20261201-0007 at 00ee2444", * "status": "failed" * }, * { - * "at": "2026-11-27T20:59:04.480562Z", + * "at": "2026-12-01T15:13:15.355831Z", * "by": "opal", * "event": "retry", * "note": "retry requested", @@ -15278,22 +16426,22 @@ export interface operations { * "instance": "nonprod", * "justification": "Payments service dev namespace", * "links": { - * "events": "/api/v1/requests/req-20261127-0007/events", + * "events": "/api/v1/requests/req-20261201-0007/events", * "pr": "https://git.test/pulls/5", - * "self": "/api/v1/requests/req-20261127-0007" + * "self": "/api/v1/requests/req-20261201-0007" * }, * "mergeSha": null, * "namespace": "search-dev", - * "planHash": "2cbf58b2fd56a364d34143e4ad6349cd2aeda2faa6214d9720de95dce8966f81", + * "planHash": "9e54f6892405d065608268e425a03e3a4ffcbf02c1d0465424fc7f3a06a65833", * "plugin": "namespaces", * "pr": { - * "branch": "cmapi/CRC/req-20261127-0007", - * "head": "479aab8d", + * "branch": "cmapi/CRC/req-20261201-0007", + * "head": "4afd09a1", * "number": 5, * "url": "https://git.test/pulls/5" * }, * "reason": null, - * "requestId": "req-20261127-0007", + * "requestId": "req-20261201-0007", * "requester": { * "automated": false, * "requester": { @@ -15311,7 +16459,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "approved", - * "updatedAt": "2026-11-27T20:59:04.382387Z" + * "updatedAt": "2026-12-01T15:13:15.083613Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; @@ -15462,63 +16610,63 @@ export interface operations { * "slots": [], * "timeoutHours": 8 * }, - * "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + * "baseSha": "f33469a0b99e67100557d4172703299def66403b", * "beyondTier": null, * "clusterId": "CRC", - * "createdAt": "2026-11-27T20:59:08.498578Z", + * "createdAt": "2026-12-01T15:13:24.659107Z", * "env": "dev", * "events": [ * { - * "at": "2026-11-27T20:59:08.528720Z", + * "at": "2026-12-01T15:13:24.709971Z", * "by": "ola", * "event": "plan_auto_approved", * "note": "auto:baseline-rnd-namespace", * "status": "approved" * }, * { - * "at": "2026-11-27T20:59:08.615802Z", + * "at": "2026-12-01T15:13:24.888974Z", * "by": "cmapi-bot", * "event": "branch_pushed", - * "note": "cmapi/CRC/req-20261127-0009 at f4851764 on a539f2ec (created)", + * "note": "cmapi/CRC/req-20261201-0009 at 8dde0960 on f33469a0 (created)", * "status": "approved" * }, * { - * "at": "2026-11-27T20:59:08.662018Z", + * "at": "2026-12-01T15:13:24.957534Z", * "by": "cmapi-bot", * "event": "pr_opened", - * "note": "cmapi/CRC/req-20261127-0009 #8", + * "note": "cmapi/CRC/req-20261201-0009 #8", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:59:08.703276Z", + * "at": "2026-12-01T15:13:25.016675Z", * "by": "ci", * "event": "ci", * "note": "kubeconform: pass; kyverno: pass; cmapi check: pass", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:59:08.743034Z", + * "at": "2026-12-01T15:13:25.072457Z", * "by": "worker", * "event": "merge_verified", - * "note": "merged f4851764; the folder at it is the plan's", + * "note": "merged 8dde0960; the folder at it is the plan's", * "status": "pr_open" * }, * { - * "at": "2026-11-27T20:59:08.753863Z", + * "at": "2026-12-01T15:13:25.089654Z", * "by": "cmapi-bot", * "event": "merged", - * "note": "merged f4851764", + * "note": "merged 8dde0960", * "status": "merged" * }, * { - * "at": "2026-11-27T20:59:08.804072Z", + * "at": "2026-12-01T15:13:25.173437Z", * "by": "worker", * "event": "sync_timeout", * "note": "orders-dev exists on the cluster and cmapi does not manage it; nothing applied", * "status": "sync_failed" * }, * { - * "at": "2026-11-27T20:59:08.972422Z", + * "at": "2026-12-01T15:13:25.438291Z", * "by": "opal", * "event": "revert_requested", * "note": "", @@ -15535,22 +16683,22 @@ export interface operations { * "instance": "nonprod", * "justification": "Payments service dev namespace", * "links": { - * "events": "/api/v1/requests/req-20261127-0009/events", + * "events": "/api/v1/requests/req-20261201-0009/events", * "pr": "https://git.test/pulls/8", - * "self": "/api/v1/requests/req-20261127-0009" + * "self": "/api/v1/requests/req-20261201-0009" * }, - * "mergeSha": "f4851764", + * "mergeSha": "8dde0960", * "namespace": "orders-dev", - * "planHash": "2b55cc5cb3a1687f1a10e7038a5ce91dfb672e864e45f9479f2a4ca2b85ddcdc", + * "planHash": "4b5e5a0bd420f5925cbcfcc96fecca8e8fc2c4ccd0a7f579ffa057a49b37af02", * "plugin": "namespaces", * "pr": { - * "branch": "cmapi/CRC/req-20261127-0009", - * "head": "f4851764", + * "branch": "cmapi/CRC/req-20261201-0009", + * "head": "8dde0960", * "number": 8, * "url": "https://git.test/pulls/8" * }, * "reason": null, - * "requestId": "req-20261127-0009", + * "requestId": "req-20261201-0009", * "requester": { * "automated": false, * "requester": { @@ -15568,7 +16716,7 @@ export interface operations { * "submittedByClient": null * }, * "status": "sync_failed", - * "updatedAt": "2026-11-27T20:59:08.871988Z" + * "updatedAt": "2026-12-01T15:13:25.162107Z" * } */ "application/json": components["schemas"]["ChangeRequest"]; diff --git a/cmapi/contract/openapi.json b/cmapi/contract/openapi.json index 228d2d57..f812c1ef 100644 --- a/cmapi/contract/openapi.json +++ b/cmapi/contract/openapi.json @@ -5534,41 +5534,26 @@ "title": "OpenRequestRef", "type": "object" }, - "PageInfo": { + "Operation": { "additionalProperties": false, "properties": { - "from": { - "description": "1-based index of the first row", - "examples": [ - 1 - ], - "title": "From", - "type": "integer" - }, - "limit": { - "description": "Page size", - "examples": [ - 50 - ], - "title": "Limit", - "type": "integer" - }, - "nextCursor": { + "cancelRequestedAt": { "anyOf": [ { + "format": "date-time", "type": "string" }, { "type": "null" } ], - "description": "Cursor for the next page", + "description": "When", "examples": [ - "eyJ..." + null ], - "title": "Nextcursor" + "title": "Cancelrequestedat" }, - "prevCursor": { + "cancelRequestedBy": { "anyOf": [ { "type": "string" @@ -5577,433 +5562,418 @@ "type": "null" } ], - "description": "Cursor for the previous page", + "description": "Who asked to cancel it", "examples": [ null ], - "title": "Prevcursor" + "title": "Cancelrequestedby" }, - "to": { - "description": "Index of the last row", + "engine": { + "description": "The engine that runs it", "examples": [ - 50 + "builtin" ], - "title": "To", - "type": "integer" + "title": "Engine", + "type": "string" }, - "total": { - "description": "Rows matching the filters", + "environments": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "description": "Where it acts; null for the whole instance", "examples": [ - 120 + [ + "dev" + ] ], - "title": "Total", - "type": "integer" - } - }, - "required": [ - "limit", - "total", - "from", - "to", - "nextCursor", - "prevCursor" - ], - "title": "PageInfo", - "type": "object" - }, - "PermanentBody": { - "additionalProperties": false, - "properties": { - "justification": { + "title": "Environments" + }, + "finishedAt": { "anyOf": [ { + "format": "date-time", "type": "string" }, { "type": "null" } ], - "description": "Why", + "description": "When it ended", "examples": [ - "The service went to production use" + null ], - "title": "Justification" - } - }, - "title": "PermanentBody", - "type": "object" - }, - "PlacementAsk": { - "additionalProperties": false, - "properties": { - "constraints": { - "$ref": "#/components/schemas/PlacementConstraints", - "description": "As asked" + "title": "Finishedat" }, - "cpu": { - "description": "The tier's `requests.cpu`, in millicores: what is reserved", - "examples": [ - 8000 - ], - "title": "Cpu", - "type": "integer" + "links": { + "$ref": "#/components/schemas/OperationLinks", + "description": "Links" }, - "environment": { - "description": "As asked", + "operationId": { + "description": "The operation's ID", "examples": [ - "dev" + "op-20261201-3f9a1c2e" ], - "title": "Environment", + "title": "Operationid", "type": "string" }, - "memory": { - "description": "The tier's `requests.memory`, in bytes", + "parameters": { + "additionalProperties": true, + "description": "The parameters it was started with, with their defaults", "examples": [ - 17179869184 + { + "batchSize": 20, + "environments": [ + "dev" + ], + "maxOpenPerCluster": 5, + "tier": "small" + } ], - "title": "Memory", - "type": "integer" + "title": "Parameters", + "type": "object" }, - "pods": { - "description": "The tier's `pods`, 0 when it sets none", + "phase": { + "description": "Pending, Running, or final: Succeeded, Failed (a step failed), Error (the engine failed) or Stopped (cancelled)", + "enum": [ + "Pending", + "Running", + "Succeeded", + "Failed", + "Error", + "Stopped" + ], "examples": [ - 50 + "Running" ], - "title": "Pods", - "type": "integer" + "title": "Phase", + "type": "string" }, - "team": { + "progress": { + "$ref": "#/components/schemas/OperationProgress", + "description": "Its step rows, counted by phase" + }, + "report": { "anyOf": [ { - "type": "string" + "additionalProperties": true, + "type": "object" }, { "type": "null" } ], - "description": "As asked", + "description": "Once it ended: each step's rows by phase, and each item that did not succeed, or that found something, with why", "examples": [ - "payments" + null ], - "title": "Team" + "title": "Report" }, - "tier": { - "description": "As asked", + "runName": { + "description": "The run's name on its engine: the operation's ID on the built-in engine", "examples": [ - "small" + "op-20261201-3f9a1c2e" ], - "title": "Tier", + "title": "Runname", "type": "string" - } - }, - "required": [ - "environment", - "team", - "tier", - "cpu", - "memory", - "pods", - "constraints" - ], - "title": "PlacementAsk", - "type": "object" - }, - "PlacementConstraints": { - "additionalProperties": false, - "properties": { - "clusterSelector": { - "anyOf": [ - { - "$ref": "#/components/schemas/ClusterSelector" - }, - { - "type": "null" - } - ], - "description": "Only clusters whose labels match", - "examples": [ - null - ] }, - "region": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Only clusters whose clusters.yaml label `region` is this", + "startedAt": { + "description": "When it started", "examples": [ - "us-central" + "2026-12-01T10:00:00Z" ], - "title": "Region" + "format": "date-time", + "title": "Startedat", + "type": "string" }, - "zones": { - "description": "Only clusters with a counted node in each of these zones", + "startedBy": { + "description": "The username of the person who started it", "examples": [ - [] + "opal" ], + "title": "Startedby", + "type": "string" + }, + "steps": { + "description": "Every step row, in the template's order", "items": { - "type": "string" + "$ref": "#/components/schemas/OperationStep" }, - "title": "Zones", + "title": "Steps", "type": "array" + }, + "template": { + "description": "The template it runs", + "examples": [ + "tiers-rerender" + ], + "title": "Template", + "type": "string" } }, - "title": "PlacementConstraints", + "required": [ + "operationId", + "template", + "engine", + "runName", + "phase", + "parameters", + "environments", + "startedBy", + "startedAt", + "finishedAt", + "cancelRequestedBy", + "cancelRequestedAt", + "progress", + "links", + "steps", + "report" + ], + "title": "Operation", "type": "object" }, - "PlacementExcluded": { + "OperationLinks": { "additionalProperties": false, "properties": { - "clusterId": { - "description": "A cluster of the environment left out", - "examples": [ - "OCP_GF7" - ], - "title": "Clusterid", - "type": "string" - }, - "detail": { - "description": "Why, in words", + "cancel": { + "description": "Where to cancel it", "examples": [ - "newest complete snapshot 95 min old, limit 60 min" + "/api/v1/operations/op-20261201-3f9a1c2e:cancel" ], - "title": "Detail", + "title": "Cancel", "type": "string" }, - "reason": { - "description": "The first hard filter it fails", - "enum": [ - "not-connected", - "not-writable", - "placement-disabled", - "outside-region", - "outside-zones", - "outside-selector", - "stale-data", - "partial-data", - "no-size", - "max-namespaces", - "no-cpu-headroom", - "no-memory-headroom", - "zone-failure-headroom" - ], + "self": { + "description": "This operation", "examples": [ - "stale-data" + "/api/v1/operations/op-20261201-3f9a1c2e" ], - "title": "Reason", + "title": "Self", "type": "string" } }, "required": [ - "clusterId", - "reason", - "detail" + "self", + "cancel" ], - "title": "PlacementExcluded", + "title": "OperationLinks", "type": "object" }, - "PlacementFactors": { + "OperationPage": { "additionalProperties": false, "properties": { - "balance": { - "description": "0 to 1: 0.5 at the environment's average commitment, more below it", - "examples": [ - 0.5 - ], - "title": "Balance", - "type": "number" + "items": { + "description": "One page of operations, newest first", + "items": { + "$ref": "#/components/schemas/OperationSummary" + }, + "title": "Items", + "type": "array" }, - "quotaHeadroom": { - "description": "0 to 1: the smaller resource's headroom after placement, over its limit", + "letters": { + "additionalProperties": { + "type": "integer" + }, + "description": "Rows per first letter of the template", "examples": [ - 0.875 + { + "T": 2 + } ], - "title": "Quotaheadroom", - "type": "number" + "title": "Letters", + "type": "object" }, - "teamAffinity": { - "description": "1 when the team already has a namespace on the cluster, else 0", + "page": { + "$ref": "#/components/schemas/PageInfo", + "description": "Paging" + } + }, + "required": [ + "items", + "page", + "letters" + ], + "title": "OperationPage", + "type": "object" + }, + "OperationProgress": { + "additionalProperties": false, + "properties": { + "finished": { + "description": "Rows in a final phase", "examples": [ - 0.0 + 1 ], - "title": "Teamaffinity", - "type": "number" + "title": "Finished", + "type": "integer" }, - "usageHeadroom": { - "description": "0 to 1: 1 \u2212 the 14-day p95 of use; 0 when not measured", + "phases": { + "additionalProperties": { + "type": "integer" + }, + "description": "Rows in each phase", "examples": [ - 0.0 + { + "Succeeded": 1, + "Waiting": 3 + } ], - "title": "Usageheadroom", - "type": "number" + "title": "Phases", + "type": "object" }, - "zoneSpread": { - "description": "0 to 1: the smallest zone's allocatable over the largest's; 0 with under two zones", + "total": { + "description": "Step rows so far: a fan-out step has one per item", "examples": [ - 0.0 + 4 ], - "title": "Zonespread", - "type": "number" + "title": "Total", + "type": "integer" } }, "required": [ - "quotaHeadroom", - "usageHeadroom", - "balance", - "teamAffinity", - "zoneSpread" + "total", + "finished", + "phases" ], - "title": "PlacementFactors", + "title": "OperationProgress", "type": "object" }, - "PlacementFigures": { + "OperationStart": { "additionalProperties": false, "properties": { - "quotaHeadroomAfter": { - "description": "The same after this namespace", + "parameters": { + "additionalProperties": true, + "description": "The template's parameters. tiers-rerender: `tier`, `environments`, and optionally `clusterSelector` ({matchLabels}), `batchSize` (default 20) and `maxOpenPerCluster` (default 5). rebuild-verify: `cluster-id`, and optionally `parallelism` (default 10). cluster-onboard: `cluster-id`. reconcile: none", "examples": [ - 112000 + { + "environments": [ + "dev" + ], + "tier": "small" + } ], - "title": "Quotaheadroomafter", - "type": "integer" + "title": "Parameters", + "type": "object" }, - "quotaHeadroomBefore": { - "description": "Size \u00d7 overcommit \u2212 committed \u2212 active reservations, now", + "template": { + "description": "The template to run: `tiers-rerender`, `rebuild-verify`, `reconcile` or `cluster-onboard`", "examples": [ - 120000 + "tiers-rerender" ], - "title": "Quotaheadroombefore", + "title": "Template", + "type": "string" + } + }, + "required": [ + "template" + ], + "title": "OperationStart", + "type": "object" + }, + "OperationStep": { + "additionalProperties": false, + "properties": { + "attempts": { + "description": "Failed attempts so far; the template's retry block retries until its limit", + "examples": [ + 0 + ], + "title": "Attempts", "type": "integer" }, - "unit": { - "description": "The unit of the amounts", - "enum": [ - "millicores", - "bytes" - ], + "clusterId": { + "description": "The item's cluster; empty when the step is not about one cluster", "examples": [ - "millicores" + "CRC" ], - "title": "Unit", + "title": "Clusterid", "type": "string" }, - "usageP95": { + "finishedAt": { "anyOf": [ { - "type": "number" + "format": "date-time", + "type": "string" }, { "type": "null" } ], - "description": "The 14-day p95 of use over allocatable, from the snapshots. Null when no snapshot measured use", + "description": "When it reached a final phase", "examples": [ null ], - "title": "Usagep95" + "title": "Finishedat" }, - "zoneFailureHeadroomAfter": { + "item": { + "description": "The fan-out item, such as `/`; empty for a step that is not fanned out", + "examples": [ + "CRC/payments-dev" + ], + "title": "Item", + "type": "string" + }, + "lastError": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "description": "The headroom after this namespace with the largest zone lost; only in placement.yaml `zoneFailureEnvironments` (prod)", + "description": "The last failure, with the problem code where there is one", "examples": [ null ], - "title": "Zonefailureheadroomafter" - } - }, - "required": [ - "unit", - "quotaHeadroomBefore", - "quotaHeadroomAfter", - "zoneFailureHeadroomAfter", - "usageP95" - ], - "title": "PlacementFigures", - "type": "object" - }, - "PlacementRanked": { - "additionalProperties": false, - "properties": { - "basis": { + "title": "Lasterror" + }, + "outputs": { "anyOf": [ { - "enum": [ - "simulated", - "allocatable" - ], - "type": "string" + "additionalProperties": true, + "type": "object" }, { "type": "null" } ], - "description": "The size headroom is measured against, as the Capacity tab's", + "description": "What the step recorded: a request it opened (`requestId`), its `outcome`, a `note`, and the step's own results", "examples": [ - "simulated" + { + "note": "request req-20261201-0001 is pending_approval", + "outcome": "pending_approval", + "requestId": "req-20261201-0001" + } ], - "title": "Basis" + "title": "Outputs" }, - "boundBy": { - "description": "The resource whose commitment is higher after placement", + "phase": { + "description": "Pending (not started), Running (queued or running now), Waiting (for a request, an import or a retry's backoff), or final: Succeeded, Skipped, Failed, Error (the engine failed) or Stopped (cancelled)", "enum": [ - "cpu", - "memory", - "both" - ], - "examples": [ - "cpu" + "Pending", + "Running", + "Waiting", + "Succeeded", + "Skipped", + "Failed", + "Error", + "Stopped" ], - "title": "Boundby", - "type": "string" - }, - "clusterId": { - "description": "A cluster that passes every hard filter", "examples": [ - "CRC" + "Waiting" ], - "title": "Clusterid", + "title": "Phase", "type": "string" }, - "cpu": { - "$ref": "#/components/schemas/PlacementFigures", - "description": "CPU, in millicores" - }, - "factors": { - "$ref": "#/components/schemas/PlacementFactors", - "description": "Each factor of the score, before its weight" - }, - "memory": { - "$ref": "#/components/schemas/PlacementFigures", - "description": "Memory, in bytes" - }, - "reserved": { - "description": "True on the cluster the placement holds: the first that still fit under its lock", - "examples": [ - true - ], - "title": "Reserved", - "type": "boolean" - }, - "score": { - "description": "0 to 100: the weighted factors \u00d7 the cluster's `placement.weight`, capped at 100", - "examples": [ - 50 - ], - "title": "Score", - "type": "integer" - }, - "snapshotAt": { + "startedAt": { "anyOf": [ { "format": "date-time", @@ -6013,128 +5983,98 @@ "type": "null" } ], - "description": "The end of the newest complete snapshot's interval", + "description": "When the step first ran", "examples": [ - "2026-11-26T17:00:00Z" + "2026-12-01T10:00:00Z" ], - "title": "Snapshotat" + "title": "Startedat" + }, + "step": { + "description": "The step's name in its template", + "examples": [ + "rerender-namespace" + ], + "title": "Step", + "type": "string" } }, "required": [ + "step", + "item", "clusterId", - "score", - "reserved", - "basis", - "snapshotAt", - "boundBy", - "factors", - "cpu", - "memory" - ], - "title": "PlacementRanked", + "phase", + "attempts", + "outputs", + "lastError", + "startedAt", + "finishedAt" + ], + "title": "OperationStep", "type": "object" }, - "PlacementRequest": { + "OperationSummary": { "additionalProperties": false, "properties": { - "constraints": { - "$ref": "#/components/schemas/PlacementConstraints", - "description": "Where the namespace may go" - }, - "environment": { - "description": "The environment of the new namespace: one this instance serves", - "examples": [ - "dev" - ], - "title": "Environment", - "type": "string" - }, - "quota": { + "cancelRequestedAt": { "anyOf": [ { - "additionalProperties": { - "type": "string" - }, - "type": "object" + "format": "date-time", + "type": "string" }, { "type": "null" } ], - "description": "Custom tier only: the sizable quota keys, as the create sends them", + "description": "When", "examples": [ null ], - "title": "Quota" + "title": "Cancelrequestedat" }, - "team": { + "cancelRequestedBy": { "anyOf": [ { - "pattern": "^[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$", "type": "string" }, { "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": "Who asked to cancel it", "examples": [ - "payments" + null ], - "title": "Team" + "title": "Cancelrequestedby" }, - "tier": { - "default": "small", - "description": "A tier of GET /tiers, or custom", - "examples": [ - "small" - ], - "title": "Tier", - "type": "string" - } - }, - "required": [ - "environment" - ], - "title": "PlacementRequest", - "type": "object" - }, - "PlacementResult": { - "additionalProperties": false, - "properties": { - "asOf": { - "description": "When the clusters were ranked", + "engine": { + "description": "The engine that runs it", "examples": [ - "2026-11-26T17:00:12Z" + "builtin" ], - "format": "date-time", - "title": "Asof", + "title": "Engine", "type": "string" }, - "clusterId": { + "environments": { "anyOf": [ { - "type": "string" + "items": { + "type": "string" + }, + "type": "array" }, { "type": "null" } ], - "description": "The reserved cluster: the create's path cluster. Null on a dry run", + "description": "Where it acts; null for the whole instance", "examples": [ - "CRC" + [ + "dev" + ] ], - "title": "Clusterid" - }, - "excluded": { - "description": "Every other cluster of the environment in the caller's scope, with its reason", - "items": { - "$ref": "#/components/schemas/PlacementExcluded" - }, - "title": "Excluded", - "type": "array" + "title": "Environments" }, - "expiresAt": { + "finishedAt": { "anyOf": [ { "format": "date-time", @@ -6144,272 +6084,148 @@ "type": "null" } ], - "description": "When the reservation lapses unless a create claims it. Null on a dry run", - "examples": [ - "2026-11-26T17:15:00Z" - ], - "title": "Expiresat" - }, - "placementId": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "The reservation to send as the create's `placementId`. Null on a dry run", + "description": "When it ended", "examples": [ - "pl-20261126-3f9a1c2e" + null ], - "title": "Placementid" - }, - "ranked": { - "description": "The clusters that pass, best first; ties go to the lower cluster ID", - "items": { - "$ref": "#/components/schemas/PlacementRanked" - }, - "title": "Ranked", - "type": "array" + "title": "Finishedat" }, - "request": { - "$ref": "#/components/schemas/PlacementAsk", - "description": "What was asked, sized from the tier" - } - }, - "required": [ - "placementId", - "expiresAt", - "clusterId", - "asOf", - "request", - "ranked", - "excluded" - ], - "title": "PlacementResult", - "type": "object" - }, - "PlanAdoption": { - "additionalProperties": false, - "properties": { - "keys": { - "description": "Each label and annotation under a skip prefix, and whether it is kept", - "items": { - "$ref": "#/components/schemas/AdoptionKey" - }, - "title": "Keys", - "type": "array" + "links": { + "$ref": "#/components/schemas/OperationLinks", + "description": "Links" }, - "label": { - "description": "The opt-in label. It stays on the namespace after the adoption and is then ignored; removing it before the merge cancels the request", + "operationId": { + "description": "The operation's ID", "examples": [ - "cmapi.net/adopt" + "op-20261201-3f9a1c2e" ], - "title": "Label", + "title": "Operationid", "type": "string" }, - "missingKeys": { - "description": "Each declared key that the adopted namespace will still lack, which a later change request can add, required ones first", - "examples": [ - [] - ], - "items": { - "$ref": "#/components/schemas/MissingKey" - }, - "title": "Missingkeys", - "type": "array" - }, - "notAdopted": { - "additionalProperties": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ] - }, - "description": "How many objects of the other kinds the namespace has, which stay unmanaged; null when they could not be counted", + "parameters": { + "additionalProperties": true, + "description": "The parameters it was started with, with their defaults", "examples": [ { - "RoleBinding": 1, - "ServiceAccount": 2 + "batchSize": 20, + "environments": [ + "dev" + ], + "maxOpenPerCluster": 5, + "tier": "small" } ], - "title": "Notadopted", + "title": "Parameters", "type": "object" }, - "objects": { - "description": "Each object that the plan read and adopts: the Namespace, each ResourceQuota and each LimitRange. cmapi reads them again when the request is approved, when the bot opens the pull request and in its check; a difference fails the request", - "items": { - "$ref": "#/components/schemas/AdoptedObject" - }, - "title": "Objects", - "type": "array" - }, - "recognised": { - "description": "Each adoptionLabels key and value of metadata-keys.yaml that the namespace carries: made by another tool", + "phase": { + "description": "Pending, Running, or final: Succeeded, Failed (a step failed), Error (the engine failed) or Stopped (cancelled)", + "enum": [ + "Pending", + "Running", + "Succeeded", + "Failed", + "Error", + "Stopped" + ], "examples": [ - [ - "company.net/provisioner=cluster-configs" - ] + "Running" ], - "items": { - "type": "string" - }, - "title": "Recognised", - "type": "array" + "title": "Phase", + "type": "string" }, - "snapshotHash": { - "description": "SHA-256 of the objects as read: the base of the policy checks at plan time and in the pull request's check, which never take it from the pull request", + "progress": { + "$ref": "#/components/schemas/OperationProgress", + "description": "Its step rows, counted by phase" + }, + "runName": { + "description": "The run's name on its engine: the operation's ID on the built-in engine", "examples": [ - "5d1f0c9e2b7a4c3d8e6f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d" + "op-20261201-3f9a1c2e" ], - "title": "Snapshothash", + "title": "Runname", "type": "string" }, - "supplied": { - "$ref": "#/components/schemas/SuppliedMetadata", - "description": "The labels and annotations that the request adds to the namespace (#739), which it lacked: empty maps when it adds none" - } - }, - "required": [ - "objects", - "label", - "recognised", - "keys", - "notAdopted", - "snapshotHash", - "supplied", - "missingKeys" - ], - "title": "PlanAdoption", - "type": "object" - }, - "PlanMetadata": { - "additionalProperties": false, - "properties": { - "annotations": { - "additionalProperties": { - "$ref": "#/components/schemas/MetadataValue" - }, - "description": "Each annotation that the request sets or that cmapi fills in, with its source", + "startedAt": { + "description": "When it started", "examples": [ - { - "cmapi.net/team-dl": { - "source": "request", - "value": "payments-team@ephico2real.com" - } - } + "2026-12-01T10:00:00Z" ], - "title": "Annotations", - "type": "object" + "format": "date-time", + "title": "Startedat", + "type": "string" }, - "labels": { - "additionalProperties": { - "$ref": "#/components/schemas/MetadataValue" - }, - "description": "Each label that the request sets or that cmapi fills in, with its source. cmapi's own system labels are not listed", + "startedBy": { + "description": "The username of the person who started it", "examples": [ - { - "cmapi.net/cost-center": { - "source": "request", - "value": "cc-4410" - }, - "cmapi.net/team": { - "source": "request", - "value": "payments" - } - } + "opal" ], - "title": "Labels", - "type": "object" + "title": "Startedby", + "type": "string" }, - "namespace": { - "description": "The namespace name", + "template": { + "description": "The template it runs", "examples": [ - "payments-dev" + "tiers-rerender" ], - "title": "Namespace", + "title": "Template", "type": "string" } }, "required": [ - "namespace", - "labels", - "annotations" + "operationId", + "template", + "engine", + "runName", + "phase", + "parameters", + "environments", + "startedBy", + "startedAt", + "finishedAt", + "cancelRequestedBy", + "cancelRequestedAt", + "progress", + "links" ], - "title": "PlanMetadata", + "title": "OperationSummary", "type": "object" }, - "PlanMetadataDiff": { + "PageInfo": { "additionalProperties": false, "properties": { - "annotations": { - "additionalProperties": { - "$ref": "#/components/schemas/MetadataChange" - }, - "description": "Each annotation whose value the change moves, by key, in the same form", + "from": { + "description": "1-based index of the first row", "examples": [ - { - "runbook.ephico2real.com/url": { - "after": "https://wiki.ephico2real.com/payments/runbook", - "source": "request" - } - } + 1 ], - "title": "Annotations", - "type": "object" + "title": "From", + "type": "integer" }, - "labels": { - "additionalProperties": { - "$ref": "#/components/schemas/MetadataChange" - }, - "description": "Each label whose value the change moves, by key: only effective changes, and only the keys that a request may name or that cmapi fills in (cmapi's own system labels are not listed)", + "limit": { + "description": "Page size", "examples": [ - { - "cmapi.net/cost-center": { - "before": "cc-4410", - "source": "request" - } - } + 50 ], - "title": "Labels", - "type": "object" - } - }, - "required": [ - "labels", - "annotations" - ], - "title": "PlanMetadataDiff", - "type": "object" - }, - "PlanUsage": { - "additionalProperties": false, - "properties": { - "coverage": { + "title": "Limit", + "type": "integer" + }, + "nextCursor": { "anyOf": [ { - "type": "number" + "type": "string" }, { "type": "null" } ], - "description": "The share of the window's 4,032 five-minute steps with a running-pod sample", + "description": "Cursor for the next page", "examples": [ - 0.98 + "eyJ..." ], - "title": "Coverage" - }, - "cpu": { - "$ref": "#/components/schemas/UsageFigures", - "description": "CPU, in millicores" + "title": "Nextcursor" }, - "evaluatedAt": { + "prevCursor": { "anyOf": [ { "type": "string" @@ -6418,17 +6234,44 @@ "type": "null" } ], - "description": "The one instant every query used, RFC 3339; null when nothing was read", + "description": "Cursor for the previous page", "examples": [ - "2026-11-25T10:00:00+00:00" + null ], - "title": "Evaluatedat" + "title": "Prevcursor" }, - "memory": { - "$ref": "#/components/schemas/UsageFigures", - "description": "Memory, in bytes" + "to": { + "description": "Index of the last row", + "examples": [ + 50 + ], + "title": "To", + "type": "integer" }, - "reason": { + "total": { + "description": "Rows matching the filters", + "examples": [ + 120 + ], + "title": "Total", + "type": "integer" + } + }, + "required": [ + "limit", + "total", + "from", + "to", + "nextCursor", + "prevCursor" + ], + "title": "PageInfo", + "type": "object" + }, + "PermanentBody": { + "additionalProperties": false, + "properties": { + "justification": { "anyOf": [ { "type": "string" @@ -6437,109 +6280,109 @@ "type": "null" } ], - "description": "Why the state is not ok, in a sentence; null when it is", + "description": "Why", "examples": [ - null + "The service went to production use" ], - "title": "Reason" + "title": "Justification" + } + }, + "title": "PermanentBody", + "type": "object" + }, + "PlacementAsk": { + "additionalProperties": false, + "properties": { + "constraints": { + "$ref": "#/components/schemas/PlacementConstraints", + "description": "As asked" }, - "state": { - "description": "`ok`, the figures can be judged by. `insufficient-data`: no usage source is configured, or Thanos has too few samples (under 80% of the 14-day window's 5-minute steps), and the figures are null. `unavailable`: Thanos did not answer in 10 seconds; the change needs a platform approval (docs/01)", - "enum": [ - "ok", - "insufficient-data", - "unavailable" + "cpu": { + "description": "The tier's `requests.cpu`, in millicores: what is reserved", + "examples": [ + 8000 ], + "title": "Cpu", + "type": "integer" + }, + "environment": { + "description": "As asked", "examples": [ - "ok" + "dev" ], - "title": "State", + "title": "Environment", "type": "string" }, - "units": { - "additionalProperties": { - "type": "string" - }, - "description": "The unit of each resource's figures", + "memory": { + "description": "The tier's `requests.memory`, in bytes", + "examples": [ + 17179869184 + ], + "title": "Memory", + "type": "integer" + }, + "pods": { + "description": "The tier's `pods`, 0 when it sets none", "examples": [ + 50 + ], + "title": "Pods", + "type": "integer" + }, + "team": { + "anyOf": [ { - "cpu": "millicores", - "memory": "bytes" + "type": "string" + }, + { + "type": "null" } ], - "title": "Units", - "type": "object" + "description": "As asked", + "examples": [ + "payments" + ], + "title": "Team" }, - "window": { - "const": "14d", - "description": "The window of p95 and peak", + "tier": { + "description": "As asked", "examples": [ - "14d" + "small" ], - "title": "Window", + "title": "Tier", "type": "string" } }, "required": [ - "state", - "reason", - "window", - "coverage", - "evaluatedAt", - "units", + "environment", + "team", + "tier", "cpu", - "memory" + "memory", + "pods", + "constraints" ], - "title": "PlanUsage", + "title": "PlacementAsk", "type": "object" }, - "PlanView": { + "PlacementConstraints": { "additionalProperties": false, "properties": { - "adoption": { - "anyOf": [ - { - "$ref": "#/components/schemas/PlanAdoption" - }, - { - "type": "null" - } - ], - "description": "On an adoption: the objects it read, the keys under a skip prefix, and what stays unmanaged (story #26). Null on other writes" - }, - "approval": { - "$ref": "#/components/schemas/ApprovalView", - "description": "The approval that would apply" - }, - "beyondTier": { + "clusterSelector": { "anyOf": [ { - "$ref": "#/components/schemas/BeyondTier" + "$ref": "#/components/schemas/ClusterSelector" }, { "type": "null" } ], - "description": "The values beyond the tier and the approvals they add; null when the request has none" - }, - "capacity": { - "$ref": "#/components/schemas/CapacityView", - "description": "The capacity check" - }, - "changes": { - "additionalProperties": { - "type": "string" - }, - "description": "Per changed file: added, changed or removed", + "description": "Only clusters whose labels match", "examples": [ - { - "clusters/CRC/namespaces/payments-dev/namespace.yaml": "added" - } - ], - "title": "Changes", - "type": "object" + null + ] }, - "etag": { + "region": { "anyOf": [ { "type": "string" @@ -6548,1024 +6391,958 @@ "type": "null" } ], - "description": "The entity tag of the namespace that the plan was made against, as `GET .../namespaces/{ns}` gives it. On a change it is the one that `If-Match` matched: send the same `If-Match` when you submit the change. A list of tags passes when one of them is this one; `*` is 428 `precondition-required`, and a weak tag (`W/\"...\"`) never matches. A create takes no `If-Match`, so ignore it there. Compare it; never parse it", - "examples": [ - "3f9a1c0b7e2d4a68" - ], - "title": "Etag" - }, - "files": { - "additionalProperties": { - "type": "string" - }, - "description": "Rendered content of each changed file", + "description": "Only clusters whose clusters.yaml label `region` is this", "examples": [ - { - "clusters/CRC/namespaces/payments-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\n..." - } + "us-central" ], - "title": "Files", - "type": "object" + "title": "Region" }, - "findings": { - "description": "Validator warnings", + "zones": { + "description": "Only clusters with a counted node in each of these zones", "examples": [ [] ], "items": { - "additionalProperties": true, - "type": "object" + "type": "string" }, - "title": "Findings", + "title": "Zones", "type": "array" - }, - "metadata": { - "anyOf": [ - { - "$ref": "#/components/schemas/PlanMetadata" - }, - { - "type": "null" - } - ], - "description": "On a create: the final labels and annotations, each with its source (#479). Null on other writes" - }, - "metadataDiff": { - "anyOf": [ - { - "$ref": "#/components/schemas/PlanMetadataDiff" - }, - { - "type": "null" - } + } + }, + "title": "PlacementConstraints", + "type": "object" + }, + "PlacementExcluded": { + "additionalProperties": false, + "properties": { + "clusterId": { + "description": "A cluster of the environment left out", + "examples": [ + "OCP_GF7" ], - "description": "On a change of an existing namespace (PATCH and the expiry calls): each label and annotation that it moves, before and after, with its source (#481). Empty maps when it moves none. Null on a create, whose `metadata` lists every key" + "title": "Clusterid", + "type": "string" }, - "planHash": { - "description": "SHA-256 of the planned files", + "detail": { + "description": "Why, in words", "examples": [ - "9f2c..." + "newest complete snapshot 95 min old, limit 60 min" ], - "title": "Planhash", + "title": "Detail", "type": "string" }, - "requester": { - "$ref": "#/components/schemas/RequesterView", - "description": "Who the request would be for" - }, - "usage": { - "anyOf": [ - { - "$ref": "#/components/schemas/PlanUsage" - }, - { - "type": "null" - } - ], - "description": "On a change of an existing namespace's quota: its live usage over the last 14 days, read from Thanos for this plan and cached 10 minutes (#310). Null on a create and on a change that leaves the quota as it is" - } - }, - "required": [ - "changes", - "planHash", - "etag", - "requester", - "capacity", - "approval", - "files" - ], - "title": "PlanView", - "type": "object" - }, - "PluginList": { - "additionalProperties": false, - "properties": { - "configured": { - "description": "False when the instance has no `plugins.yaml`: each built-in plugin is then enabled", - "examples": [ - true + "reason": { + "description": "The first hard filter it fails", + "enum": [ + "not-connected", + "not-writable", + "placement-disabled", + "outside-region", + "outside-zones", + "outside-selector", + "stale-data", + "partial-data", + "no-size", + "max-namespaces", + "no-cpu-headroom", + "no-memory-headroom", + "zone-failure-headroom" ], - "title": "Configured", - "type": "boolean" - }, - "instance": { - "description": "The instance that answered", "examples": [ - "nonprod" + "stale-data" ], - "title": "Instance", + "title": "Reason", "type": "string" - }, - "items": { - "description": "The core parts, then each built-in plugin, enabled or not", - "items": { - "$ref": "#/components/schemas/PluginRow" - }, - "title": "Items", - "type": "array" } }, "required": [ - "instance", - "configured", - "items" + "clusterId", + "reason", + "detail" ], - "title": "PluginList", + "title": "PlacementExcluded", "type": "object" }, - "PluginRow": { + "PlacementFactors": { "additionalProperties": false, "properties": { - "core": { - "description": "True for a part of the service itself, which `plugins.yaml` cannot switch", + "balance": { + "description": "0 to 1: 0.5 at the environment's average commitment, more below it", "examples": [ - false + 0.5 ], - "title": "Core", - "type": "boolean" + "title": "Balance", + "type": "number" }, - "disabledEnvironments": { - "description": "The served environments where an override of `plugins.yaml` stops the plugin's writes. The reads stay", + "quotaHeadroom": { + "description": "0 to 1: the smaller resource's headroom after placement, over its limit", "examples": [ - [ - "dev" - ] + 0.875 ], - "items": { - "type": "string" - }, - "title": "Disabledenvironments", - "type": "array" + "title": "Quotaheadroom", + "type": "number" }, - "enabled": { - "description": "Whether this instance mounts the plugin's routes", + "teamAffinity": { + "description": "1 when the team already has a namespace on the cluster, else 0", "examples": [ - true + 0.0 ], - "title": "Enabled", - "type": "boolean" + "title": "Teamaffinity", + "type": "number" }, - "name": { - "description": "The plugin's name: its tag in this document, and its name in `plugins.yaml`", + "usageHeadroom": { + "description": "0 to 1: 1 \u2212 the 14-day p95 of use; 0 when not measured", "examples": [ - "namespaces" + 0.0 ], - "title": "Name", - "type": "string" + "title": "Usageheadroom", + "type": "number" }, - "version": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "The version of the plugin. Null for a plugin that is not enabled: its code is not loaded", + "zoneSpread": { + "description": "0 to 1: the smallest zone's allocatable over the largest's; 0 with under two zones", "examples": [ - "0.1.0" + 0.0 ], - "title": "Version" + "title": "Zonespread", + "type": "number" } }, "required": [ - "name", - "core", - "enabled", - "version", - "disabledEnvironments" + "quotaHeadroom", + "usageHeadroom", + "balance", + "teamAffinity", + "zoneSpread" ], - "title": "PluginRow", + "title": "PlacementFactors", "type": "object" }, - "Policy": { + "PlacementFigures": { "additionalProperties": false, "properties": { - "engine": { - "description": "The policy engine of the instance: `kyverno`, or `none`, which runs no policy anywhere", + "quotaHeadroomAfter": { + "description": "The same after this namespace", + "examples": [ + 112000 + ], + "title": "Quotaheadroomafter", + "type": "integer" + }, + "quotaHeadroomBefore": { + "description": "Size \u00d7 overcommit \u2212 committed \u2212 active reservations, now", + "examples": [ + 120000 + ], + "title": "Quotaheadroombefore", + "type": "integer" + }, + "unit": { + "description": "The unit of the amounts", "enum": [ - "kyverno", - "none" + "millicores", + "bytes" ], "examples": [ - "kyverno" + "millicores" ], - "title": "Engine", + "title": "Unit", "type": "string" }, - "environments": { - "additionalProperties": { - "enum": [ - "enforce", - "audit", - "off" - ], - "type": "string" - }, - "description": "The mode of each served environment: `audit` (the default: admitted, reported and warned), `enforce` (denied) or `off` (no policy)", - "examples": [ + "usageP95": { + "anyOf": [ { - "dev": "audit", - "rnd": "audit" + "type": "number" + }, + { + "type": "null" } ], - "title": "Environments", - "type": "object" + "description": "The 14-day p95 of use over allocatable, from the snapshots. Null when no snapshot measured use", + "examples": [ + null + ], + "title": "Usagep95" }, - "kyvernoVersion": { + "zoneFailureHeadroomAfter": { "anyOf": [ { - "type": "string" + "type": "integer" }, { "type": "null" } ], - "description": "The Kyverno CLI that the image pins: the least version that the clusters must run. Null outside the image", + "description": "The headroom after this namespace with the largest zone lost; only in placement.yaml `zoneFailureEnvironments` (prod)", "examples": [ - "v1.20.0" + null ], - "title": "Kyvernoversion" + "title": "Zonefailureheadroomafter" } }, "required": [ - "engine", - "kyvernoVersion", - "environments" + "unit", + "quotaHeadroomBefore", + "quotaHeadroomAfter", + "zoneFailureHeadroomAfter", + "usageP95" ], - "title": "Policy", + "title": "PlacementFigures", "type": "object" }, - "PolicyBundleHashes": { + "PlacementRanked": { "additionalProperties": false, "properties": { - "live": { + "basis": { "anyOf": [ { + "enum": [ + "simulated", + "allocatable" + ], "type": "string" }, { "type": "null" } ], - "description": "Version 1 SHA-256 from the generated policy digest annotations observed on this cluster. Null for an empty bundle or an unavailable policy list.", + "description": "The size headroom is measured against, as the Capacity tab's", "examples": [ - null + "simulated" ], - "title": "Live" + "title": "Basis" }, - "rendered": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "boundBy": { + "description": "The resource whose commitment is higher after placement", + "enum": [ + "cpu", + "memory", + "both" ], - "description": "Version 1 SHA-256 of the generated policies rendered for this environment. Null for an empty render.", "examples": [ - null + "cpu" ], - "title": "Rendered" - } - }, - "required": [ - "rendered", - "live" - ], - "title": "PolicyBundleHashes", - "type": "object" - }, - "PolicyBundleView": { - "additionalProperties": false, - "properties": { - "actionsDiffer": { - "description": "Rendered policies whose live `validationActions` are not those of the environment's mode (at most 20)", - "examples": [ - [] - ], - "items": { - "type": "string" - }, - "title": "Actionsdiffer", - "type": "array" + "title": "Boundby", + "type": "string" }, - "actionsDifferTotal": { - "description": "How many rendered policies on the cluster have other `validationActions` than the mode's: `actionsDiffer` names 20 at most", + "clusterId": { + "description": "A cluster that passes every hard filter", "examples": [ - 0 + "CRC" ], - "title": "Actionsdiffertotal", - "type": "integer" + "title": "Clusterid", + "type": "string" }, - "current": { - "description": "Of those, the ones whose `cmapi.net/policy-digest` is the render's", - "examples": [ - 31 - ], - "title": "Current", - "type": "integer" + "cpu": { + "$ref": "#/components/schemas/PlacementFigures", + "description": "CPU, in millicores" }, - "differing": { - "description": "Bundle policies whose digest on the cluster is not the render's (at most 20)", - "examples": [ - [] - ], - "items": { - "type": "string" - }, - "title": "Differing", - "type": "array" + "factors": { + "$ref": "#/components/schemas/PlacementFactors", + "description": "Each factor of the score, before its weight" }, - "expected": { - "description": "The policies of the bundle for the cluster's environment", + "memory": { + "$ref": "#/components/schemas/PlacementFigures", + "description": "Memory, in bytes" + }, + "reserved": { + "description": "True on the cluster the placement holds: the first that still fit under its lock", "examples": [ - 31 + true ], - "title": "Expected", - "type": "integer" + "title": "Reserved", + "type": "boolean" }, - "live": { - "description": "Of those, the ones on the cluster", + "score": { + "description": "0 to 100: the weighted factors \u00d7 the cluster's `placement.weight`, capped at 100", "examples": [ - 31 + 50 ], - "title": "Live", + "title": "Score", "type": "integer" }, - "missing": { - "description": "Bundle policies that are not on the cluster (at most 20 names)", - "examples": [ - [] + "snapshotAt": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } ], - "items": { - "type": "string" - }, - "title": "Missing", - "type": "array" - }, - "ready": { - "description": "Of those, the ones whose `status.conditionStatus.ready` is true", + "description": "The end of the newest complete snapshot's interval", "examples": [ - 31 + "2026-11-26T17:00:00Z" ], - "title": "Ready", - "type": "integer" + "title": "Snapshotat" } }, "required": [ - "expected", - "live", - "current", - "ready", - "missing", - "differing", - "actionsDiffer", - "actionsDifferTotal" + "clusterId", + "score", + "reserved", + "basis", + "snapshotAt", + "boundBy", + "factors", + "cpu", + "memory" ], - "title": "PolicyBundleView", + "title": "PlacementRanked", "type": "object" }, - "PolicyCheck": { + "PlacementRequest": { "additionalProperties": false, "properties": { - "key": { + "constraints": { + "$ref": "#/components/schemas/PlacementConstraints", + "description": "Where the namespace may go" + }, + "environment": { + "description": "The environment of the new namespace: one this instance serves", + "examples": [ + "dev" + ], + "title": "Environment", + "type": "string" + }, + "quota": { "anyOf": [ { - "type": "string" + "additionalProperties": { + "type": "string" + }, + "type": "object" }, { "type": "null" } ], - "description": "The key it checks; null for a rule over the keys that no stanza declares", + "description": "Custom tier only: the sizable quota keys, as the create sends them", "examples": [ - "cmapi.net/team" + null ], - "title": "Key" + "title": "Quota" }, - "kind": { - "description": "What the rendered policy checks: label, annotation, quota or limit", + "team": { + "anyOf": [ + { + "pattern": "^[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$", + "type": "string" + }, + { + "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", "examples": [ - "label" + "payments" ], - "title": "Kind", - "type": "string" + "title": "Team" }, - "rule": { - "description": "The rule: required, pattern, enum, max, prefix and the others of core/policygen.py", + "tier": { + "default": "small", + "description": "A tier of GET /tiers, or custom", "examples": [ - "pattern" + "small" ], - "title": "Rule", + "title": "Tier", "type": "string" } }, "required": [ - "kind", - "key", - "rule" + "environment" ], - "title": "PolicyCheck", + "title": "PlacementRequest", "type": "object" }, - "PolicyCluster": { + "PlacementResult": { "additionalProperties": false, "properties": { "asOf": { - "anyOf": [ - { - "format": "date-time", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "The last good read of the reports. For `unreachable` and `not-imported`, when the registry observed the current import status, or null if never imported.", + "description": "When the clusters were ranked", "examples": [ - "2026-11-17T18:02:11Z" + "2026-11-26T17:00:12Z" ], - "title": "Asof" + "format": "date-time", + "title": "Asof", + "type": "string" }, - "bundle": { + "clusterId": { "anyOf": [ { - "$ref": "#/components/schemas/PolicyBundleView" + "type": "string" }, { "type": "null" } ], - "description": "The bundle on the cluster against the render. Null when the policies are not read", - "examples": [ - null - ] - }, - "clusterId": { - "description": "Cluster", + "description": "The reserved cluster: the create's path cluster. Null on a dry run", "examples": [ "CRC" ], - "title": "Clusterid", - "type": "string" + "title": "Clusterid" }, - "counts": { + "excluded": { + "description": "Every other cluster of the environment in the caller's scope, with its reason", + "items": { + "$ref": "#/components/schemas/PlacementExcluded" + }, + "title": "Excluded", + "type": "array" + }, + "expiresAt": { "anyOf": [ { - "$ref": "#/components/schemas/PolicyCounts" + "format": "date-time", + "type": "string" }, { "type": "null" } ], - "description": "Results of the bundle's policies on the managed namespaces. Null, never zero, when they are not known", + "description": "When the reservation lapses unless a create claims it. Null on a dry run", "examples": [ - null - ] + "2026-11-26T17:15:00Z" + ], + "title": "Expiresat" }, - "dropped": { + "placementId": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "description": "Rows past the cap, counted in `counts` and not listed. Null when the counts are null", + "description": "The reservation to send as the create's `placementId`. Null on a dry run", "examples": [ - 0 + "pl-20261126-3f9a1c2e" ], - "title": "Dropped" + "title": "Placementid" }, - "env": { - "description": "Its environment", - "examples": [ - "dev" - ], - "title": "Env", - "type": "string" + "ranked": { + "description": "The clusters that pass, best first; ties go to the lower cluster ID", + "items": { + "$ref": "#/components/schemas/PlacementRanked" + }, + "title": "Ranked", + "type": "array" }, - "hashState": { - "description": "Current when the live hash matches the render, drift when it differs, off for an empty bundle, unknown when the reports or live policies cannot establish the comparison. Behind means live matches Git while the render differs. The API has no Git hash yet, so behind cannot occur.", - "enum": [ - "current", - "behind", - "drift", - "unknown", - "off" - ], + "request": { + "$ref": "#/components/schemas/PlacementAsk", + "description": "What was asked, sized from the tier" + } + }, + "required": [ + "placementId", + "expiresAt", + "clusterId", + "asOf", + "request", + "ranked", + "excluded" + ], + "title": "PlacementResult", + "type": "object" + }, + "PlanAdoption": { + "additionalProperties": false, + "properties": { + "keys": { + "description": "Each label and annotation under a skip prefix, and whether it is kept", + "items": { + "$ref": "#/components/schemas/AdoptionKey" + }, + "title": "Keys", + "type": "array" + }, + "label": { + "description": "The opt-in label. It stays on the namespace after the adoption and is then ignored; removing it before the merge cancels the request", "examples": [ - "current" + "cmapi.net/adopt" ], - "title": "Hashstate", + "title": "Label", "type": "string" }, - "hashes": { - "$ref": "#/components/schemas/PolicyBundleHashes", - "description": "The environment's rendered hash and the cluster's observed hash." + "missingKeys": { + "description": "Each declared key that the adopted namespace will still lack, which a later change request can add, required ones first", + "examples": [ + [] + ], + "items": { + "$ref": "#/components/schemas/MissingKey" + }, + "title": "Missingkeys", + "type": "array" }, - "hidden": { - "anyOf": [ - { - "$ref": "#/components/schemas/PolicyHidden" - }, + "notAdopted": { + "additionalProperties": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ] + }, + "description": "How many objects of the other kinds the namespace has, which stay unmanaged; null when they could not be counted", + "examples": [ { - "type": "null" + "RoleBinding": 1, + "ServiceAccount": 2 } ], - "description": "Results that are counted and not shown. Null when the counts are null", - "examples": [ - null - ] + "title": "Notadopted", + "type": "object" }, - "liveActions": { - "description": "The `validationActions` that the cluster's copies of the bundle carry: `Audit` and `Warn` for audit, `Deny` for enforce. Empty when none is read", + "objects": { + "description": "Each object that the plan read and adopts: the Namespace, each ResourceQuota and each LimitRange. cmapi reads them again when the request is approved, when the bot opens the pull request and in its check; a difference fails the request", + "items": { + "$ref": "#/components/schemas/AdoptedObject" + }, + "title": "Objects", + "type": "array" + }, + "recognised": { + "description": "Each adoptionLabels key and value of metadata-keys.yaml that the namespace carries: made by another tool", "examples": [ [ - "Audit", - "Warn" + "company.net/provisioner=cluster-configs" ] ], "items": { "type": "string" }, - "title": "Liveactions", + "title": "Recognised", "type": "array" }, - "mode": { - "description": "The mode that instance.yaml configures for the environment", - "enum": [ - "enforce", - "audit", - "off" - ], + "snapshotHash": { + "description": "SHA-256 of the objects as read: the base of the policy checks at plan time and in the pull request's check, which never take it from the pull request", "examples": [ - "audit" + "5d1f0c9e2b7a4c3d8e6f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d" ], - "title": "Mode", + "title": "Snapshothash", "type": "string" }, - "state": { - "description": "What can be said of the cluster's reports: `ok`; `loading` (not listed yet); `not-installed` (discovery does not serve wgpolicyk8s.io/v1alpha2); `forbidden` (cmapi-reader may not list the reports or the policies); `not-imported` (clusters.yaml names the cluster and no import Secret does: nothing was tried); `unreachable` (the cluster's import is not connected: the detail names its status of GET /clusters); `stale` (no good read for 30 minutes: the counts are the last ones read); `capped` (rows past policy.reports.maxResultsPerCluster are counted and not listed); `drift` (the bundle on the cluster is not the render, or its actions are not the mode's); `mode-off` (the environment's mode is off); `engine-off` (policy.engine is none)", - "enum": [ - "ok", - "loading", - "not-installed", - "forbidden", - "not-imported", - "unreachable", - "stale", - "capped", - "drift", - "mode-off", - "engine-off" - ], + "supplied": { + "$ref": "#/components/schemas/SuppliedMetadata", + "description": "The labels and annotations that the request adds to the namespace (#739), which it lacked: empty maps when it adds none" + } + }, + "required": [ + "objects", + "label", + "recognised", + "keys", + "notAdopted", + "snapshotHash", + "supplied", + "missingKeys" + ], + "title": "PlanAdoption", + "type": "object" + }, + "PlanMetadata": { + "additionalProperties": false, + "properties": { + "annotations": { + "additionalProperties": { + "$ref": "#/components/schemas/MetadataValue" + }, + "description": "Each annotation that the request sets or that cmapi fills in, with its source", "examples": [ - "ok" + { + "cmapi.net/team-dl": { + "source": "request", + "value": "payments-team@ephico2real.com" + } + } ], - "title": "State", - "type": "string" + "title": "Annotations", + "type": "object" }, - "stateDetail": { - "anyOf": [ - { - "type": "string" - }, + "labels": { + "additionalProperties": { + "$ref": "#/components/schemas/MetadataValue" + }, + "description": "Each label that the request sets or that cmapi fills in, with its source. cmapi's own system labels are not listed", + "examples": [ { - "type": "null" + "cmapi.net/cost-center": { + "source": "request", + "value": "cc-4410" + }, + "cmapi.net/team": { + "source": "request", + "value": "payments" + } } ], - "description": "Why, in words; null when the state is ok", + "title": "Labels", + "type": "object" + }, + "namespace": { + "description": "The namespace name", "examples": [ - null + "payments-dev" ], - "title": "Statedetail" + "title": "Namespace", + "type": "string" } }, "required": [ - "clusterId", - "env", - "mode", - "liveActions", - "state", - "stateDetail", - "asOf", - "bundle", - "hashes", - "hashState", - "counts", - "hidden", - "dropped" + "namespace", + "labels", + "annotations" ], - "title": "PolicyCluster", + "title": "PlanMetadata", "type": "object" }, - "PolicyCounts": { + "PlanMetadataDiff": { "additionalProperties": false, "properties": { - "error": { - "description": "Results that Kyverno could not evaluate", + "annotations": { + "additionalProperties": { + "$ref": "#/components/schemas/MetadataChange" + }, + "description": "Each annotation whose value the change moves, by key, in the same form", "examples": [ - 0 + { + "runbook.ephico2real.com/url": { + "after": "https://wiki.ephico2real.com/payments/runbook", + "source": "request" + } + } ], - "title": "Error", - "type": "integer" + "title": "Annotations", + "type": "object" }, - "fail": { - "description": "Results that failed. In `audit` the resource was admitted and the failure recorded; in `enforce` a failure at admission was denied, and a background scan still reports one", + "labels": { + "additionalProperties": { + "$ref": "#/components/schemas/MetadataChange" + }, + "description": "Each label whose value the change moves, by key: only effective changes, and only the keys that a request may name or that cmapi fills in (cmapi's own system labels are not listed)", "examples": [ - 2 + { + "cmapi.net/cost-center": { + "before": "cc-4410", + "source": "request" + } + } ], - "title": "Fail", - "type": "integer" - }, - "pass": { - "description": "Results that passed", - "examples": [ - 412 - ], - "title": "Pass", - "type": "integer" - }, - "skip": { - "description": "Results that did not apply", - "examples": [ - 0 - ], - "title": "Skip", - "type": "integer" - }, - "warn": { - "description": "Results of a policy that is not scored: Kyverno reports such a failure as warn", - "examples": [ - 0 - ], - "title": "Warn", - "type": "integer" + "title": "Labels", + "type": "object" } }, "required": [ - "pass", - "fail", - "warn", - "error", - "skip" + "labels", + "annotations" ], - "title": "PolicyCounts", + "title": "PlanMetadataDiff", "type": "object" }, - "PolicyHidden": { + "PlanUsage": { "additionalProperties": false, "properties": { - "otherPolicies": { - "description": "Results of policies that are not in the bundle of the cluster's environment", - "examples": [ - 41 + "coverage": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } ], - "title": "Otherpolicies", - "type": "integer" - }, - "stale": { - "description": "Results of a bundle policy that is not on the cluster any more: Kyverno drops them at its next reconcile", + "description": "The share of the window's 4,032 five-minute steps with a running-pod sample", "examples": [ - 0 + 0.98 ], - "title": "Stale", - "type": "integer" + "title": "Coverage" }, - "unmanaged": { - "description": "Results on namespaces that cmapi does not manage, and on cluster-scoped objects other than a Namespace: counted, never listed", - "examples": [ - 1840 + "cpu": { + "$ref": "#/components/schemas/UsageFigures", + "description": "CPU, in millicores" + }, + "evaluatedAt": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } ], - "title": "Unmanaged", - "type": "integer" - } - }, - "required": [ - "unmanaged", - "otherPolicies", - "stale" - ], - "title": "PolicyHidden", - "type": "object" - }, - "PolicyResource": { - "additionalProperties": false, - "properties": { - "apiVersion": { - "description": "apiVersion", + "description": "The one instant every query used, RFC 3339; null when nothing was read", "examples": [ - "v1" + "2026-11-25T10:00:00+00:00" ], - "title": "Apiversion", - "type": "string" + "title": "Evaluatedat" }, - "kind": { - "description": "Kind", + "memory": { + "$ref": "#/components/schemas/UsageFigures", + "description": "Memory, in bytes" + }, + "reason": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Why the state is not ok, in a sentence; null when it is", "examples": [ - "Namespace" + null ], - "title": "Kind", - "type": "string" + "title": "Reason" }, - "name": { - "description": "Name", + "state": { + "description": "`ok`, the figures can be judged by. `insufficient-data`: no usage source is configured, or Thanos has too few samples (under 80% of the 14-day window's 5-minute steps), and the figures are null. `unavailable`: Thanos did not answer in 10 seconds; the change needs a platform approval (docs/01)", + "enum": [ + "ok", + "insufficient-data", + "unavailable" + ], "examples": [ - "orders-dev" + "ok" ], - "title": "Name", + "title": "State", "type": "string" - } - }, - "required": [ - "apiVersion", - "kind", - "name" - ], - "title": "PolicyResource", - "type": "object" - }, - "PolicyResultPage": { - "additionalProperties": false, - "properties": { - "clusters": { - "description": "Each cluster of an environment where the caller holds objects:read", - "items": { - "$ref": "#/components/schemas/PolicyCluster" - }, - "title": "Clusters", - "type": "array" - }, - "items": { - "description": "One page of fail, warn and error results on managed namespaces", - "items": { - "$ref": "#/components/schemas/PolicyResultRow" - }, - "title": "Items", - "type": "array" }, - "letters": { + "units": { "additionalProperties": { - "type": "integer" + "type": "string" }, - "description": "Rows per first letter of the namespace", + "description": "The unit of each resource's figures", "examples": [ { - "O": 1 + "cpu": "millicores", + "memory": "bytes" } ], - "title": "Letters", + "title": "Units", "type": "object" }, - "page": { - "$ref": "#/components/schemas/PageInfo", - "description": "Paging" - }, - "policies": { - "description": "Each policy of the bundles of those environments, with its counts", - "items": { - "$ref": "#/components/schemas/PolicySummary" - }, - "title": "Policies", - "type": "array" - }, - "policy": { - "$ref": "#/components/schemas/Policy", - "description": "The engine, the pinned Kyverno version and each environment's mode: the `policy` object of GET /api/v1/admin/integrations" + "window": { + "const": "14d", + "description": "The window of p95 and peak", + "examples": [ + "14d" + ], + "title": "Window", + "type": "string" } }, "required": [ - "policy", - "clusters", - "policies", - "items", - "page", - "letters" + "state", + "reason", + "window", + "coverage", + "evaluatedAt", + "units", + "cpu", + "memory" ], - "title": "PolicyResultPage", + "title": "PlanUsage", "type": "object" }, - "PolicyResultRow": { + "PlanView": { "additionalProperties": false, "properties": { - "clusterId": { - "description": "Cluster", - "examples": [ - "CRC" + "adoption": { + "anyOf": [ + { + "$ref": "#/components/schemas/PlanAdoption" + }, + { + "type": "null" + } ], - "title": "Clusterid", - "type": "string" + "description": "On an adoption: the objects it read, the keys under a skip prefix, and what stays unmanaged (story #26). Null on other writes" }, - "env": { - "description": "Environment", - "examples": [ - "dev" - ], - "title": "Env", - "type": "string" + "approval": { + "$ref": "#/components/schemas/ApprovalView", + "description": "The approval that would apply" }, - "kyvernoRule": { + "beyondTier": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/BeyondTier" }, { "type": "null" } ], - "description": "Kyverno's own rule name from the report (`validation` for a ValidatingPolicy)", - "examples": [ - "validation" - ], - "title": "Kyvernorule" + "description": "The values beyond the tier and the approvals they add; null when the request has none" }, - "message": { - "description": "Kyverno's message, at most 300 characters", - "examples": [ - "the label keys other.example/x are not declared in metadata-keys.yaml" - ], - "title": "Message", - "type": "string" - }, - "mode": { - "description": "The environment's mode: in `audit` the resource was admitted, in `enforce` an admission was denied", - "enum": [ - "enforce", - "audit", - "off" - ], - "examples": [ - "audit" - ], - "title": "Mode", - "type": "string" + "capacity": { + "$ref": "#/components/schemas/CapacityView", + "description": "The capacity check" }, - "namespace": { - "description": "The managed namespace: the resource's, or the Namespace itself", + "changes": { + "additionalProperties": { + "type": "string" + }, + "description": "Per changed file: added, changed or removed", "examples": [ - "orders-dev" + { + "clusters/CRC/namespaces/payments-dev/namespace.yaml": "added" + } ], - "title": "Namespace", - "type": "string" + "title": "Changes", + "type": "object" }, - "observedAt": { + "etag": { "anyOf": [ { - "format": "date-time", "type": "string" }, { "type": "null" } ], - "description": "The result's timestamp", + "description": "The entity tag of the namespace that the plan was made against, as `GET .../namespaces/{ns}` gives it. On a change it is the one that `If-Match` matched: send the same `If-Match` when you submit the change. A list of tags passes when one of them is this one; `*` is 428 `precondition-required`, and a weak tag (`W/\"...\"`) never matches. A create takes no `If-Match`, so ignore it there. Compare it; never parse it", "examples": [ - "2026-11-17T17:58:40Z" + "3f9a1c0b7e2d4a68" ], - "title": "Observedat" + "title": "Etag" }, - "policy": { - "description": "The policy", + "files": { + "additionalProperties": { + "type": "string" + }, + "description": "Rendered content of each changed file", "examples": [ - "cmapi-metadata-dev-label-other-keys-prefix" + { + "clusters/CRC/namespaces/payments-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\n..." + } ], - "title": "Policy", - "type": "string" + "title": "Files", + "type": "object" }, - "process": { + "findings": { + "description": "Validator warnings", + "examples": [ + [] + ], + "items": { + "additionalProperties": true, + "type": "object" + }, + "title": "Findings", + "type": "array" + }, + "metadata": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/PlanMetadata" }, { "type": "null" } ], - "description": "`admission review` or `background scan`", - "examples": [ - "background scan" - ], - "title": "Process" - }, - "resource": { - "$ref": "#/components/schemas/PolicyResource", - "description": "The resource the result is about" - }, - "result": { - "description": "The verdict", - "enum": [ - "fail", - "warn", - "error" - ], - "examples": [ - "fail" - ], - "title": "Result", - "type": "string" + "description": "On a create: the final labels and annotations, each with its source (#479). Null on other writes" }, - "rule": { + "metadataDiff": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/PlanMetadataDiff" }, { "type": "null" } ], - "description": "The rule: index.json's rule of a rendered policy, else Kyverno's own rule", + "description": "On a change of an existing namespace (PATCH and the expiry calls): each label and annotation that it moves, before and after, with its source (#481). Empty maps when it moves none. Null on a create, whose `metadata` lists every key" + }, + "planHash": { + "description": "SHA-256 of the planned files", "examples": [ - "prefix" + "9f2c..." ], - "title": "Rule" + "title": "Planhash", + "type": "string" }, - "source": { + "requester": { + "$ref": "#/components/schemas/RequesterView", + "description": "Who the request would be for" + }, + "usage": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/PlanUsage" }, { "type": "null" } ], - "description": "The result's source, as Kyverno writes it", - "examples": [ - "KyvernoValidatingPolicy" - ], - "title": "Source" + "description": "On a change of an existing namespace's quota: its live usage over the last 14 days, read from Thanos for this plan and cached 10 minutes (#310). Null on a create and on a change that leaves the quota as it is" } }, "required": [ - "clusterId", - "env", - "mode", - "namespace", - "resource", - "policy", - "rule", - "kyvernoRule", - "result", - "message", - "process", - "source", - "observedAt" + "changes", + "planHash", + "etag", + "requester", + "capacity", + "approval", + "files" ], - "title": "PolicyResultRow", + "title": "PlanView", "type": "object" }, - "PolicySummary": { + "PluginList": { "additionalProperties": false, "properties": { - "check": { - "anyOf": [ - { - "$ref": "#/components/schemas/PolicyCheck" - }, - { - "type": "null" - } - ], - "description": "What a rendered policy checks, from the bundle's index.json; null for a hand-written policy", + "configured": { + "description": "False when the instance has no `plugins.yaml`: each built-in plugin is then enabled", "examples": [ - null - ] - }, - "counts": { - "anyOf": [ - { - "$ref": "#/components/schemas/PolicyCounts" - }, - { - "type": "null" - } + true ], - "description": "Its results over the clusters in scope that run it and have counts, following `clusterId`, `env` and `namespace`. Null, never zero, when no such cluster has counts: Kyverno not installed, the policy not on the cluster, the reports not readable or not listed yet", - "examples": [ - null - ] + "title": "Configured", + "type": "boolean" }, - "description": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "instance": { + "description": "The instance that answered", + "examples": [ + "nonprod" ], - "description": "`policies.kyverno.io/description`", + "title": "Instance", + "type": "string" + }, + "items": { + "description": "The core parts, then each built-in plugin, enabled or not", + "items": { + "$ref": "#/components/schemas/PluginRow" + }, + "title": "Items", + "type": "array" + } + }, + "required": [ + "instance", + "configured", + "items" + ], + "title": "PluginList", + "type": "object" + }, + "PluginRow": { + "additionalProperties": false, + "properties": { + "core": { + "description": "True for a part of the service itself, which `plugins.yaml` cannot switch", "examples": [ - "The labels and annotations that metadata-keys.yaml requires" + false ], - "title": "Description" + "title": "Core", + "type": "boolean" }, - "environments": { - "description": "The environments in scope whose bundle has it", + "disabledEnvironments": { + "description": "The served environments where an override of `plugins.yaml` stops the plugin's writes. The reads stay", "examples": [ [ "dev" @@ -7574,174 +7351,244 @@ "items": { "type": "string" }, - "title": "Environments", + "title": "Disabledenvironments", "type": "array" }, - "generated": { - "description": "True for a policy that cmapi renders from its configuration", + "enabled": { + "description": "Whether this instance mounts the plugin's routes", "examples": [ true ], - "title": "Generated", + "title": "Enabled", "type": "boolean" }, - "kind": { - "description": "Its kind", + "name": { + "description": "The plugin's name: its tag in this document, and its name in `plugins.yaml`", "examples": [ - "ValidatingPolicy" + "namespaces" ], - "title": "Kind", + "title": "Name", "type": "string" }, - "name": { - "description": "The policy's name, from the bundle", + "version": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The version of the plugin. Null for a plugin that is not enabled: its code is not loaded", "examples": [ - "cmapi-metadata-dev-label-cmapi-net-team-pattern" + "0.1.0" ], - "title": "Name", - "type": "string" + "title": "Version" } }, "required": [ "name", - "kind", - "description", - "check", - "environments", - "generated", - "counts" + "core", + "enabled", + "version", + "disabledEnvironments" ], - "title": "PolicySummary", + "title": "PluginRow", "type": "object" }, - "PrView": { + "Policy": { "additionalProperties": false, "properties": { - "branch": { - "description": "Bot branch", - "examples": [ - "cmapi/CRC/req-20261105-0001" + "engine": { + "description": "The policy engine of the instance: `kyverno`, or `none`, which runs no policy anywhere", + "enum": [ + "kyverno", + "none" ], - "title": "Branch", - "type": "string" - }, - "head": { - "description": "PR head commit", "examples": [ - "0a1b2c3d" + "kyverno" ], - "title": "Head", + "title": "Engine", "type": "string" }, - "number": { - "description": "PR number", + "environments": { + "additionalProperties": { + "enum": [ + "enforce", + "audit", + "off" + ], + "type": "string" + }, + "description": "The mode of each served environment: `audit` (the default: admitted, reported and warned), `enforce` (denied) or `off` (no policy)", "examples": [ - 12 + { + "dev": "audit", + "rnd": "audit" + } ], - "title": "Number", - "type": "integer" + "title": "Environments", + "type": "object" }, - "url": { - "description": "PR URL", + "kyvernoVersion": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The Kyverno CLI that the image pins: the least version that the clusters must run. Null outside the image", "examples": [ - "https://git.example/cmapi/cluster-configs-nonprod/pulls/12" + "v1.20.0" ], - "title": "Url", - "type": "string" + "title": "Kyvernoversion" } }, "required": [ - "number", - "url", - "branch", - "head" + "engine", + "kyvernoVersion", + "environments" ], - "title": "PrView", + "title": "Policy", "type": "object" }, - "ProblemDetail": { - "additionalProperties": true, - "description": "RFC 9457 problem details, the one shape of every refusal.", + "PolicyBundleHashes": { + "additionalProperties": false, "properties": { - "code": { - "description": "The problem code, the last segment of type", - "examples": [ - "policy-violation" + "live": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } ], - "title": "Code", - "type": "string" - }, - "detail": { - "description": "What went wrong, for a person", + "description": "Version 1 SHA-256 from the generated policy digest annotations observed on this cluster. Null for an empty bundle or an unavailable policy list.", "examples": [ - "Metadata refused" + null ], - "title": "Detail", - "type": "string" + "title": "Live" }, - "errors": { + "rendered": { "anyOf": [ { - "items": { - "additionalProperties": true, - "type": "object" - }, - "type": "array" + "type": "string" }, { "type": "null" } ], - "description": "One entry for each key or limit that a policy-violation refuses: `code` (reserved_key, invalid_key, invalid_value, derived_key, missing_required_key, too_many_keys or annotations_too_large) and, where they apply, `key`, `kind` (label or annotation) and `detail`, the rule in words", + "description": "Version 1 SHA-256 of the generated policies rendered for this environment. Null for an empty render.", "examples": [ - [ - { - "code": "reserved_key", - "key": "cmapi.net/tier" - } - ] + null ], - "title": "Errors" + "title": "Rendered" + } + }, + "required": [ + "rendered", + "live" + ], + "title": "PolicyBundleHashes", + "type": "object" + }, + "PolicyBundleView": { + "additionalProperties": false, + "properties": { + "actionsDiffer": { + "description": "Rendered policies whose live `validationActions` are not those of the environment's mode (at most 20)", + "examples": [ + [] + ], + "items": { + "type": "string" + }, + "title": "Actionsdiffer", + "type": "array" }, - "status": { - "description": "HTTP status", + "actionsDifferTotal": { + "description": "How many rendered policies on the cluster have other `validationActions` than the mode's: `actionsDiffer` names 20 at most", "examples": [ - 422 + 0 ], - "title": "Status", + "title": "Actionsdiffertotal", "type": "integer" }, - "title": { - "description": "Short name of the problem", + "current": { + "description": "Of those, the ones whose `cmapi.net/policy-digest` is the render's", "examples": [ - "policy violation" + 31 ], - "title": "Title", - "type": "string" + "title": "Current", + "type": "integer" }, - "type": { - "description": "Problem type URI", + "differing": { + "description": "Bundle policies whose digest on the cluster is not the render's (at most 20)", "examples": [ - "https://cmapi.ephico2real.com/problems/policy-violation" + [] ], - "title": "Type", - "type": "string" + "items": { + "type": "string" + }, + "title": "Differing", + "type": "array" + }, + "expected": { + "description": "The policies of the bundle for the cluster's environment", + "examples": [ + 31 + ], + "title": "Expected", + "type": "integer" + }, + "live": { + "description": "Of those, the ones on the cluster", + "examples": [ + 31 + ], + "title": "Live", + "type": "integer" + }, + "missing": { + "description": "Bundle policies that are not on the cluster (at most 20 names)", + "examples": [ + [] + ], + "items": { + "type": "string" + }, + "title": "Missing", + "type": "array" + }, + "ready": { + "description": "Of those, the ones whose `status.conditionStatus.ready` is true", + "examples": [ + 31 + ], + "title": "Ready", + "type": "integer" } }, "required": [ - "type", - "title", - "status", - "detail", - "code" + "expected", + "live", + "current", + "ready", + "missing", + "differing", + "actionsDiffer", + "actionsDifferTotal" ], - "title": "ProblemDetail", + "title": "PolicyBundleView", "type": "object" }, - "PruneConfirm": { + "PolicyCheck": { "additionalProperties": false, "properties": { - "clusterId": { + "key": { "anyOf": [ { "type": "string" @@ -7750,101 +7597,69 @@ "type": "null" } ], - "description": "Cluster, when the name is ambiguous", + "description": "The key it checks; null for a rule over the keys that no stanza declares", "examples": [ - "CRC" + "cmapi.net/team" ], - "title": "Clusterid" + "title": "Key" }, - "namespace": { - "description": "Namespace whose delete is awaiting a prune", + "kind": { + "description": "What the rendered policy checks: label, annotation, quota or limit", "examples": [ - "payments-dev" + "label" ], - "title": "Namespace", + "title": "Kind", + "type": "string" + }, + "rule": { + "description": "The rule: required, pattern, enum, max, prefix and the others of core/policygen.py", + "examples": [ + "pattern" + ], + "title": "Rule", "type": "string" } }, "required": [ - "namespace" + "kind", + "key", + "rule" ], - "title": "PruneConfirm", + "title": "PolicyCheck", "type": "object" }, - "QuotaPage": { + "PolicyCluster": { "additionalProperties": false, "properties": { - "facets": { - "additionalProperties": { - "type": "integer" - }, - "description": "Attention counts over the filters, each the count that `state` with its name lists: `quota-tight`, `near-limit` (a use of 80% or more), `oversized` (`quota-oversized` or `requests-oversized`), `idle`, `tier-outdated`, `open-request`, and `needs-attention`: the rows whose severity is 1 or more (`sort=severity`)", - "examples": [ + "asOf": { + "anyOf": [ { - "idle": 0, - "near-limit": 0, - "needs-attention": 0, - "open-request": 0, - "oversized": 0, - "quota-tight": 0, - "tier-outdated": 0 + "format": "date-time", + "type": "string" + }, + { + "type": "null" } ], - "title": "Facets", - "type": "object" - }, - "items": { - "description": "One page", - "items": { - "$ref": "#/components/schemas/QuotaRow" - }, - "title": "Items", - "type": "array" - }, - "letters": { - "additionalProperties": { - "type": "integer" - }, - "description": "Rows per first letter", + "description": "The last good read of the reports. For `unreachable` and `not-imported`, when the registry observed the current import status, or null if never imported.", "examples": [ - { - "P": 3 - } + "2026-11-17T18:02:11Z" ], - "title": "Letters", - "type": "object" + "title": "Asof" }, - "page": { - "$ref": "#/components/schemas/PageInfo", - "description": "Paging" - } - }, - "required": [ - "items", - "page", - "letters", - "facets" - ], - "title": "QuotaPage", - "type": "object" - }, - "QuotaRow": { - "additionalProperties": false, - "properties": { - "app": { + "bundle": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/PolicyBundleView" }, { "type": "null" } ], - "description": "cmapi.net/app", + "description": "The bundle on the cluster against the render. Null when the policies are not read", "examples": [ null - ], - "title": "App" + ] }, "clusterId": { "description": "Cluster", @@ -7854,153 +7669,125 @@ "title": "Clusterid", "type": "string" }, - "cpu": { - "description": "[used, hard] requests.cpu", - "examples": [ - [ - "0", - "8" - ] - ], - "items": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - }, - "title": "Cpu", - "type": "array" - }, - "env": { + "counts": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/PolicyCounts" }, { "type": "null" } ], - "description": "Environment", + "description": "Results of the bundle's policies on the managed namespaces. Null, never zero, when they are not known", "examples": [ - "dev" - ], - "title": "Env" + null + ] }, - "expiresAt": { + "dropped": { "anyOf": [ { - "type": "string" + "type": "integer" }, { "type": "null" } ], - "description": "cmapi.net/expires-at", + "description": "Rows past the cap, counted in `counts` and not listed. Null when the counts are null", "examples": [ - null + 0 ], - "title": "Expiresat" + "title": "Dropped" }, - "memory": { - "description": "[used, hard] requests.memory", + "env": { + "description": "Its environment", "examples": [ - [ - "0", - "16Gi" - ] + "dev" ], - "items": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] - }, - "title": "Memory", - "type": "array" + "title": "Env", + "type": "string" }, - "name": { - "description": "Namespace", + "hashState": { + "description": "Current when the live hash matches the render, drift when it differs, off for an empty bundle, unknown when the reports or live policies cannot establish the comparison. Behind means live matches Git while the render differs. The API has no Git hash yet, so behind cannot occur.", + "enum": [ + "current", + "behind", + "drift", + "unknown", + "off" + ], "examples": [ - "payments-dev" + "current" ], - "title": "Name", + "title": "Hashstate", "type": "string" }, - "openRequest": { + "hashes": { + "$ref": "#/components/schemas/PolicyBundleHashes", + "description": "The environment's rendered hash and the cluster's observed hash." + }, + "hidden": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/PolicyHidden" }, { "type": "null" } ], - "description": "Request holding the namespace", + "description": "Results that are counted and not shown. Null when the counts are null", "examples": [ null - ], - "title": "Openrequest" + ] }, - "pods": { - "description": "[used, hard] pods", + "liveActions": { + "description": "The `validationActions` that the cluster's copies of the bundle carry: `Audit` and `Warn` for audit, `Deny` for enforce. Empty when none is read", "examples": [ [ - "0", - "50" + "Audit", + "Warn" ] ], "items": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ] + "type": "string" }, - "title": "Pods", + "title": "Liveactions", "type": "array" }, - "team": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "mode": { + "description": "The mode that instance.yaml configures for the environment", + "enum": [ + "enforce", + "audit", + "off" ], - "description": "Team", "examples": [ - "payments" + "audit" ], - "title": "Team" + "title": "Mode", + "type": "string" }, - "tier": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } + "state": { + "description": "What can be said of the cluster's reports: `ok`; `loading` (not listed yet); `not-installed` (discovery does not serve wgpolicyk8s.io/v1alpha2); `forbidden` (cmapi-reader may not list the reports or the policies); `not-imported` (clusters.yaml names the cluster and no import Secret does: nothing was tried); `unreachable` (the cluster's import is not connected: the detail names its status of GET /clusters); `stale` (no good read for 30 minutes: the counts are the last ones read); `capped` (rows past policy.reports.maxResultsPerCluster are counted and not listed); `drift` (the bundle on the cluster is not the render, or its actions are not the mode's); `mode-off` (the environment's mode is off); `engine-off` (policy.engine is none)", + "enum": [ + "ok", + "loading", + "not-installed", + "forbidden", + "not-imported", + "unreachable", + "stale", + "capped", + "drift", + "mode-off", + "engine-off" ], - "description": "Tier", "examples": [ - "small" + "ok" ], - "title": "Tier" + "title": "State", + "type": "string" }, - "tierHash": { + "stateDetail": { "anyOf": [ { "type": "string" @@ -8009,241 +7796,305 @@ "type": "null" } ], - "description": "Catalog hash the quota was rendered from", - "examples": [ - "dec3e603bf8d" - ], - "title": "Tierhash" - }, - "tierOutdated": { - "description": "The catalog changed since it was rendered", + "description": "Why, in words; null when the state is ok", "examples": [ - false - ], - "title": "Tieroutdated", - "type": "boolean" - }, - "used": { - "description": "Highest used/hard ratio of the three", - "examples": [ - 0.0 - ], - "title": "Used", - "type": "number" - }, - "verdict": { - "description": "The usage verdict of the latest daily sweep (docs/03, \"Verdicts\"): its worst risk, else its largest waste, else `right-sized`. `insufficient-data` when the sweep could not judge it, when no sweep has run yet, or when the instance has no usage source; `verdictReason` says which", - "enum": [ - "quota-tight", - "idle", - "quota-oversized", - "requests-oversized", - "right-sized", - "insufficient-data" + null ], + "title": "Statedetail" + } + }, + "required": [ + "clusterId", + "env", + "mode", + "liveActions", + "state", + "stateDetail", + "asOf", + "bundle", + "hashes", + "hashState", + "counts", + "hidden", + "dropped" + ], + "title": "PolicyCluster", + "type": "object" + }, + "PolicyCounts": { + "additionalProperties": false, + "properties": { + "error": { + "description": "Results that Kyverno could not evaluate", "examples": [ - "insufficient-data" + 0 ], - "title": "Verdict", - "type": "string" + "title": "Error", + "type": "integer" }, - "verdictDay": { - "anyOf": [ - { - "format": "date", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "The UTC day of the sweep that made the verdict; null when none did. A missed sweep leaves the previous day's verdict", + "fail": { + "description": "Results that failed. In `audit` the resource was admitted and the failure recorded; in `enforce` a failure at admission was denied, and a background scan still reports one", "examples": [ - null + 2 ], - "title": "Verdictday" + "title": "Fail", + "type": "integer" }, - "verdictKind": { - "description": "What the verdict is: `risk`, `waste`, `ok` or `info` (insufficient data)", - "enum": [ - "ok", - "info", - "waste", - "risk" - ], + "pass": { + "description": "Results that passed", "examples": [ - "info" + 412 ], - "title": "Verdictkind", - "type": "string" + "title": "Pass", + "type": "integer" }, - "verdictReason": { - "description": "Why, in a sentence, with the numbers and the threshold", + "skip": { + "description": "Results that did not apply", "examples": [ - "No usage source is configured on this instance (capacity.yaml usage.source is none), so there is no 14-day usage." + 0 ], - "title": "Verdictreason", - "type": "string" + "title": "Skip", + "type": "integer" }, - "verdictResources": { - "description": "The resources the verdict holds for, CPU first; empty when no sweep judged the namespace", + "warn": { + "description": "Results of a policy that is not scored: Kyverno reports such a failure as warn", "examples": [ - [] + 0 ], - "items": { - "enum": [ - "cpu", - "memory" - ], - "type": "string" - }, - "title": "Verdictresources", - "type": "array" + "title": "Warn", + "type": "integer" } }, "required": [ - "name", - "clusterId", - "env", - "team", - "tier", - "cpu", - "memory", - "pods", - "used", - "expiresAt", - "tierHash", - "tierOutdated", - "verdict", - "verdictKind", - "verdictResources", - "verdictReason", - "verdictDay" + "pass", + "fail", + "warn", + "error", + "skip" ], - "title": "QuotaRow", + "title": "PolicyCounts", "type": "object" }, - "Rejection": { + "PolicyHidden": { "additionalProperties": false, "properties": { - "action": { - "description": "`create`, `update`, `delete`, `expiration:extend`, `expiration:set` or `expiration:makePermanent`", + "otherPolicies": { + "description": "Results of policies that are not in the bundle of the cluster's environment", "examples": [ - "create" + 41 ], - "title": "Action", - "type": "string" + "title": "Otherpolicies", + "type": "integer" }, - "automated": { - "description": "A service client or an automation account", + "stale": { + "description": "Results of a bundle policy that is not on the cluster any more: Kyverno drops them at its next reconcile", "examples": [ - false + 0 ], - "title": "Automated", - "type": "boolean" + "title": "Stale", + "type": "integer" }, - "clusterId": { - "description": "Cluster", + "unmanaged": { + "description": "Results on namespaces that cmapi does not manage, and on cluster-scoped objects other than a Namespace: counted, never listed", "examples": [ - "CRC" + 1840 ], - "title": "Clusterid", + "title": "Unmanaged", + "type": "integer" + } + }, + "required": [ + "unmanaged", + "otherPolicies", + "stale" + ], + "title": "PolicyHidden", + "type": "object" + }, + "PolicyResource": { + "additionalProperties": false, + "properties": { + "apiVersion": { + "description": "apiVersion", + "examples": [ + "v1" + ], + "title": "Apiversion", "type": "string" }, - "count": { - "description": "How many times that day", + "kind": { + "description": "Kind", "examples": [ - 2 + "Namespace" ], - "title": "Count", - "type": "integer" + "title": "Kind", + "type": "string" }, - "env": { - "description": "Environment", + "name": { + "description": "Name", "examples": [ - "dev" + "orders-dev" ], - "title": "Env", + "title": "Name", "type": "string" + } + }, + "required": [ + "apiVersion", + "kind", + "name" + ], + "title": "PolicyResource", + "type": "object" + }, + "PolicyResultPage": { + "additionalProperties": false, + "properties": { + "clusters": { + "description": "Each cluster of an environment where the caller holds objects:read", + "items": { + "$ref": "#/components/schemas/PolicyCluster" + }, + "title": "Clusters", + "type": "array" }, - "findings": { - "description": "Each error and warning, at most 20", + "items": { + "description": "One page of fail, warn and error results on managed namespaces", "items": { - "$ref": "#/components/schemas/RejectionFinding" + "$ref": "#/components/schemas/PolicyResultRow" }, - "title": "Findings", + "title": "Items", "type": "array" }, - "firstAt": { - "description": "When it was first refused on its UTC day: the order of the list", + "letters": { + "additionalProperties": { + "type": "integer" + }, + "description": "Rows per first letter of the namespace", "examples": [ - "2026-11-17T17:02:11Z" + { + "O": 1 + } ], - "format": "date-time", - "title": "Firstat", - "type": "string" + "title": "Letters", + "type": "object" }, - "id": { - "description": "`rej-`; never a request ID", - "examples": [ - "rej-1042" - ], - "title": "Id", - "type": "string" + "page": { + "$ref": "#/components/schemas/PageInfo", + "description": "Paging" }, - "lastAt": { - "description": "When it was last refused that day", + "policies": { + "description": "Each policy of the bundles of those environments, with its counts", + "items": { + "$ref": "#/components/schemas/PolicySummary" + }, + "title": "Policies", + "type": "array" + }, + "policy": { + "$ref": "#/components/schemas/Policy", + "description": "The engine, the pinned Kyverno version and each environment's mode: the `policy` object of GET /api/v1/admin/integrations" + } + }, + "required": [ + "policy", + "clusters", + "policies", + "items", + "page", + "letters" + ], + "title": "PolicyResultPage", + "type": "object" + }, + "PolicyResultRow": { + "additionalProperties": false, + "properties": { + "clusterId": { + "description": "Cluster", "examples": [ - "2026-11-17T17:05:40Z" + "CRC" ], - "format": "date-time", - "title": "Lastat", + "title": "Clusterid", "type": "string" }, - "namespace": { - "description": "Namespace", + "env": { + "description": "Environment", "examples": [ - "checkout-dev" + "dev" ], - "title": "Namespace", + "title": "Env", "type": "string" }, - "outcome": { - "description": "`refused`, or `warned`: Kyverno's findings on a plan that went on to a request", + "kyvernoRule": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Kyverno's own rule name from the report (`validation` for a ValidatingPolicy)", + "examples": [ + "validation" + ], + "title": "Kyvernorule" + }, + "message": { + "description": "Kyverno's message, at most 300 characters", + "examples": [ + "the label keys other.example/x are not declared in metadata-keys.yaml" + ], + "title": "Message", + "type": "string" + }, + "mode": { + "description": "The environment's mode: in `audit` the resource was admitted, in `enforce` an admission was denied", "enum": [ - "refused", - "warned" + "enforce", + "audit", + "off" ], "examples": [ - "refused" + "audit" ], - "title": "Outcome", + "title": "Mode", "type": "string" }, - "plugin": { - "description": "Plugin", + "namespace": { + "description": "The managed namespace: the resource's, or the Namespace itself", "examples": [ - "namespaces" + "orders-dev" ], - "title": "Plugin", + "title": "Namespace", "type": "string" }, - "problem": { + "observedAt": { "anyOf": [ { + "format": "date-time", "type": "string" }, { "type": "null" } ], - "description": "The problem code of the 422 of a refused plan", + "description": "The result's timestamp", "examples": [ - "policy-violation" + "2026-11-17T17:58:40Z" ], - "title": "Problem" + "title": "Observedat" }, - "requestId": { + "policy": { + "description": "The policy", + "examples": [ + "cmapi-metadata-dev-label-other-keys-prefix" + ], + "title": "Policy", + "type": "string" + }, + "process": { "anyOf": [ { "type": "string" @@ -8252,104 +8103,110 @@ "type": "null" } ], - "description": "The request of a warned plan or a CI refusal; null for a refused plan, which never became one", + "description": "`admission review` or `background scan`", "examples": [ - null + "background scan" ], - "title": "Requestid" + "title": "Process" }, - "stage": { - "description": "`plan` (the API's plan) or `ci` (the worker's checks of the pull request)", + "resource": { + "$ref": "#/components/schemas/PolicyResource", + "description": "The resource the result is about" + }, + "result": { + "description": "The verdict", "enum": [ - "plan", - "ci" + "fail", + "warn", + "error" ], "examples": [ - "plan" + "fail" ], - "title": "Stage", + "title": "Result", "type": "string" }, - "username": { - "description": "Who asked: the username only, never the email, the employee ID or the justification", + "rule": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The rule: index.json's rule of a rendered policy, else Kyverno's own rule", "examples": [ - "ola" + "prefix" ], - "title": "Username", - "type": "string" + "title": "Rule" + }, + "source": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The result's source, as Kyverno writes it", + "examples": [ + "KyvernoValidatingPolicy" + ], + "title": "Source" } }, "required": [ - "id", - "firstAt", - "lastAt", - "count", - "stage", - "outcome", - "problem", "clusterId", "env", + "mode", "namespace", - "plugin", - "action", - "requestId", - "username", - "automated", - "findings" + "resource", + "policy", + "rule", + "kyvernoRule", + "result", + "message", + "process", + "source", + "observedAt" ], - "title": "Rejection", + "title": "PolicyResultRow", "type": "object" }, - "RejectionFinding": { + "PolicySummary": { "additionalProperties": false, "properties": { - "kyvernoRule": { + "check": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/PolicyCheck" }, { "type": "null" } ], - "description": "Kyverno's own rule name, for a Kyverno finding", + "description": "What a rendered policy checks, from the bundle's index.json; null for a hand-written policy", "examples": [ null - ], - "title": "Kyvernorule" - }, - "message": { - "description": "What it said, at most 300 characters", - "examples": [ - "must match ^[a-z][a-z0-9-]{1,30}$" - ], - "title": "Message", - "type": "string" + ] }, - "path": { + "counts": { "anyOf": [ { - "type": "string" + "$ref": "#/components/schemas/PolicyCounts" }, { "type": "null" } ], - "description": "Where: `labels/`, or the file of the plan", - "examples": [ - "labels/cmapi.net/team" - ], - "title": "Path" - }, - "policy": { - "description": "The policy or check: a Kyverno policy, `metadata-keys`, a problem code, `cmapi-check`", + "description": "Its results over the clusters in scope that run it and have counts, following `clusterId`, `env` and `namespace`. Null, never zero, when no such cluster has counts: Kyverno not installed, the policy not on the cluster, the reports not readable or not listed yet", "examples": [ - "metadata-keys" - ], - "title": "Policy", - "type": "string" + null + ] }, - "rule": { + "description": { "anyOf": [ { "type": "string" @@ -8358,232 +8215,245 @@ "type": "null" } ], - "description": "The rule: the error's code for cmapi, index.json's rule of a rendered policy", + "description": "`policies.kyverno.io/description`", "examples": [ - "invalid_value" + "The labels and annotations that metadata-keys.yaml requires" ], - "title": "Rule" + "title": "Description" }, - "severity": { - "description": "`error` refused; `warning` reported only (audit)", - "enum": [ - "error", - "warning" - ], + "environments": { + "description": "The environments in scope whose bundle has it", "examples": [ - "error" + [ + "dev" + ] ], - "title": "Severity", - "type": "string" + "items": { + "type": "string" + }, + "title": "Environments", + "type": "array" }, - "source": { - "description": "`cmapi` (its own checks), `kyverno`, `kubeconform`, or `ci` (the Git host's CI)", + "generated": { + "description": "True for a policy that cmapi renders from its configuration", "examples": [ - "cmapi" + true ], - "title": "Source", + "title": "Generated", + "type": "boolean" + }, + "kind": { + "description": "Its kind", + "examples": [ + "ValidatingPolicy" + ], + "title": "Kind", + "type": "string" + }, + "name": { + "description": "The policy's name, from the bundle", + "examples": [ + "cmapi-metadata-dev-label-cmapi-net-team-pattern" + ], + "title": "Name", "type": "string" } }, "required": [ - "source", - "policy", - "rule", - "kyvernoRule", - "path", - "severity", - "message" + "name", + "kind", + "description", + "check", + "environments", + "generated", + "counts" ], - "title": "RejectionFinding", + "title": "PolicySummary", "type": "object" }, - "RejectionPage": { + "PrView": { "additionalProperties": false, "properties": { - "from": { - "description": "The start of the window", + "branch": { + "description": "Bot branch", "examples": [ - "2026-11-10T18:02:11Z" + "cmapi/CRC/req-20261105-0001" ], - "format": "date-time", - "title": "From", + "title": "Branch", "type": "string" }, - "items": { - "description": "One page, newest first", - "items": { - "$ref": "#/components/schemas/Rejection" - }, - "title": "Items", - "type": "array" - }, - "letters": { - "additionalProperties": { - "type": "integer" - }, - "description": "Rows per first letter of the namespace", + "head": { + "description": "PR head commit", "examples": [ - { - "C": 1 - } + "0a1b2c3d" ], - "title": "Letters", - "type": "object" - }, - "page": { - "$ref": "#/components/schemas/PageInfo", - "description": "Paging" + "title": "Head", + "type": "string" }, - "since": { - "description": "The window asked for, in days", + "number": { + "description": "PR number", "examples": [ - "7d" + 12 ], - "title": "Since", - "type": "string" + "title": "Number", + "type": "integer" }, - "truncated": { - "description": "True when the window holds more than the 10,000 newest rows that one list reads", + "url": { + "description": "PR URL", "examples": [ - false + "https://git.example/cmapi/cluster-configs-nonprod/pulls/12" ], - "title": "Truncated", - "type": "boolean" + "title": "Url", + "type": "string" } }, "required": [ - "since", - "from", - "truncated", - "items", - "page", - "letters" + "number", + "url", + "branch", + "head" ], - "title": "RejectionPage", + "title": "PrView", "type": "object" }, - "RequestEvent": { - "additionalProperties": false, + "ProblemDetail": { + "additionalProperties": true, + "description": "RFC 9457 problem details, the one shape of every refusal.", "properties": { - "at": { - "description": "When", - "examples": [ - "2026-11-05T10:00:00Z" - ], - "format": "date-time", - "title": "At", - "type": "string" - }, - "by": { - "description": "Actor", - "examples": [ - "cmapi-bot" - ], - "title": "By", - "type": "string" - }, - "event": { - "description": "Lifecycle event or note", + "code": { + "description": "The problem code, the last segment of type", "examples": [ - "pr_opened" + "policy-violation" ], - "title": "Event", + "title": "Code", "type": "string" }, - "note": { - "default": "", - "description": "Detail", + "detail": { + "description": "What went wrong, for a person", "examples": [ - "cmapi/CRC/req-20261105-0001" + "Metadata refused" ], - "title": "Note", + "title": "Detail", "type": "string" }, - "status": { + "errors": { "anyOf": [ { - "type": "string" + "items": { + "additionalProperties": true, + "type": "object" + }, + "type": "array" }, { "type": "null" } ], - "description": "Status after the event", + "description": "One entry for each key or limit that a policy-violation refuses: `code` (reserved_key, invalid_key, invalid_value, derived_key, missing_required_key, too_many_keys or annotations_too_large) and, where they apply, `key`, `kind` (label or annotation) and `detail`, the rule in words", "examples": [ - "pr_open" + [ + { + "code": "reserved_key", + "key": "cmapi.net/tier" + } + ] ], - "title": "Status" + "title": "Errors" + }, + "status": { + "description": "HTTP status", + "examples": [ + 422 + ], + "title": "Status", + "type": "integer" + }, + "title": { + "description": "Short name of the problem", + "examples": [ + "policy violation" + ], + "title": "Title", + "type": "string" + }, + "type": { + "description": "Problem type URI", + "examples": [ + "https://cmapi.ephico2real.com/problems/policy-violation" + ], + "title": "Type", + "type": "string" } }, "required": [ - "at", - "event", + "type", + "title", "status", - "by" + "detail", + "code" ], - "title": "RequestEvent", + "title": "ProblemDetail", "type": "object" }, - "RequestEvents": { + "PruneConfirm": { "additionalProperties": false, "properties": { - "events": { - "description": "Every event, oldest first", - "items": { - "$ref": "#/components/schemas/RequestEvent" - }, - "title": "Events", - "type": "array" - }, - "requestId": { - "description": "Request ID", + "clusterId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Cluster, when the name is ambiguous", "examples": [ - "req-20261105-0001" + "CRC" ], - "title": "Requestid", - "type": "string" + "title": "Clusterid" }, - "status": { - "description": "Current state", - "enum": [ - "pending_approval", - "approved", - "pr_open", - "merged", - "awaiting_prune", - "rejected", - "synced", - "failed", - "sync_failed", - "superseded", - "cancelled", - "timeout", - "reverted", - "applied", - "merge_failed" - ], + "namespace": { + "description": "Namespace whose delete is awaiting a prune", "examples": [ - "synced" + "payments-dev" ], - "title": "Status", + "title": "Namespace", "type": "string" } }, "required": [ - "requestId", - "status", - "events" + "namespace" ], - "title": "RequestEvents", + "title": "PruneConfirm", "type": "object" }, - "RequestPage": { + "QuotaPage": { "additionalProperties": false, "properties": { - "items": { - "description": "One page of requests", + "facets": { + "additionalProperties": { + "type": "integer" + }, + "description": "Attention counts over the filters, each the count that `state` with its name lists: `quota-tight`, `near-limit` (a use of 80% or more), `oversized` (`quota-oversized` or `requests-oversized`), `idle`, `tier-outdated`, `open-request`, and `needs-attention`: the rows whose severity is 1 or more (`sort=severity`)", + "examples": [ + { + "idle": 0, + "near-limit": 0, + "needs-attention": 0, + "open-request": 0, + "oversized": 0, + "quota-tight": 0, + "tier-outdated": 0 + } + ], + "title": "Facets", + "type": "object" + }, + "items": { + "description": "One page", "items": { - "$ref": "#/components/schemas/ChangeRequest" + "$ref": "#/components/schemas/QuotaRow" }, "title": "Items", "type": "array" @@ -8592,7 +8462,7 @@ "additionalProperties": { "type": "integer" }, - "description": "Rows per first letter of the namespace", + "description": "Rows per first letter", "examples": [ { "P": 3 @@ -8609,27 +8479,16 @@ "required": [ "items", "page", - "letters" + "letters", + "facets" ], - "title": "RequestPage", + "title": "QuotaPage", "type": "object" }, - "RequesterView": { + "QuotaRow": { "additionalProperties": false, "properties": { - "automated": { - "description": "Whether a service or automation account submitted it", - "examples": [ - false - ], - "title": "Automated", - "type": "boolean" - }, - "requester": { - "$ref": "#/components/schemas/IdentityRecord", - "description": "The person or client the request is for" - }, - "submittedBy": { + "app": { "anyOf": [ { "type": "string" @@ -8638,13 +8497,42 @@ "type": "null" } ], - "description": "The caller, when it differs from the requester", + "description": "cmapi.net/app", "examples": [ null ], - "title": "Submittedby" + "title": "App" }, - "submittedByClient": { + "clusterId": { + "description": "Cluster", + "examples": [ + "CRC" + ], + "title": "Clusterid", + "type": "string" + }, + "cpu": { + "description": "[used, hard] requests.cpu", + "examples": [ + [ + "0", + "8" + ] + ], + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "title": "Cpu", + "type": "array" + }, + "env": { "anyOf": [ { "type": "string" @@ -8653,77 +8541,57 @@ "type": "null" } ], - "description": "The service client that submitted", + "description": "Environment", "examples": [ - null + "dev" ], - "title": "Submittedbyclient" - } - }, - "required": [ - "requester", - "automated" - ], - "title": "RequesterView", - "type": "object" - }, - "RoleAccess": { - "additionalProperties": false, - "properties": { - "environments": { + "title": "Env" + }, + "expiresAt": { "anyOf": [ { - "items": { - "type": "string" - }, - "type": "array" + "type": "string" }, { - "const": "all", - "type": "string" + "type": "null" } ], - "description": "Environments the role covers, or all", + "description": "cmapi.net/expires-at", "examples": [ - "all" + null ], - "title": "Environments" + "title": "Expiresat" }, - "permissions": { - "description": "Permissions the role grants", + "memory": { + "description": "[used, hard] requests.memory", "examples": [ [ - "namespaces:create", - "objects:read" + "0", + "16Gi" ] ], "items": { - "type": "string" + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] }, - "title": "Permissions", + "title": "Memory", "type": "array" }, - "role": { - "description": "A Keycloak client role in the token", + "name": { + "description": "Namespace", "examples": [ - "cmapi-requester" + "payments-dev" ], - "title": "Role", + "title": "Name", "type": "string" - } - }, - "required": [ - "role", - "permissions", - "environments" - ], - "title": "RoleAccess", - "type": "object" - }, - "SetBody": { - "additionalProperties": false, - "properties": { - "justification": { + }, + "openRequest": { "anyOf": [ { "type": "string" @@ -8732,397 +8600,292 @@ "type": "null" } ], - "description": "Why", + "description": "Request holding the namespace", "examples": [ - "A test namespace for one sprint" + null ], - "title": "Justification" + "title": "Openrequest" }, - "until": { - "description": "The expiry date: after today, and at most the environment's maxExtensionDays away", + "pods": { + "description": "[used, hard] pods", "examples": [ - "2026-12-15" + [ + "0", + "50" + ] ], - "format": "date", - "title": "Until", - "type": "string" - } - }, - "required": [ - "until" - ], - "title": "SetBody", - "type": "object" - }, - "SnapshotResource": { - "additionalProperties": false, - "properties": { - "allocatable": { + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "title": "Pods", + "type": "array" + }, + "team": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "description": "The counted nodes' `status.allocatable`", + "description": "Team", "examples": [ - 7500 + "payments" ], - "title": "Allocatable" + "title": "Team" }, - "capacity": { + "tier": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "description": "The nodes' `status.capacity`", + "description": "Tier", "examples": [ - 8000 + "small" ], - "title": "Capacity" + "title": "Tier" }, - "limits": { + "tierHash": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "description": "Live pods' limits (Thanos). Null when not measured", + "description": "Catalog hash the quota was rendered from", "examples": [ - null + "dec3e603bf8d" ], - "title": "Limits" + "title": "Tierhash" }, - "quotaCommitted": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } + "tierOutdated": { + "description": "The catalog changed since it was rendered", + "examples": [ + false ], - "description": "What cmapi's quotas committed at the snapshot (cluster row only)", + "title": "Tieroutdated", + "type": "boolean" + }, + "used": { + "description": "Highest used/hard ratio of the three", "examples": [ - 8000 + 0.0 ], - "title": "Quotacommitted" + "title": "Used", + "type": "number" }, - "requested": { + "verdict": { + "description": "The usage verdict of the latest daily sweep (docs/03, \"Verdicts\"): its worst risk, else its largest waste, else `right-sized`. `insufficient-data` when the sweep could not judge it, when no sweep has run yet, or when the instance has no usage source; `verdictReason` says which", + "enum": [ + "quota-tight", + "idle", + "quota-oversized", + "requests-oversized", + "right-sized", + "insufficient-data" + ], + "examples": [ + "insufficient-data" + ], + "title": "Verdict", + "type": "string" + }, + "verdictDay": { "anyOf": [ { - "type": "integer" + "format": "date", + "type": "string" }, { "type": "null" } ], - "description": "Live pods' requests (Thanos). Null when not measured", + "description": "The UTC day of the sweep that made the verdict; null when none did. A missed sweep leaves the previous day's verdict", "examples": [ null ], - "title": "Requested" + "title": "Verdictday" }, - "unit": { - "description": "The unit of the amounts", + "verdictKind": { + "description": "What the verdict is: `risk`, `waste`, `ok` or `info` (insufficient data)", "enum": [ - "millicores", - "bytes" + "ok", + "info", + "waste", + "risk" ], "examples": [ - "millicores" + "info" ], - "title": "Unit", + "title": "Verdictkind", "type": "string" }, - "usedAvg": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Average use over the interval (Thanos). Null when not measured", + "verdictReason": { + "description": "Why, in a sentence, with the numbers and the threshold", "examples": [ - null + "No usage source is configured on this instance (capacity.yaml usage.source is none), so there is no 14-day usage." ], - "title": "Usedavg" + "title": "Verdictreason", + "type": "string" }, - "usedPeak": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Peak use over the interval, in 5-minute steps (Thanos)", + "verdictResources": { + "description": "The resources the verdict holds for, CPU first; empty when no sweep judged the namespace", "examples": [ - null + [] ], - "title": "Usedpeak" + "items": { + "enum": [ + "cpu", + "memory" + ], + "type": "string" + }, + "title": "Verdictresources", + "type": "array" } }, "required": [ - "unit", - "capacity", - "allocatable", - "requested", - "limits", - "usedAvg", - "usedPeak", - "quotaCommitted" + "name", + "clusterId", + "env", + "team", + "tier", + "cpu", + "memory", + "pods", + "used", + "expiresAt", + "tierHash", + "tierOutdated", + "verdict", + "verdictKind", + "verdictResources", + "verdictReason", + "verdictDay" ], - "title": "SnapshotResource", + "title": "QuotaRow", "type": "object" }, - "SnapshotRun": { + "Rejection": { "additionalProperties": false, "properties": { - "clusterId": { - "description": "The cluster", + "action": { + "description": "`create`, `update`, `delete`, `expiration:extend`, `expiration:set` or `expiration:makePermanent`", "examples": [ - "CRC" + "create" ], - "title": "Clusterid", + "title": "Action", "type": "string" }, - "queued": { - "description": "True when a run was queued; false when one was already waiting", + "automated": { + "description": "A service client or an automation account", "examples": [ - true + false ], - "title": "Queued", + "title": "Automated", "type": "boolean" - } - }, - "required": [ - "clusterId", - "queued" - ], - "title": "SnapshotRun", - "type": "object" - }, - "SnapshotScope": { - "additionalProperties": false, - "properties": { - "cpu": { - "$ref": "#/components/schemas/SnapshotResource", - "description": "CPU, in millicores" }, - "memory": { - "$ref": "#/components/schemas/SnapshotResource", - "description": "Memory, in bytes" + "clusterId": { + "description": "Cluster", + "examples": [ + "CRC" + ], + "title": "Clusterid", + "type": "string" }, - "nodes": { - "additionalProperties": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ] - }, - "description": "`total`, `schedulable`, `notReady`, `memoryPressure`, `diskPressure`", + "count": { + "description": "How many times that day", "examples": [ - { - "diskPressure": 0, - "memoryPressure": 0, - "notReady": 0, - "schedulable": 1, - "total": 1 - } + 2 ], - "title": "Nodes", - "type": "object" + "title": "Count", + "type": "integer" }, - "pods": { - "additionalProperties": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ] - }, - "description": "`allocatable` and `running` (Thanos)", + "env": { + "description": "Environment", "examples": [ - { - "allocatable": 250 - } + "dev" ], - "title": "Pods", - "type": "object" + "title": "Env", + "type": "string" }, - "scope": { - "description": "`cluster`, `zone:` or `role:`", + "findings": { + "description": "Each error and warning, at most 20", + "items": { + "$ref": "#/components/schemas/RejectionFinding" + }, + "title": "Findings", + "type": "array" + }, + "firstAt": { + "description": "When it was first refused on its UTC day: the order of the list", "examples": [ - "cluster" + "2026-11-17T17:02:11Z" ], - "title": "Scope", + "format": "date-time", + "title": "Firstat", "type": "string" - } - }, - "required": [ - "scope", - "cpu", - "memory", - "pods", - "nodes" - ], - "title": "SnapshotScope", - "type": "object" - }, - "Suggestion": { - "additionalProperties": false, - "properties": { - "clusterId": { - "description": "Cluster", + }, + "id": { + "description": "`rej-`; never a request ID", "examples": [ - "CRC" + "rej-1042" ], - "title": "Clusterid", + "title": "Id", "type": "string" }, - "name": { - "description": "Namespace", + "lastAt": { + "description": "When it was last refused that day", "examples": [ - "payments-dev" + "2026-11-17T17:05:40Z" ], - "title": "Name", + "format": "date-time", + "title": "Lastat", "type": "string" }, - "why": { - "description": "Why it matched", + "namespace": { + "description": "Namespace", "examples": [ - "name starts with" + "checkout-dev" ], - "title": "Why", + "title": "Namespace", "type": "string" - } - }, - "required": [ - "name", - "clusterId", - "why" - ], - "title": "Suggestion", - "type": "object" - }, - "Suggestions": { - "additionalProperties": false, - "properties": { - "items": { - "description": "Up to ten matches", - "items": { - "$ref": "#/components/schemas/Suggestion" - }, - "title": "Items", - "type": "array" - } - }, - "required": [ - "items" - ], - "title": "Suggestions", - "type": "object" - }, - "SuppliedMetadata": { - "additionalProperties": false, - "properties": { - "annotations": { - "additionalProperties": { - "type": "string" - }, - "description": "Each annotation that the request adds, by key", - "examples": [ - {} - ], - "title": "Annotations", - "type": "object" }, - "labels": { - "additionalProperties": { - "type": "string" - }, - "description": "Each label that the request adds, by key", - "examples": [ - { - "cmapi.net/team": "payments" - } + "outcome": { + "description": "`refused`, or `warned`: Kyverno's findings on a plan that went on to a request", + "enum": [ + "refused", + "warned" ], - "title": "Labels", - "type": "object" - } - }, - "required": [ - "labels", - "annotations" - ], - "title": "SuppliedMetadata", - "type": "object" - }, - "SwitchBody": { - "additionalProperties": false, - "properties": { - "reason": { - "description": "Why the switch is being changed", "examples": [ - "incident 1234" + "refused" ], - "title": "Reason", + "title": "Outcome", "type": "string" - } - }, - "required": [ - "reason" - ], - "title": "SwitchBody", - "type": "object" - }, - "SwitchView": { - "additionalProperties": false, - "properties": { - "paused": { - "description": "Whether auto-approval is paused", - "examples": [ - false - ], - "title": "Paused", - "type": "boolean" }, - "reason": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Why", + "plugin": { + "description": "Plugin", "examples": [ - "incident 1234" + "namespaces" ], - "title": "Reason" + "title": "Plugin", + "type": "string" }, - "setAt": { + "problem": { "anyOf": [ { "type": "string" @@ -9131,13 +8894,13 @@ "type": "null" } ], - "description": "When", + "description": "The problem code of the 422 of a refused plan", "examples": [ - "2026-11-05T10:00:00+00:00" + "policy-violation" ], - "title": "Setat" + "title": "Problem" }, - "setBy": { + "requestId": { "anyOf": [ { "type": "string" @@ -9146,1081 +8909,1178 @@ "type": "null" } ], - "description": "Who set it", - "examples": [ - "opal" - ], - "title": "Setby" - } - }, - "required": [ - "paused" - ], - "title": "SwitchView", - "type": "object" - }, - "TierCatalogView": { - "additionalProperties": true, - "description": "Body of GET /tiers: the catalog as core/tiers.py describes it.", - "properties": { - "catalogHash": { - "description": "Hash of the catalog", + "description": "The request of a warned plan or a CI refusal; null for a refused plan, which never became one", "examples": [ - "dec3e603bf8d" + null ], - "title": "Cataloghash", - "type": "string" + "title": "Requestid" }, - "environments": { - "additionalProperties": true, - "description": "Per environment: tiers, custom bounds, and storageLimitRange.enabled: whether cmapi renders the storage LimitRange -limits-storage and takes limitRange.pvc.* values (off unless tiers.yaml turns it on)", - "examples": [ - { - "dev": { - "custom": {}, - "storageLimitRange": { - "enabled": false - }, - "tiers": [] - } - } + "stage": { + "description": "`plan` (the API's plan) or `ci` (the worker's checks of the pull request)", + "enum": [ + "plan", + "ci" ], - "title": "Environments", - "type": "object" - }, - "overridable": { - "description": "More keys that a custom-tier request can change: a quota key, or limitRange.... A value that differs from the tier needs the beyond-tier approval", "examples": [ - [ - "requests.storage", - "limitRange.container.max.cpu" - ] + "plan" ], - "items": { - "type": "string" - }, - "title": "Overridable", - "type": "array" + "title": "Stage", + "type": "string" }, - "sizable": { - "description": "Quota keys a request may size", + "username": { + "description": "Who asked: the username only, never the email, the employee ID or the justification", "examples": [ - [ - "requests.cpu", - "requests.memory", - "pods" - ] + "ola" ], - "items": { - "type": "string" - }, - "title": "Sizable", - "type": "array" + "title": "Username", + "type": "string" } }, "required": [ - "catalogHash", - "sizable", - "environments" + "id", + "firstAt", + "lastAt", + "count", + "stage", + "outcome", + "problem", + "clusterId", + "env", + "namespace", + "plugin", + "action", + "requestId", + "username", + "automated", + "findings" ], - "title": "TierCatalogView", + "title": "Rejection", "type": "object" }, - "UsageFigures": { + "RejectionFinding": { "additionalProperties": false, "properties": { - "avg7d": { + "kyvernoRule": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "description": "The average over the last 7 days", + "description": "Kyverno's own rule name, for a Kyverno finding", "examples": [ - 5400 + null ], - "title": "Avg7D" + "title": "Kyvernorule" }, - "newOverPeak": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ], - "description": "The planned hard limit over the 14-day peak; null without a peak", + "message": { + "description": "What it said, at most 300 characters", "examples": [ - 3.33 + "must match ^[a-z][a-z0-9-]{1,30}$" ], - "title": "Newoverpeak" + "title": "Message", + "type": "string" }, - "newQuota": { + "path": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "description": "The hard limit the change plans", + "description": "Where: `labels/`, or the file of the plan", "examples": [ - 32000 + "labels/cmapi.net/team" ], - "title": "Newquota" + "title": "Path" }, - "now": { + "policy": { + "description": "The policy or check: a Kyverno policy, `metadata-keys`, a problem code, `cmapi-check`", + "examples": [ + "metadata-keys" + ], + "title": "Policy", + "type": "string" + }, + "rule": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "description": "Usage now, in the unit of `units`; null unless `state` is ok", + "description": "The rule: the error's code for cmapi, index.json's rule of a rendered policy", "examples": [ - 6100 + "invalid_value" ], - "title": "Now" + "title": "Rule" }, - "p95": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } + "severity": { + "description": "`error` refused; `warning` reported only (audit)", + "enum": [ + "error", + "warning" ], - "description": "The 95th percentile over the last 14 days", "examples": [ - 8200 + "error" ], - "title": "P95" + "title": "Severity", + "type": "string" }, - "peak": { - "anyOf": [ - { - "type": "integer" - }, + "source": { + "description": "`cmapi` (its own checks), `kyverno`, `kubeconform`, or `ci` (the Git host's CI)", + "examples": [ + "cmapi" + ], + "title": "Source", + "type": "string" + } + }, + "required": [ + "source", + "policy", + "rule", + "kyvernoRule", + "path", + "severity", + "message" + ], + "title": "RejectionFinding", + "type": "object" + }, + "RejectionPage": { + "additionalProperties": false, + "properties": { + "from": { + "description": "The start of the window", + "examples": [ + "2026-11-10T18:02:11Z" + ], + "format": "date-time", + "title": "From", + "type": "string" + }, + "items": { + "description": "One page, newest first", + "items": { + "$ref": "#/components/schemas/Rejection" + }, + "title": "Items", + "type": "array" + }, + "letters": { + "additionalProperties": { + "type": "integer" + }, + "description": "Rows per first letter of the namespace", + "examples": [ { - "type": "null" + "C": 1 } ], - "description": "The highest 5-minute sample over the last 14 days", + "title": "Letters", + "type": "object" + }, + "page": { + "$ref": "#/components/schemas/PageInfo", + "description": "Paging" + }, + "since": { + "description": "The window asked for, in days", "examples": [ - 9600 + "7d" ], - "title": "Peak" + "title": "Since", + "type": "string" }, - "quota": { + "truncated": { + "description": "True when the window holds more than the 10,000 newest rows that one list reads", + "examples": [ + false + ], + "title": "Truncated", + "type": "boolean" + } + }, + "required": [ + "since", + "from", + "truncated", + "items", + "page", + "letters" + ], + "title": "RejectionPage", + "type": "object" + }, + "RequestEvent": { + "additionalProperties": false, + "properties": { + "at": { + "description": "When", + "examples": [ + "2026-11-05T10:00:00Z" + ], + "format": "date-time", + "title": "At", + "type": "string" + }, + "by": { + "description": "Actor", + "examples": [ + "cmapi-bot" + ], + "title": "By", + "type": "string" + }, + "event": { + "description": "Lifecycle event or note", + "examples": [ + "pr_opened" + ], + "title": "Event", + "type": "string" + }, + "note": { + "default": "", + "description": "Detail", + "examples": [ + "cmapi/CRC/req-20261105-0001" + ], + "title": "Note", + "type": "string" + }, + "status": { "anyOf": [ { - "type": "integer" + "type": "string" }, { "type": "null" } ], - "description": "The hard limit now (requests.cpu or requests.memory); null when it has none", + "description": "Status after the event", "examples": [ - 16000 + "pr_open" ], - "title": "Quota" + "title": "Status" } }, "required": [ - "now", - "avg7d", - "p95", - "peak", - "quota", - "newQuota", - "newOverPeak" + "at", + "event", + "status", + "by" ], - "title": "UsageFigures", + "title": "RequestEvent", "type": "object" }, - "Version": { + "RequestEvents": { "additionalProperties": false, "properties": { - "commit": { - "description": "Git commit the image was built from", - "examples": [ - "72d082b4c1" - ], - "title": "Commit", - "type": "string" + "events": { + "description": "Every event, oldest first", + "items": { + "$ref": "#/components/schemas/RequestEvent" + }, + "title": "Events", + "type": "array" }, - "component": { - "description": "api, worker or capacity", + "requestId": { + "description": "Request ID", "examples": [ - "api" + "req-20261105-0001" ], - "title": "Component", + "title": "Requestid", "type": "string" }, - "version": { - "description": "cmapi version", + "status": { + "description": "Current state", + "enum": [ + "pending_approval", + "approved", + "pr_open", + "merged", + "awaiting_prune", + "rejected", + "synced", + "failed", + "sync_failed", + "superseded", + "cancelled", + "timeout", + "reverted", + "applied", + "merge_failed" + ], "examples": [ - "0.2.0" + "synced" ], - "title": "Version", + "title": "Status", "type": "string" } }, "required": [ - "version", - "commit", - "component" + "requestId", + "status", + "events" ], - "title": "Version", + "title": "RequestEvents", "type": "object" - } - }, - "securitySchemes": { - "keycloak": { - "flows": { - "authorizationCode": { - "authorizationUrl": "https://keycloak.test/realms/cmapi/protocol/openid-connect/auth", - "scopes": {}, - "tokenUrl": "https://keycloak.test/realms/cmapi/protocol/openid-connect/token" - } - }, - "type": "oauth2" - } - } - }, - "info": { - "description": "The nonprod instance serves ['dev', 'rnd']. Every write is approved in cmapi, then becomes a bot pull request to cluster-configs.", - "title": "cmapi (nonprod)", - "version": "0.2.0" - }, - "openapi": "3.1.0", - "paths": { - "/api/v1/admin/auto-approval": { - "get": { - "description": "Whether the kill switch is on, who set it and why.\n\n**Requires** `requests:read`.", - "operationId": "admin_switch_state", - "responses": { - "200": { - "content": { - "application/json": { - "example": { - "paused": false, - "reason": null, - "setAt": null, - "setBy": null - }, - "schema": { - "$ref": "#/components/schemas/SwitchView" - } - } + }, + "RequestPage": { + "additionalProperties": false, + "properties": { + "items": { + "description": "One page of requests", + "items": { + "$ref": "#/components/schemas/ChangeRequest" }, - "description": "Whether the kill switch is on, with who set it, when and why." + "title": "Items", + "type": "array" }, - "401": { - "content": { - "application/problem+json": { - "examples": { - "unauthenticated": { - "value": { - "code": "unauthenticated", - "detail": "Bearer token required", - "status": 401, - "title": "unauthenticated", - "type": "https://cmapi.ephico2real.com/problems/unauthenticated" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } + "letters": { + "additionalProperties": { + "type": "integer" }, - "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." - }, - "403": { - "content": { - "application/problem+json": { - "examples": { - "forbidden": { - "value": { - "code": "forbidden", - "detail": "Missing permission requests:read: no role in your token grants it (roles: ['cmapi-requester'])", - "status": 403, - "title": "forbidden", - "type": "https://cmapi.ephico2real.com/problems/forbidden" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } + "description": "Rows per first letter of the namespace", + "examples": [ + { + "P": 3 } - }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + ], + "title": "Letters", + "type": "object" }, - "429": { - "content": { - "application/problem+json": { - "examples": { - "rate-limited": { - "value": { - "code": "rate-limited", - "detail": "Too many write calls by this caller; try again in 2 s", - "retryAfter": 2, - "status": 429, - "title": "rate limited", - "type": "https://cmapi.ephico2real.com/problems/rate-limited" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } - } - } + "page": { + "$ref": "#/components/schemas/PageInfo", + "description": "Paging" + } + }, + "required": [ + "items", + "page", + "letters" + ], + "title": "RequestPage", + "type": "object" + }, + "RequesterView": { + "additionalProperties": false, + "properties": { + "automated": { + "description": "Whether a service or automation account submitted it", + "examples": [ + false + ], + "title": "Automated", + "type": "boolean" }, - "503": { - "content": { - "application/problem+json": { - "examples": { - "idp-unavailable": { - "value": { - "code": "idp-unavailable", - "detail": "Keycloak signing keys are unreachable and this key is not cached", - "retryAfter": 30, - "status": 503, - "title": "idp unavailable", - "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } + "requester": { + "$ref": "#/components/schemas/IdentityRecord", + "description": "The person or client the request is for" + }, + "submittedBy": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" } - }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } + ], + "description": "The caller, when it differs from the requester", + "examples": [ + null + ], + "title": "Submittedby" + }, + "submittedByClient": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" } - } + ], + "description": "The service client that submitted", + "examples": [ + null + ], + "title": "Submittedbyclient" } }, - "security": [ - { - "keycloak": [] - } - ], - "summary": "Get the auto-approval switch state", - "tags": [ - "admin" - ], - "x-cmapi-permission": "requests:read", - "x-cmapi-plugin": "admin", - "x-cmapi-rate-limit": "read", - "x-codeSamples": [ - { - "label": "curl", - "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/admin/auto-approval -H \"Authorization: Bearer $TOKEN\"" - } + "required": [ + "requester", + "automated" ], - "x-plugin-version": "0.2.0" - } - }, - "/api/v1/admin/auto-approval:pause": { - "post": { - "description": "The kill switch: every request follows the normal rules until resumed. Immediate, no PR; recorded with who and why.\n\n**Requires** `approvals:pause`.", - "operationId": "admin_pause", - "requestBody": { - "content": { - "application/json": { - "example": { - "reason": "incident 1234" + "title": "RequesterView", + "type": "object" + }, + "RoleAccess": { + "additionalProperties": false, + "properties": { + "environments": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" }, - "schema": { - "$ref": "#/components/schemas/SwitchBody" + { + "const": "all", + "type": "string" } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "example": { - "paused": true, - "reason": "incident 1234", - "setAt": "2026-11-27T20:59:01.388335+00:00", - "setBy": "ada" - }, - "schema": { - "$ref": "#/components/schemas/SwitchView" - } - } - }, - "description": "The kill switch, now on, with who set it, when and why." + ], + "description": "Environments the role covers, or all", + "examples": [ + "all" + ], + "title": "Environments" }, - "400": { - "content": { - "application/problem+json": { - "examples": { - "dry-run-not-supported": { - "value": { - "code": "dry-run-not-supported", - "detail": "This call has no dry run, and nothing was done", - "status": 400, - "title": "dry run not supported", - "type": "https://cmapi.ephico2real.com/problems/dry-run-not-supported" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } + "permissions": { + "description": "Permissions the role grants", + "examples": [ + [ + "namespaces:create", + "objects:read" + ] + ], + "items": { + "type": "string" }, - "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `dry-run-not-supported`." + "title": "Permissions", + "type": "array" }, - "401": { - "content": { - "application/problem+json": { - "examples": { - "unauthenticated": { - "value": { - "code": "unauthenticated", - "detail": "Bearer token required", - "status": 401, - "title": "unauthenticated", - "type": "https://cmapi.ephico2real.com/problems/unauthenticated" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } + "role": { + "description": "A Keycloak client role in the token", + "examples": [ + "cmapi-requester" + ], + "title": "Role", + "type": "string" + } + }, + "required": [ + "role", + "permissions", + "environments" + ], + "title": "RoleAccess", + "type": "object" + }, + "SetBody": { + "additionalProperties": false, + "properties": { + "justification": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" } - }, - "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + ], + "description": "Why", + "examples": [ + "A test namespace for one sprint" + ], + "title": "Justification" }, - "403": { - "content": { - "application/problem+json": { - "examples": { - "forbidden": { - "value": { - "code": "forbidden", - "detail": "Missing permission approvals:pause: no role in your token grants it (roles: ['cmapi-requester'])", - "status": 403, - "title": "forbidden", - "type": "https://cmapi.ephico2real.com/problems/forbidden" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } + "until": { + "description": "The expiry date: after today, and at most the environment's maxExtensionDays away", + "examples": [ + "2026-12-15" + ], + "format": "date", + "title": "Until", + "type": "string" + } + }, + "required": [ + "until" + ], + "title": "SetBody", + "type": "object" + }, + "SnapshotResource": { + "additionalProperties": false, + "properties": { + "allocatable": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" } - }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + ], + "description": "The counted nodes' `status.allocatable`", + "examples": [ + 7500 + ], + "title": "Allocatable" }, - "413": { - "content": { - "application/problem+json": { - "examples": { - "content-too-large": { - "value": { - "code": "content-too-large", - "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", - "maxBytes": 1048576, - "status": 413, - "title": "content too large", - "type": "https://cmapi.ephico2real.com/problems/content-too-large" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } + "capacity": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" } - }, - "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." + ], + "description": "The nodes' `status.capacity`", + "examples": [ + 8000 + ], + "title": "Capacity" }, - "422": { - "content": { - "application/problem+json": { - "examples": { - "validation-failed": { - "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } + "limits": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" } - }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + ], + "description": "Live pods' limits (Thanos). Null when not measured", + "examples": [ + null + ], + "title": "Limits" }, - "429": { - "content": { - "application/problem+json": { - "examples": { - "rate-limited": { - "value": { - "code": "rate-limited", - "detail": "Too many write calls by this caller; try again in 2 s", - "retryAfter": 2, - "status": 429, - "title": "rate limited", - "type": "https://cmapi.ephico2real.com/problems/rate-limited" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } + "quotaCommitted": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" } - } + ], + "description": "What cmapi's quotas committed at the snapshot (cluster row only)", + "examples": [ + 8000 + ], + "title": "Quotacommitted" }, - "503": { - "content": { - "application/problem+json": { - "examples": { - "idp-unavailable": { - "value": { - "code": "idp-unavailable", - "detail": "Keycloak signing keys are unreachable and this key is not cached", - "retryAfter": 30, - "status": 503, - "title": "idp unavailable", - "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } + "requested": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" } - }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } + ], + "description": "Live pods' requests (Thanos). Null when not measured", + "examples": [ + null + ], + "title": "Requested" + }, + "unit": { + "description": "The unit of the amounts", + "enum": [ + "millicores", + "bytes" + ], + "examples": [ + "millicores" + ], + "title": "Unit", + "type": "string" + }, + "usedAvg": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" } - } + ], + "description": "Average use over the interval (Thanos). Null when not measured", + "examples": [ + null + ], + "title": "Usedavg" + }, + "usedPeak": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Peak use over the interval, in 5-minute steps (Thanos)", + "examples": [ + null + ], + "title": "Usedpeak" } }, - "security": [ - { - "keycloak": [] - } - ], - "summary": "Pause auto-approval", - "tags": [ - "admin" + "required": [ + "unit", + "capacity", + "allocatable", + "requested", + "limits", + "usedAvg", + "usedPeak", + "quotaCommitted" ], - "x-cmapi-permission": "approvals:pause", - "x-cmapi-plugin": "admin", - "x-cmapi-rate-limit": "write", - "x-codeSamples": [ - { - "label": "curl", - "lang": "Shell", - "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/admin/auto-approval:pause -H \"Authorization: Bearer $TOKEN\" -H 'Content-Type: application/json' -d '{\"reason\": \"incident 1234\"}'" + "title": "SnapshotResource", + "type": "object" + }, + "SnapshotRun": { + "additionalProperties": false, + "properties": { + "clusterId": { + "description": "The cluster", + "examples": [ + "CRC" + ], + "title": "Clusterid", + "type": "string" + }, + "queued": { + "description": "True when a run was queued; false when one was already waiting", + "examples": [ + true + ], + "title": "Queued", + "type": "boolean" } + }, + "required": [ + "clusterId", + "queued" ], - "x-plugin-version": "0.2.0" - } - }, - "/api/v1/admin/auto-approval:resume": { - "post": { - "description": "Turns the kill switch off again.\n\n**Requires** `approvals:pause`.", - "operationId": "admin_resume", - "requestBody": { - "content": { - "application/json": { - "example": { - "reason": "incident 1234 closed" - }, - "schema": { - "$ref": "#/components/schemas/SwitchBody" - } - } + "title": "SnapshotRun", + "type": "object" + }, + "SnapshotScope": { + "additionalProperties": false, + "properties": { + "cpu": { + "$ref": "#/components/schemas/SnapshotResource", + "description": "CPU, in millicores" }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "example": { - "paused": false, - "reason": "incident 1234 closed", - "setAt": "2026-11-27T20:59:01.394640+00:00", - "setBy": "ada" - }, - "schema": { - "$ref": "#/components/schemas/SwitchView" - } - } - }, - "description": "The kill switch, now off, with who set it and when." + "memory": { + "$ref": "#/components/schemas/SnapshotResource", + "description": "Memory, in bytes" }, - "400": { - "content": { - "application/problem+json": { - "examples": { - "dry-run-not-supported": { - "value": { - "code": "dry-run-not-supported", - "detail": "This call has no dry run, and nothing was done", - "status": 400, - "title": "dry run not supported", - "type": "https://cmapi.ephico2real.com/problems/dry-run-not-supported" - } - } + "nodes": { + "additionalProperties": { + "anyOf": [ + { + "type": "integer" }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" + { + "type": "null" } - } + ] }, - "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `dry-run-not-supported`." + "description": "`total`, `schedulable`, `notReady`, `memoryPressure`, `diskPressure`", + "examples": [ + { + "diskPressure": 0, + "memoryPressure": 0, + "notReady": 0, + "schedulable": 1, + "total": 1 + } + ], + "title": "Nodes", + "type": "object" }, - "401": { - "content": { - "application/problem+json": { - "examples": { - "unauthenticated": { - "value": { - "code": "unauthenticated", - "detail": "Bearer token required", - "status": 401, - "title": "unauthenticated", - "type": "https://cmapi.ephico2real.com/problems/unauthenticated" - } - } + "pods": { + "additionalProperties": { + "anyOf": [ + { + "type": "integer" }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" + { + "type": "null" } - } + ] }, - "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + "description": "`allocatable` and `running` (Thanos)", + "examples": [ + { + "allocatable": 250 + } + ], + "title": "Pods", + "type": "object" }, - "403": { - "content": { - "application/problem+json": { - "examples": { - "forbidden": { - "value": { - "code": "forbidden", - "detail": "Missing permission approvals:pause: no role in your token grants it (roles: ['cmapi-requester'])", - "status": 403, - "title": "forbidden", - "type": "https://cmapi.ephico2real.com/problems/forbidden" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + "scope": { + "description": "`cluster`, `zone:` or `role:`", + "examples": [ + "cluster" + ], + "title": "Scope", + "type": "string" + } + }, + "required": [ + "scope", + "cpu", + "memory", + "pods", + "nodes" + ], + "title": "SnapshotScope", + "type": "object" + }, + "Suggestion": { + "additionalProperties": false, + "properties": { + "clusterId": { + "description": "Cluster", + "examples": [ + "CRC" + ], + "title": "Clusterid", + "type": "string" }, - "413": { - "content": { - "application/problem+json": { - "examples": { - "content-too-large": { - "value": { - "code": "content-too-large", - "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", - "maxBytes": 1048576, - "status": 413, - "title": "content too large", - "type": "https://cmapi.ephico2real.com/problems/content-too-large" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." + "name": { + "description": "Namespace", + "examples": [ + "payments-dev" + ], + "title": "Name", + "type": "string" }, - "422": { - "content": { - "application/problem+json": { - "examples": { - "validation-failed": { - "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } + "why": { + "description": "Why it matched", + "examples": [ + "name starts with" + ], + "title": "Why", + "type": "string" + } + }, + "required": [ + "name", + "clusterId", + "why" + ], + "title": "Suggestion", + "type": "object" + }, + "Suggestions": { + "additionalProperties": false, + "properties": { + "items": { + "description": "Up to ten matches", + "items": { + "$ref": "#/components/schemas/Suggestion" }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." - }, - "429": { - "content": { - "application/problem+json": { - "examples": { - "rate-limited": { - "value": { - "code": "rate-limited", - "detail": "Too many write calls by this caller; try again in 2 s", - "retryAfter": 2, - "status": 429, - "title": "rate limited", - "type": "https://cmapi.ephico2real.com/problems/rate-limited" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } + "title": "Items", + "type": "array" + } + }, + "required": [ + "items" + ], + "title": "Suggestions", + "type": "object" + }, + "SuppliedMetadata": { + "additionalProperties": false, + "properties": { + "annotations": { + "additionalProperties": { + "type": "string" }, - "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } - } - } + "description": "Each annotation that the request adds, by key", + "examples": [ + {} + ], + "title": "Annotations", + "type": "object" }, - "503": { - "content": { - "application/problem+json": { - "examples": { - "idp-unavailable": { - "value": { - "code": "idp-unavailable", - "detail": "Keycloak signing keys are unreachable and this key is not cached", - "retryAfter": 30, - "status": 503, - "title": "idp unavailable", - "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } + "labels": { + "additionalProperties": { + "type": "string" }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } + "description": "Each label that the request adds, by key", + "examples": [ + { + "cmapi.net/team": "payments" } - } + ], + "title": "Labels", + "type": "object" } }, - "security": [ - { - "keycloak": [] - } - ], - "summary": "Resume auto-approval", - "tags": [ - "admin" + "required": [ + "labels", + "annotations" ], - "x-cmapi-permission": "approvals:pause", - "x-cmapi-plugin": "admin", - "x-cmapi-rate-limit": "write", - "x-codeSamples": [ - { - "label": "curl", - "lang": "Shell", - "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/admin/auto-approval:resume -H \"Authorization: Bearer $TOKEN\" -H 'Content-Type: application/json' -d '{\"reason\": \"incident 1234 closed\"}'" + "title": "SuppliedMetadata", + "type": "object" + }, + "SwitchBody": { + "additionalProperties": false, + "properties": { + "reason": { + "description": "Why the switch is being changed", + "examples": [ + "incident 1234" + ], + "title": "Reason", + "type": "string" } + }, + "required": [ + "reason" ], - "x-plugin-version": "0.2.0" - } - }, - "/api/v1/admin/git-log": { - "get": { - "description": "The last commits on the repository's default branch: the bot's merges.\n\n**Requires** `reports:read`.", - "operationId": "admin_git_log", - "responses": { - "200": { - "content": { - "application/json": { - "example": { - "log": [ - "80f4f1ba Merge cmapi/CRC/req-20261127-0001", - "aaaaaaaa initial" - ] - }, - "schema": { - "$ref": "#/components/schemas/GitLog" - } - } - }, - "description": "The last commits on the default branch of cluster-configs." + "title": "SwitchBody", + "type": "object" + }, + "SwitchView": { + "additionalProperties": false, + "properties": { + "paused": { + "description": "Whether auto-approval is paused", + "examples": [ + false + ], + "title": "Paused", + "type": "boolean" }, - "401": { - "content": { - "application/problem+json": { - "examples": { - "unauthenticated": { - "value": { - "code": "unauthenticated", - "detail": "Bearer token required", - "status": 401, - "title": "unauthenticated", - "type": "https://cmapi.ephico2real.com/problems/unauthenticated" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } + "reason": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" } - }, - "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + ], + "description": "Why", + "examples": [ + "incident 1234" + ], + "title": "Reason" }, - "403": { - "content": { - "application/problem+json": { - "examples": { - "forbidden": { - "value": { - "code": "forbidden", - "detail": "Missing permission reports:read: no role in your token grants it (roles: ['cmapi-requester'])", - "status": 403, - "title": "forbidden", - "type": "https://cmapi.ephico2real.com/problems/forbidden" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } + "setAt": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" } - }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + ], + "description": "When", + "examples": [ + "2026-11-05T10:00:00+00:00" + ], + "title": "Setat" }, - "429": { - "content": { - "application/problem+json": { - "examples": { - "rate-limited": { - "value": { - "code": "rate-limited", - "detail": "Too many write calls by this caller; try again in 2 s", - "retryAfter": 2, - "status": 429, - "title": "rate limited", - "type": "https://cmapi.ephico2real.com/problems/rate-limited" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } + "setBy": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" } - } + ], + "description": "Who set it", + "examples": [ + "opal" + ], + "title": "Setby" + } + }, + "required": [ + "paused" + ], + "title": "SwitchView", + "type": "object" + }, + "TierCatalogView": { + "additionalProperties": true, + "description": "Body of GET /tiers: the catalog as core/tiers.py describes it.", + "properties": { + "catalogHash": { + "description": "Hash of the catalog", + "examples": [ + "dec3e603bf8d" + ], + "title": "Cataloghash", + "type": "string" }, - "502": { - "content": { - "application/problem+json": { - "examples": { - "git-unavailable": { - "value": { - "code": "git-unavailable", - "detail": "The Git host answered 500", - "status": 502, - "title": "git unavailable", - "type": "https://cmapi.ephico2real.com/problems/git-unavailable" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" + "environments": { + "additionalProperties": true, + "description": "Per environment: tiers, custom bounds, and storageLimitRange.enabled: whether cmapi renders the storage LimitRange -limits-storage and takes limitRange.pvc.* values (off unless tiers.yaml turns it on)", + "examples": [ + { + "dev": { + "custom": {}, + "storageLimitRange": { + "enabled": false + }, + "tiers": [] } } + ], + "title": "Environments", + "type": "object" + }, + "overridable": { + "description": "More keys that a custom-tier request can change: a quota key, or limitRange.... A value that differs from the tier needs the beyond-tier approval", + "examples": [ + [ + "requests.storage", + "limitRange.container.max.cpu" + ] + ], + "items": { + "type": "string" }, - "description": "The Git host failed.\n\nCodes: `git-unavailable`." + "title": "Overridable", + "type": "array" }, - "503": { - "content": { - "application/problem+json": { - "examples": { - "idp-unavailable": { - "value": { - "code": "idp-unavailable", - "detail": "Keycloak signing keys are unreachable and this key is not cached", - "retryAfter": 30, - "status": 503, - "title": "idp unavailable", - "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } + "sizable": { + "description": "Quota keys a request may size", + "examples": [ + [ + "requests.cpu", + "requests.memory", + "pods" + ] + ], + "items": { + "type": "string" }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } - } - } + "title": "Sizable", + "type": "array" } }, - "security": [ - { - "keycloak": [] - } - ], - "summary": "List recent commits in cluster-configs", - "tags": [ - "admin" + "required": [ + "catalogHash", + "sizable", + "environments" ], - "x-cmapi-permission": "reports:read", - "x-cmapi-plugin": "admin", - "x-cmapi-rate-limit": "read", - "x-codeSamples": [ - { - "label": "curl", - "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/admin/git-log -H \"Authorization: Bearer $TOKEN\"" + "title": "TierCatalogView", + "type": "object" + }, + "UsageFigures": { + "additionalProperties": false, + "properties": { + "avg7d": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "The average over the last 7 days", + "examples": [ + 5400 + ], + "title": "Avg7D" + }, + "newOverPeak": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "description": "The planned hard limit over the 14-day peak; null without a peak", + "examples": [ + 3.33 + ], + "title": "Newoverpeak" + }, + "newQuota": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "The hard limit the change plans", + "examples": [ + 32000 + ], + "title": "Newquota" + }, + "now": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Usage now, in the unit of `units`; null unless `state` is ok", + "examples": [ + 6100 + ], + "title": "Now" + }, + "p95": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "The 95th percentile over the last 14 days", + "examples": [ + 8200 + ], + "title": "P95" + }, + "peak": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "The highest 5-minute sample over the last 14 days", + "examples": [ + 9600 + ], + "title": "Peak" + }, + "quota": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "The hard limit now (requests.cpu or requests.memory); null when it has none", + "examples": [ + 16000 + ], + "title": "Quota" } + }, + "required": [ + "now", + "avg7d", + "p95", + "peak", + "quota", + "newQuota", + "newOverPeak" ], - "x-plugin-version": "0.2.0" + "title": "UsageFigures", + "type": "object" + }, + "Version": { + "additionalProperties": false, + "properties": { + "commit": { + "description": "Git commit the image was built from", + "examples": [ + "72d082b4c1" + ], + "title": "Commit", + "type": "string" + }, + "component": { + "description": "api, worker or capacity", + "examples": [ + "api" + ], + "title": "Component", + "type": "string" + }, + "version": { + "description": "cmapi version", + "examples": [ + "0.2.0" + ], + "title": "Version", + "type": "string" + } + }, + "required": [ + "version", + "commit", + "component" + ], + "title": "Version", + "type": "object" } }, - "/api/v1/admin/integrations": { + "securitySchemes": { + "keycloak": { + "flows": { + "authorizationCode": { + "authorizationUrl": "https://keycloak.test/realms/cmapi/protocol/openid-connect/auth", + "scopes": {}, + "tokenUrl": "https://keycloak.test/realms/cmapi/protocol/openid-connect/token" + } + }, + "type": "oauth2" + } + } + }, + "info": { + "description": "The nonprod instance serves ['dev', 'rnd']. Every write is approved in cmapi, then becomes a bot pull request to cluster-configs.", + "title": "cmapi (nonprod)", + "version": "0.2.0" + }, + "openapi": "3.1.0", + "paths": { + "/api/v1/admin/auto-approval": { "get": { - "description": "Each integration's mode (delivery, sync signal, operations engine, event publisher, policy engine) and the import\nstatus per cluster.\n\n**Requires** `clusters:read`.", - "operationId": "admin_integrations", + "description": "Whether the kill switch is on, who set it and why.\n\n**Requires** `requests:read`.", + "operationId": "admin_switch_state", "responses": { "200": { "content": { "application/json": { "example": { - "clusters": { - "CRC": "connected" - }, - "delivery": { - "mode": "apply", - "pollSeconds": 1, - "syncTimeoutSeconds": 30 - }, - "events": { - "publisher": "none" - }, - "operations": { - "engine": "builtin" - }, - "policy": { - "engine": "kyverno", - "environments": { - "dev": "audit", - "rnd": "audit" - }, - "kyvernoVersion": null - }, - "syncSignal": { - "default": "poll", - "pollInterval": "1s" - } + "paused": false, + "reason": null, + "setAt": null, + "setBy": null }, "schema": { - "$ref": "#/components/schemas/Integrations" + "$ref": "#/components/schemas/SwitchView" } } }, - "description": "Each integration's mode and health, and the import status of each cluster." + "description": "Whether the kill switch is on, with who set it, when and why." }, "401": { "content": { @@ -10250,7 +10110,7 @@ "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission clusters:read: no role in your token grants it (roles: ['cmapi-requester'])", + "detail": "Missing permission requests:read: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -10334,136 +10194,77 @@ "keycloak": [] } ], - "summary": "Get integration modes and health", + "summary": "Get the auto-approval switch state", "tags": [ "admin" ], - "x-cmapi-permission": "clusters:read", + "x-cmapi-permission": "requests:read", "x-cmapi-plugin": "admin", "x-cmapi-rate-limit": "read", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/admin/integrations -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/admin/auto-approval -H \"Authorization: Bearer $TOKEN\"" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/admin/kpi": { - "get": { - "description": "The KPIs tab's data: each component's cgroup memory and CPU against its limit, the database figures,\nand the KPI rows cmapi computes from its own tables. A figure that cannot be measured reads unavailable, never 0.\n\n**Requires** `reports:read`.", - "operationId": "admin_kpi", + "/api/v1/admin/auto-approval:pause": { + "post": { + "description": "The kill switch: every request follows the normal rules until resumed. Immediate, no PR; recorded with who and why.\n\n**Requires** `approvals:pause`.", + "operationId": "admin_pause", + "requestBody": { + "content": { + "application/json": { + "example": { + "reason": "incident 1234" + }, + "schema": { + "$ref": "#/components/schemas/SwitchBody" + } + } + }, + "required": true + }, "responses": { "200": { "content": { "application/json": { "example": { - "components": [ - { - "component": "api", - "cpuLimitCores": null, - "cpuPeriods": null, - "cpuThrottledPeriods": null, - "cpuThrottledSeconds": null, - "cpuUsageSeconds": null, - "measuredAt": 1795813135.55039, - "memoryBytes": null, - "memoryLimitBytes": null - } - ], - "database": { - "connections": 9, - "connectionsMax": 100, - "oldestTransactionSeconds": 0.0, - "poolInUse": 0, - "poolSize": 5, - "sizeBytes": 10173463, - "walBytes": 83886080 - }, - "instance": "nonprod", - "kpis": [ - { - "id": "lead-time-auto-p90", - "name": "Lead time, auto-approved (p90)", - "source": "database: submit to synced, requests that a policy approved", - "target": "under 10 min", - "targetStatus": "proposed", - "unit": "seconds", - "value": 0.332343 - }, - { - "id": "lead-time-approved-p90", - "name": "Lead time, with approval (p90)", - "source": "database: submit to synced, requests that people approved", - "target": "under 1 business day", - "targetStatus": "proposed", - "unit": "seconds", - "value": null - }, - { - "id": "approval-turnaround-p50", - "name": "Approval turnaround (p50)", - "source": "database: submit to approved, requests that people approved", - "target": "4 h", - "targetStatus": "proposed", - "unit": "seconds", - "value": null - }, - { - "id": "approval-turnaround-p90", - "name": "Approval turnaround (p90)", - "source": "database: submit to approved, requests that people approved", - "target": "24 h", - "targetStatus": "proposed", - "unit": "seconds", - "value": null - }, - { - "id": "auto-approval-rate", - "name": "Auto-approval rate", - "source": "database: requests that a policy approved over requests that matched a policy", - "target": "tracked", - "targetStatus": "proposed", - "unit": "ratio", - "value": 1.0 - }, - { - "id": "self-service-rate", - "name": "Self-service rate", - "source": "database: synced requests with no approval that counted for approver-platform, over synced requests", - "target": "over 80%", - "targetStatus": "proposed", - "unit": "ratio", - "value": 1.0 - }, - { - "id": "change-failure-rate", - "name": "Change failure rate", - "source": "database: failed, sync_failed or reverted requests over merged requests", - "target": "under 5%", - "targetStatus": "proposed", - "unit": "ratio", - "value": 0.0 + "paused": true, + "reason": "incident 1234", + "setAt": "2026-12-01T15:13:07.995528+00:00", + "setBy": "ada" + }, + "schema": { + "$ref": "#/components/schemas/SwitchView" + } + } + }, + "description": "The kill switch, now on, with who set it, when and why." + }, + "400": { + "content": { + "application/problem+json": { + "examples": { + "dry-run-not-supported": { + "value": { + "code": "dry-run-not-supported", + "detail": "This call has no dry run, and nothing was done", + "status": 400, + "title": "dry run not supported", + "type": "https://cmapi.ephico2real.com/problems/dry-run-not-supported" } - ], - "thresholds": { - "backupMaxAgeHours": 26.0, - "cpuPercent": 80.0, - "dbConnectionsPercent": 80.0, - "dbVolumePercent": 80.0, - "memoryPercent": 80.0, - "throttledPercent": 1.0 - }, - "unavailable": "a null value means not measured, never zero" + } }, "schema": { - "$ref": "#/components/schemas/KpiView" + "$ref": "#/components/schemas/ProblemDetail" } } }, - "description": "Each component's memory and CPU against its limit, the database figures and the KPI rows; a figure not measured reads unavailable." + "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `dry-run-not-supported`." }, "401": { "content": { @@ -10493,7 +10294,7 @@ "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission reports:read: no role in your token grants it (roles: ['cmapi-requester'])", + "detail": "Missing permission approvals:pause: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -10507,6 +10308,49 @@ }, "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." }, + "413": { + "content": { + "application/problem+json": { + "examples": { + "content-too-large": { + "value": { + "code": "content-too-large", + "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", + "maxBytes": 1048576, + "status": 413, + "title": "content too large", + "type": "https://cmapi.ephico2real.com/problems/content-too-large" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + }, "429": { "content": { "application/problem+json": { @@ -10577,120 +10421,77 @@ "keycloak": [] } ], - "summary": "Get system KPIs", + "summary": "Pause auto-approval", "tags": [ "admin" ], - "x-cmapi-permission": "reports:read", + "x-cmapi-permission": "approvals:pause", "x-cmapi-plugin": "admin", - "x-cmapi-rate-limit": "read", + "x-cmapi-rate-limit": "write", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/admin/kpi -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/admin/auto-approval:pause -H \"Authorization: Bearer $TOKEN\" -H 'Content-Type: application/json' -d '{\"reason\": \"incident 1234\"}'" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/admin/plugins": { - "get": { - "description": "Each part of the API with its version, and what `plugins.yaml` says for this instance: whether a plugin is\nenabled, and the environments where an override stops its writes. A plugin that is not enabled has no route and\nis not in this document.\n\n**Requires** `clusters:read`.", - "operationId": "admin_plugins", + "/api/v1/admin/auto-approval:resume": { + "post": { + "description": "Turns the kill switch off again.\n\n**Requires** `approvals:pause`.", + "operationId": "admin_resume", + "requestBody": { + "content": { + "application/json": { + "example": { + "reason": "incident 1234 closed" + }, + "schema": { + "$ref": "#/components/schemas/SwitchBody" + } + } + }, + "required": true + }, "responses": { "200": { "content": { "application/json": { "example": { - "configured": false, - "instance": "nonprod", - "items": [ - { - "core": true, - "disabledEnvironments": [], - "enabled": true, - "name": "admin", - "version": "0.2.0" - }, - { - "core": true, - "disabledEnvironments": [], - "enabled": true, - "name": "core", - "version": "0.2.0" - }, - { - "core": true, - "disabledEnvironments": [], - "enabled": true, - "name": "requests", - "version": "0.2.0" - }, - { - "core": false, - "disabledEnvironments": [], - "enabled": true, - "name": "adoption", - "version": "0.2.0" - }, - { - "core": false, - "disabledEnvironments": [], - "enabled": true, - "name": "capacity", - "version": "0.2.0" - }, - { - "core": false, - "disabledEnvironments": [], - "enabled": true, - "name": "directory", - "version": "0.2.0" - }, - { - "core": false, - "disabledEnvironments": [], - "enabled": true, - "name": "expiration", - "version": "0.2.0" - }, - { - "core": false, - "disabledEnvironments": [], - "enabled": true, - "name": "namespaces", - "version": "0.2.0" - }, - { - "core": false, - "disabledEnvironments": [], - "enabled": true, - "name": "policies", - "version": "0.2.0" - }, - { - "core": false, - "disabledEnvironments": [], - "enabled": true, - "name": "quotas", - "version": "0.2.0" - }, - { - "core": false, - "disabledEnvironments": [], - "enabled": true, - "name": "tiers", - "version": "0.2.0" + "paused": false, + "reason": "incident 1234 closed", + "setAt": "2026-12-01T15:13:07.918684+00:00", + "setBy": "ada" + }, + "schema": { + "$ref": "#/components/schemas/SwitchView" + } + } + }, + "description": "The kill switch, now off, with who set it and when." + }, + "400": { + "content": { + "application/problem+json": { + "examples": { + "dry-run-not-supported": { + "value": { + "code": "dry-run-not-supported", + "detail": "This call has no dry run, and nothing was done", + "status": 400, + "title": "dry run not supported", + "type": "https://cmapi.ephico2real.com/problems/dry-run-not-supported" } - ] + } }, "schema": { - "$ref": "#/components/schemas/PluginList" + "$ref": "#/components/schemas/ProblemDetail" } } }, - "description": "Each plugin with its version, whether plugins.yaml enables it, and where an override stops its writes." + "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `dry-run-not-supported`." }, "401": { "content": { @@ -10720,7 +10521,7 @@ "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission clusters:read: no role in your token grants it (roles: ['cmapi-requester'])", + "detail": "Missing permission approvals:pause: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -10734,6 +10535,49 @@ }, "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." }, + "413": { + "content": { + "application/problem+json": { + "examples": { + "content-too-large": { + "value": { + "code": "content-too-large", + "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", + "maxBytes": 1048576, + "status": 413, + "title": "content too large", + "type": "https://cmapi.ephico2real.com/problems/content-too-large" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + }, "429": { "content": { "application/problem+json": { @@ -10804,235 +10648,76 @@ "keycloak": [] } ], - "summary": "List this instance's plugins", + "summary": "Resume auto-approval", "tags": [ "admin" ], - "x-cmapi-permission": "clusters:read", + "x-cmapi-permission": "approvals:pause", "x-cmapi-plugin": "admin", - "x-cmapi-rate-limit": "read", + "x-cmapi-rate-limit": "write", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/admin/plugins -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/admin/auto-approval:resume -H \"Authorization: Bearer $TOKEN\" -H 'Content-Type: application/json' -d '{\"reason\": \"incident 1234 closed\"}'" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/admin/prune:confirm": { - "post": { - "description": "An operator confirms that a merged delete may remove the namespace. In `argocd` delivery the\nconfirmation happens in Argo CD and the worker observes it; in `apply` delivery this call is the\nconfirmation and the worker's delivery job removes the namespace. In `gitops` delivery the deliverer\nremoves it, and a read of its absence ends the request: this call only makes the worker read again.\n\n**Requires** `operations:run`.", - "operationId": "admin_prune_confirm", - "requestBody": { - "content": { - "application/json": { - "example": { - "clusterId": "CRC", - "namespace": "search-dev" - }, - "schema": { - "$ref": "#/components/schemas/PruneConfirm" - } - } - }, - "required": true - }, + "/api/v1/admin/git-log": { + "get": { + "description": "The last commits on the repository's default branch: the bot's merges.\n\n**Requires** `reports:read`.", + "operationId": "admin_git_log", "responses": { "200": { "content": { "application/json": { "example": { - "action": "delete", - "approval": { - "approvals": [ - { - "at": "2026-11-27T20:59:06.043703Z", - "comment": "", - "relayedBy": null, - "sub": "sub-amy", - "username": "amy" - } - ], - "auto": null, - "autoFallback": null, - "reasons": [ - "dev delete: 1 from approver-platform" - ], - "remaining": [], - "rule": "dev-delete", - "selfApproval": true, - "slots": [ - { - "count": 1, - "group": "approver-platform", - "reason": "dev delete: 1 from approver-platform" - } - ], - "timeoutHours": 8 - }, - "baseSha": "479aab8dca85cfbd40e9c4c4b791535b8a69d428", - "beyondTier": null, - "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:05.959028Z", - "env": "dev", - "events": [ - { - "at": "2026-11-27T20:59:05.969036Z", - "by": "ola", - "event": "plan_needs_approval", - "note": "waiting for [('approver-platform', 1)]", - "status": "pending_approval" - }, - { - "at": "2026-11-27T20:59:06.061082Z", - "by": "amy", - "event": "approval", - "note": "", - "status": "pending_approval" - }, - { - "at": "2026-11-27T20:59:06.073368Z", - "by": "amy", - "event": "approved", - "note": "approval count met", - "status": "approved" - }, - { - "at": "2026-11-27T20:59:06.208729Z", - "by": "cmapi-bot", - "event": "branch_pushed", - "note": "cmapi/CRC/req-20261127-0008 at a539f2ec on 479aab8d (created)", - "status": "approved" - }, - { - "at": "2026-11-27T20:59:06.335675Z", - "by": "cmapi-bot", - "event": "pr_opened", - "note": "cmapi/CRC/req-20261127-0008 #7", - "status": "pr_open" - }, - { - "at": "2026-11-27T20:59:06.426044Z", - "by": "ci", - "event": "ci", - "note": "kubeconform: pass; kyverno: pass; cmapi check: pass", - "status": "pr_open" - }, - { - "at": "2026-11-27T20:59:06.516666Z", - "by": "worker", - "event": "merge_verified", - "note": "merged a539f2ec; the folder at it is the plan's", - "status": "pr_open" - }, - { - "at": "2026-11-27T20:59:06.526607Z", - "by": "cmapi-bot", - "event": "merged", - "note": "merged a539f2ec", - "status": "merged" - }, - { - "at": "2026-11-27T20:59:06.642678Z", - "by": "cmapi-deliverer", - "event": "prune_pending", - "note": "Prune=confirm: waiting for an operator to confirm the prune", - "status": "awaiting_prune" - }, - { - "at": "2026-11-27T20:59:07.179743Z", - "by": "opal", - "event": "prune_confirm", - "note": "operator confirmed the prune", - "status": "awaiting_prune" - } - ], - "files": { - "clusters/CRC/namespaces/search-dev/limitrange-search-dev-limits-cpu.yaml": "removed", - "clusters/CRC/namespaces/search-dev/limitrange-search-dev-limits-memory.yaml": "removed", - "clusters/CRC/namespaces/search-dev/namespace.yaml": "removed", - "clusters/CRC/namespaces/search-dev/resourcequota-search-dev-quota.yaml": "removed", - "clusters/CRC/namespaces/search-dev/token-issuer-rolebinding.yaml": "removed" - }, - "instance": "nonprod", - "justification": null, - "links": { - "events": "/api/v1/requests/req-20261127-0008/events", - "pr": "https://git.test/pulls/7", - "self": "/api/v1/requests/req-20261127-0008" - }, - "mergeSha": "a539f2ec", - "namespace": "search-dev", - "planHash": "c490196334dad591c3196aa59224d119861392145360aee1d428c93109235dbe", - "plugin": "namespaces", - "pr": { - "branch": "cmapi/CRC/req-20261127-0008", - "head": "a539f2ec", - "number": 7, - "url": "https://git.test/pulls/7" - }, - "reason": null, - "requestId": "req-20261127-0008", - "requester": { - "automated": false, - "requester": { - "clientId": "cmapi-portal", - "email": "ola@ephico2real.com", - "employeeId": "1001", - "familyName": "Doe", - "givenName": "Ola", - "kind": "user", - "middleName": null, - "sub": "sub-ola", - "username": "ola" - }, - "submittedBy": null, - "submittedByClient": null - }, - "status": "awaiting_prune", - "updatedAt": "2026-11-27T20:59:07.078985Z" + "log": [ + "513f40b0 Merge cmapi/CRC/req-20261201-0001", + "aaaaaaaa initial" + ] }, "schema": { - "$ref": "#/components/schemas/ChangeRequest" + "$ref": "#/components/schemas/GitLog" } } }, - "description": "The delete request, with the prune confirmed." + "description": "The last commits on the default branch of cluster-configs." }, - "400": { + "401": { "content": { "application/problem+json": { "examples": { - "dry-run-not-supported": { + "unauthenticated": { "value": { - "code": "dry-run-not-supported", - "detail": "This call has no dry run, and nothing was done", - "status": 400, - "title": "dry run not supported", - "type": "https://cmapi.ephico2real.com/problems/dry-run-not-supported" - } - } + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + } + } }, "schema": { "$ref": "#/components/schemas/ProblemDetail" } } }, - "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `dry-run-not-supported`." + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." }, - "401": { + "403": { "content": { "application/problem+json": { "examples": { - "unauthenticated": { + "forbidden": { "value": { - "code": "unauthenticated", - "detail": "Bearer token required", - "status": 401, - "title": "unauthenticated", - "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + "code": "forbidden", + "detail": "Missing permission reports:read: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" } } }, @@ -11041,28 +10726,51 @@ } } }, - "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." }, - "403": { + "429": { "content": { "application/problem+json": { "examples": { - "environment-forbidden": { + "rate-limited": { "value": { - "code": "environment-forbidden", - "detail": "Your roles grant operations:run only in ['rnd'], not dev", - "status": 403, - "title": "environment forbidden", - "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" + "code": "rate-limited", + "detail": "Too many write calls by this caller; try again in 2 s", + "retryAfter": 2, + "status": 429, + "title": "rate limited", + "type": "https://cmapi.ephico2real.com/problems/rate-limited" } - }, - "forbidden": { + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + }, + "502": { + "content": { + "application/problem+json": { + "examples": { + "git-unavailable": { "value": { - "code": "forbidden", - "detail": "Missing permission operations:run: no role in your token grants it (roles: ['cmapi-requester'])", - "status": 403, - "title": "forbidden", - "type": "https://cmapi.ephico2real.com/problems/forbidden" + "code": "git-unavailable", + "detail": "The Git host answered 500", + "status": 502, + "title": "git unavailable", + "type": "https://cmapi.ephico2real.com/problems/git-unavailable" } } }, @@ -11071,19 +10779,20 @@ } } }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`, `environment-forbidden`." + "description": "The Git host failed.\n\nCodes: `git-unavailable`." }, - "409": { + "503": { "content": { "application/problem+json": { "examples": { - "nothing-to-prune": { + "idp-unavailable": { "value": { - "code": "nothing-to-prune", - "detail": "No delete of payments-dev is awaiting a prune", - "status": 409, - "title": "nothing to prune", - "type": "https://cmapi.ephico2real.com/problems/nothing-to-prune" + "code": "idp-unavailable", + "detail": "Keycloak signing keys are unreachable and this key is not cached", + "retryAfter": 30, + "status": 503, + "title": "idp unavailable", + "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" } } }, @@ -11092,20 +10801,95 @@ } } }, - "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `nothing-to-prune`." + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + } + }, + "security": [ + { + "keycloak": [] + } + ], + "summary": "List recent commits in cluster-configs", + "tags": [ + "admin" + ], + "x-cmapi-permission": "reports:read", + "x-cmapi-plugin": "admin", + "x-cmapi-rate-limit": "read", + "x-codeSamples": [ + { + "label": "curl", + "lang": "Shell", + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/admin/git-log -H \"Authorization: Bearer $TOKEN\"" + } + ], + "x-plugin-version": "0.2.0" + } + }, + "/api/v1/admin/integrations": { + "get": { + "description": "Each integration's mode (delivery, sync signal, operations engine, event publisher, policy engine) and the import\nstatus per cluster.\n\n**Requires** `clusters:read`.", + "operationId": "admin_integrations", + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "clusters": { + "CRC": "connected" + }, + "delivery": { + "mode": "apply", + "pollSeconds": 1, + "syncTimeoutSeconds": 30 + }, + "events": { + "publisher": "none" + }, + "operations": { + "engine": "builtin" + }, + "policy": { + "engine": "kyverno", + "environments": { + "dev": "audit", + "rnd": "audit" + }, + "kyvernoVersion": null + }, + "syncSignal": { + "default": "poll", + "pollInterval": "1s" + } + }, + "schema": { + "$ref": "#/components/schemas/Integrations" + } + } + }, + "description": "Each integration's mode and health, and the import status of each cluster." }, - "413": { + "401": { "content": { "application/problem+json": { "examples": { - "content-too-large": { + "unauthenticated": { "value": { - "code": "content-too-large", - "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", - "maxBytes": 1048576, - "status": 413, - "title": "content too large", - "type": "https://cmapi.ephico2real.com/problems/content-too-large" + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" } } }, @@ -11114,19 +10898,19 @@ } } }, - "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." }, - "422": { + "403": { "content": { "application/problem+json": { "examples": { - "validation-failed": { + "forbidden": { "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" + "code": "forbidden", + "detail": "Missing permission clusters:read: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" } } }, @@ -11135,7 +10919,7 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." }, "429": { "content": { @@ -11207,378 +10991,148 @@ "keycloak": [] } ], - "summary": "Confirm the prune of a deleted namespace", + "summary": "Get integration modes and health", "tags": [ "admin" ], - "x-cmapi-permission": "operations:run", + "x-cmapi-permission": "clusters:read", "x-cmapi-plugin": "admin", - "x-cmapi-rate-limit": "write", + "x-cmapi-rate-limit": "read", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/admin/prune:confirm -H \"Authorization: Bearer $TOKEN\" -H 'Content-Type: application/json' -d '{\"clusterId\": \"CRC\", \"namespace\": \"search-dev\"}'" + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/admin/integrations -H \"Authorization: Bearer $TOKEN\"" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/capacity": { + "/api/v1/admin/kpi": { "get": { - "description": "Each cluster of the environments where the caller holds capacity:read: what cmapi's ResourceQuotas commit against the\ncluster's size times the environment's overcommit, with the size's basis (`simulated` from clusters.yaml, or the nodes'\n`allocatable`), the nodes, the zones and a named state. Then the groups by `groupBy`, whose figures are recomputed from the\nincluded clusters: summed commitments, headroom floored at 0 per cluster, and the largest single placement.\n\nRead from each cluster's watch, never from the cluster at request time. A figure that is not known is null, never 0. The\nanswer carries a strong ETag; If-None-Match answers 304, and an If-Match that does not list it answers 412.\n\n**Requires** `capacity:read`.", - "operationId": "capacity_capacity", - "parameters": [ - { - "description": "The keys of the groups, comma-separated, 1 to 3 of `environment`, `region` and `label:` (a clusters.yaml label). Another value returns 422 `validation-failed`.", - "in": "query", - "name": "groupBy", - "required": false, - "schema": { - "default": "region,environment", - "description": "The keys of the groups, comma-separated, 1 to 3 of `environment`, `region` and `label:` (a clusters.yaml label). Another value returns 422 `validation-failed`.", - "examples": [ - "region,environment" - ], - "title": "Groupby", - "type": "string" - } - }, - { - "description": "Only the clusters of this environment. One the instance does not serve returns 422 `environment-not-served`; one where the caller lacks capacity:read returns 403 `environment-forbidden`.", - "in": "query", - "name": "env", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Only the clusters of this environment. One the instance does not serve returns 422 `environment-not-served`; one where the caller lacks capacity:read returns 403 `environment-forbidden`.", - "examples": [ - "dev" - ], - "title": "Env" - } - }, - { - "description": "Only this cluster. One that is not in the caller's scope returns 404 `cluster-not-found`, as an unknown one does.", - "in": "query", - "name": "clusterId", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Only this cluster. One that is not in the caller's scope returns 404 `cluster-not-found`, as an unknown one does.", - "examples": [ - "CRC" - ], - "title": "Clusterid" - } - }, - { - "description": "The ETag of the answer the caller holds. If it is still the current one, the answer is 304 with no body.", - "in": "header", - "name": "If-None-Match", - "required": false, - "schema": { - "examples": [ - "\"1f774baf9bf093f8d4ebc497eb0d5b96\"" - ], - "type": "string" - } - }, - { - "description": "Optional on a read. The answer is sent only if one strong tag listed here is its current ETag, or if the value is `*`; otherwise it is 412 `precondition-failed`, with the current tag in `etag`. A weak tag (`W/\"...\"`) never matches. If-Match is read before If-None-Match (RFC 9110, section 13.2.2). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line.", - "in": "header", - "name": "If-Match", - "required": false, - "schema": { - "examples": [ - "\"1f774baf9bf093f8d4ebc497eb0d5b96\"" - ], - "type": "string" - } - } - ], + "description": "The KPIs tab's data: each component's cgroup memory and CPU against its limit, the database figures,\nand the KPI rows cmapi computes from its own tables. A figure that cannot be measured reads unavailable, never 0.\n\n**Requires** `reports:read`.", + "operationId": "admin_kpi", "responses": { "200": { "content": { "application/json": { "example": { - "clusters": [ + "components": [ { - "asOf": "2026-11-27T20:59:00Z", - "basis": "simulated", - "boundBy": "cpu", - "clusterId": "CRC", - "cpu": { - "allocatable": 7800, - "commitment": 0.375, - "committed": 48000, - "headroom": 80000, - "limit": 128000, - "overcommit": 2.0, - "quotaUsed": 0, - "quotaUsedMissing": 0, - "requested": null, - "simulated": 64000, - "status": "ok", - "unit": "millicores", - "usedAvg": null, - "usedPeak": null - }, - "env": "dev", - "history": null, - "managedNamespaces": 3, - "memory": { - "allocatable": 20493357056, - "commitment": 0.3, - "committed": 103079215104, - "headroom": 240518168576, - "limit": 343597383680, - "overcommit": 1.25, - "quotaUsed": 0, - "quotaUsedMissing": 0, - "requested": null, - "simulated": 274877906944, - "status": "ok", - "unit": "bytes", - "usedAvg": null, - "usedPeak": null - }, - "nodes": { - "cordoned": 0, - "counted": 1, - "notReady": 0, - "tainted": 0, - "total": 1 - }, - "nodesDetail": null, - "nodesState": "ok", - "region": "us-central", - "scopedQuotas": 0, - "snapshot": { - "detail": "no snapshot yet", - "source": null, - "state": "none", - "takenAt": null - }, - "state": "ok", - "stateDetail": null, - "status": "ok", - "writes": true, - "zones": [] + "component": "api", + "cpuLimitCores": null, + "cpuPeriods": null, + "cpuThrottledPeriods": null, + "cpuThrottledSeconds": null, + "cpuUsageSeconds": null, + "measuredAt": 1796137976.883476, + "memoryBytes": null, + "memoryLimitBytes": null } ], - "groupBy": [ - "region", - "environment" - ], - "groups": [ + "database": { + "connections": 13, + "connectionsMax": 100, + "oldestTransactionSeconds": 0.0, + "poolInUse": 0, + "poolSize": 5, + "sizeBytes": 9018391, + "walBytes": 83886080 + }, + "instance": "nonprod", + "kpis": [ { - "boundBy": "cpu", - "clusterIds": [ - "CRC" - ], - "coverage": 1.0, - "cpu": { - "commitment": 0.375, - "committed": 48000, - "headroom": 80000, - "largestPlacement": { - "clusterId": "CRC", - "value": 80000 - }, - "limit": 128000, - "unit": "millicores" - }, - "excluded": [], - "included": 1, - "key": { - "environment": "dev", - "region": "us-central" - }, - "matching": 1, - "memory": { - "commitment": 0.3, - "committed": 103079215104, - "headroom": 240518168576, - "largestPlacement": { - "clusterId": "CRC", - "value": 240518168576 - }, - "limit": 343597383680, - "unit": "bytes" - }, - "name": "us-central \u00b7 dev", - "status": "ok", - "statusCounts": { - "critical": 0, - "ok": 1, - "over": 0, - "warn": 0 - } - } - ], - "hiddenClusters": 0, - "notMeasured": [ - "requested", - "usedAvg", - "usedPeak", - "history" - ], - "snapshotIntervalSeconds": 1800, - "snapshotState": "stored", - "source": "live", - "staleAfterSeconds": 3600, - "targets": [ + "id": "lead-time-auto-p90", + "name": "Lead time, auto-approved (p90)", + "source": "database: submit to synced, requests that a policy approved", + "target": "under 10 min", + "targetStatus": "proposed", + "unit": "seconds", + "value": 0.27096 + }, { - "commitment": { - "critical": 0.95, - "warn": 0.85 - }, - "env": "dev", - "overcommit": { - "cpu": 2.0, - "memory": 1.25 - }, - "overcommitDefault": false + "id": "lead-time-approved-p90", + "name": "Lead time, with approval (p90)", + "source": "database: submit to synced, requests that people approved", + "target": "under 1 business day", + "targetStatus": "proposed", + "unit": "seconds", + "value": null }, { - "commitment": { - "critical": 0.95, - "warn": 0.85 - }, - "env": "rnd", - "overcommit": { - "cpu": 2.0, - "memory": 1.25 - }, - "overcommitDefault": false - } - ] - }, - "schema": { - "$ref": "#/components/schemas/CapacityPage" - } - } - }, - "description": "The capacity of each cluster in the caller's environments, grouped as asked, with each cluster's targets and snapshot state.", - "headers": { - "ETag": { - "description": "The strong ETag of this answer, to send back in If-None-Match.", - "schema": { - "type": "string" - } - } - } - }, - "304": { - "description": "Not modified: the ETag in If-None-Match is still the current one. Use the answer you hold; this one has no body.", - "headers": { - "ETag": { - "description": "The strong ETag of this answer, to send back in If-None-Match.", - "schema": { - "type": "string" - } - } - } - }, - "401": { - "content": { - "application/problem+json": { - "examples": { - "unauthenticated": { - "value": { - "code": "unauthenticated", - "detail": "Bearer token required", - "status": 401, - "title": "unauthenticated", - "type": "https://cmapi.ephico2real.com/problems/unauthenticated" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." - }, - "403": { - "content": { - "application/problem+json": { - "examples": { - "environment-forbidden": { - "value": { - "code": "environment-forbidden", - "detail": "Your roles grant capacity:read only in ['rnd'], not dev", - "status": 403, - "title": "environment forbidden", - "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" + "id": "approval-turnaround-p50", + "name": "Approval turnaround (p50)", + "source": "database: submit to approved, requests that people approved", + "target": "4 h", + "targetStatus": "proposed", + "unit": "seconds", + "value": null + }, + { + "id": "approval-turnaround-p90", + "name": "Approval turnaround (p90)", + "source": "database: submit to approved, requests that people approved", + "target": "24 h", + "targetStatus": "proposed", + "unit": "seconds", + "value": null + }, + { + "id": "auto-approval-rate", + "name": "Auto-approval rate", + "source": "database: requests that a policy approved over requests that matched a policy", + "target": "tracked", + "targetStatus": "proposed", + "unit": "ratio", + "value": 1.0 + }, + { + "id": "self-service-rate", + "name": "Self-service rate", + "source": "database: synced requests with no approval that counted for approver-platform, over synced requests", + "target": "over 80%", + "targetStatus": "proposed", + "unit": "ratio", + "value": 1.0 + }, + { + "id": "change-failure-rate", + "name": "Change failure rate", + "source": "database: failed, sync_failed or reverted requests over merged requests", + "target": "under 5%", + "targetStatus": "proposed", + "unit": "ratio", + "value": 0.0 } + ], + "thresholds": { + "backupMaxAgeHours": 26.0, + "cpuPercent": 80.0, + "dbConnectionsPercent": 80.0, + "dbVolumePercent": 80.0, + "memoryPercent": 80.0, + "throttledPercent": 1.0 }, - "forbidden": { - "value": { - "code": "forbidden", - "detail": "Missing permission capacity:read: no role in your token grants it (roles: ['cmapi-requester'])", - "status": 403, - "title": "forbidden", - "type": "https://cmapi.ephico2real.com/problems/forbidden" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`, `environment-forbidden`." - }, - "404": { - "content": { - "application/problem+json": { - "examples": { - "cluster-not-found": { - "value": { - "code": "cluster-not-found", - "detail": "Unknown cluster OCP_X", - "status": 404, - "title": "cluster not found", - "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" - } - } + "unavailable": "a null value means not measured, never zero" }, "schema": { - "$ref": "#/components/schemas/ProblemDetail" + "$ref": "#/components/schemas/KpiView" } } }, - "description": "What the path names is not known.\n\nCodes: `cluster-not-found`." + "description": "Each component's memory and CPU against its limit, the database figures and the KPI rows; a figure not measured reads unavailable." }, - "412": { + "401": { "content": { "application/problem+json": { "examples": { - "precondition-failed": { + "unauthenticated": { "value": { - "code": "precondition-failed", - "detail": "If-Match does not list the current ETag of this answer: read it again", - "etag": "13b13a438dedd73906000f898819ba13", - "status": 412, - "title": "precondition failed", - "type": "https://cmapi.ephico2real.com/problems/precondition-failed" + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" } } }, @@ -11587,30 +11141,19 @@ } } }, - "description": "No strong tag that If-Match lists is the object's ETag: it changed since it was read, or the value named none.\n\nCodes: `precondition-failed`." + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." }, - "422": { + "403": { "content": { "application/problem+json": { "examples": { - "environment-not-served": { - "value": { - "code": "environment-not-served", - "detail": "qa is not served by the nonprod instance", - "instanceUrl": "https://cmapi-staging.ephico2real.com", - "portalUrl": "https://portal-staging.ephico2real.com", - "status": 422, - "title": "environment not served", - "type": "https://cmapi.ephico2real.com/problems/environment-not-served" - } - }, - "validation-failed": { + "forbidden": { "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" + "code": "forbidden", + "detail": "Missing permission reports:read: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" } } }, @@ -11619,7 +11162,7 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`, `environment-not-served`." + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." }, "429": { "content": { @@ -11691,184 +11234,127 @@ "keycloak": [] } ], - "summary": "Get cluster capacity by group", + "summary": "Get system KPIs", "tags": [ - "capacity" + "admin" ], - "x-cmapi-permission": "capacity:read", - "x-cmapi-plugin": "capacity", + "x-cmapi-permission": "reports:read", + "x-cmapi-plugin": "admin", "x-cmapi-rate-limit": "read", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/capacity -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/admin/kpi -H \"Authorization: Bearer $TOKEN\"" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/capacity:place": { - "post": { - "description": "Ranks every cluster of the environment for a namespace of this tier, and holds the first that still fits for 15 minutes\n(placement.yaml `reservation`): 201 with its `placementId`. The create then sends `placementId`, which turns the hold into the request's own\n(docs/02, \"Placement\"). `dryRun=true` ranks and holds nothing: the portal's preview.\n\nEach cluster is either ranked, best first, or excluded with a named reason: not connected, not writable, placement disabled,\noutside the region, zones or clusterSelector, stale or partial snapshot data, no size, maxNamespaces reached, no CPU or\nmemory headroom after committed quota and active reservations, and in prod no headroom after losing its largest zone. CPU\nand memory are checked separately. Nothing calls Thanos: the facts are the stored snapshots, the watch of each cluster and\nthe active holds.\n\nRanking needs capacity:read in the environment; the hold needs namespaces:create there too. A team holds at most 3 active\nplacements in an environment: a fourth is 429 rate-limited until one is claimed or lapses. When no cluster can be held,\n422 `no-placement` lists every exclusion. plugins.yaml can stop placement in an environment: 422 `plugin-disabled`, the dry\nrun too, after the permission check.\n\n**Requires** `capacity:read`.", - "operationId": "capacity_place", - "parameters": [ - { - "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", - "in": "query", - "name": "dryRun", - "required": false, - "schema": { - "default": false, - "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", - "examples": [ - true - ], - "title": "Dryrun", - "type": "boolean" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "example": { - "constraints": { - "region": "us-central" - }, - "environment": "dev", - "team": "billing", - "tier": "small" - }, - "schema": { - "$ref": "#/components/schemas/PlacementRequest" - } - } - }, - "required": true - }, + "/api/v1/admin/plugins": { + "get": { + "description": "Each part of the API with its version, and what `plugins.yaml` says for this instance: whether a plugin is\nenabled, and the environments where an override stops its writes. A plugin that is not enabled has no route and\nis not in this document.\n\n**Requires** `clusters:read`.", + "operationId": "admin_plugins", "responses": { "200": { "content": { "application/json": { "example": { - "asOf": "2026-11-27T20:59:13Z", - "clusterId": null, - "excluded": [], - "expiresAt": null, - "placementId": null, - "ranked": [ + "configured": false, + "instance": "nonprod", + "items": [ { - "basis": "simulated", - "boundBy": "cpu", - "clusterId": "CRC", - "cpu": { - "quotaHeadroomAfter": 72000, - "quotaHeadroomBefore": 80000, - "unit": "millicores", - "usageP95": null, - "zoneFailureHeadroomAfter": null - }, - "factors": { - "balance": 0.4375, - "quotaHeadroom": 0.5625, - "teamAffinity": 1.0, - "usageHeadroom": 0.0, - "zoneSpread": 0.0 - }, - "memory": { - "quotaHeadroomAfter": 223338299392, - "quotaHeadroomBefore": 240518168576, - "unit": "bytes", - "usageP95": null, - "zoneFailureHeadroomAfter": null - }, - "reserved": false, - "score": 39, - "snapshotAt": "2026-11-27T20:30:00Z" - } - ], - "request": { - "constraints": { - "clusterSelector": null, - "region": "us-central", - "zones": [] + "core": true, + "disabledEnvironments": [], + "enabled": true, + "name": "admin", + "version": "0.2.0" }, - "cpu": 8000, - "environment": "dev", - "memory": 17179869184, - "pods": 50, - "team": "payments", - "tier": "small" - } - }, - "schema": { - "$ref": "#/components/schemas/PlacementResult" - } - } - }, - "description": "Dry run (`?dryRun=true`): the plan. The call opens no change request, takes no lock or reservation, queues no job and opens no pull request." - }, - "201": { - "content": { - "application/json": { - "example": { - "asOf": "2026-11-27T20:59:13Z", - "clusterId": "CRC", - "excluded": [], - "expiresAt": "2026-11-27T21:14:13.469598Z", - "placementId": "pl-20261127-7658a163", - "ranked": [ { - "basis": "simulated", - "boundBy": "cpu", - "clusterId": "CRC", - "cpu": { - "quotaHeadroomAfter": 72000, - "quotaHeadroomBefore": 80000, - "unit": "millicores", - "usageP95": null, - "zoneFailureHeadroomAfter": null - }, - "factors": { - "balance": 0.4375, - "quotaHeadroom": 0.5625, - "teamAffinity": 0.0, - "usageHeadroom": 0.0, - "zoneSpread": 0.0 - }, - "memory": { - "quotaHeadroomAfter": 223338299392, - "quotaHeadroomBefore": 240518168576, - "unit": "bytes", - "usageP95": null, - "zoneFailureHeadroomAfter": null - }, - "reserved": true, - "score": 29, - "snapshotAt": "2026-11-27T20:30:00Z" - } - ], - "request": { - "constraints": { - "clusterSelector": null, - "region": "us-central", - "zones": [] + "core": true, + "disabledEnvironments": [], + "enabled": true, + "name": "core", + "version": "0.2.0" }, - "cpu": 8000, - "environment": "dev", - "memory": 17179869184, - "pods": 50, - "team": "billing", - "tier": "small" - } + { + "core": true, + "disabledEnvironments": [], + "enabled": true, + "name": "operations", + "version": "0.2.0" + }, + { + "core": true, + "disabledEnvironments": [], + "enabled": true, + "name": "requests", + "version": "0.2.0" + }, + { + "core": false, + "disabledEnvironments": [], + "enabled": true, + "name": "adoption", + "version": "0.2.0" + }, + { + "core": false, + "disabledEnvironments": [], + "enabled": true, + "name": "capacity", + "version": "0.2.0" + }, + { + "core": false, + "disabledEnvironments": [], + "enabled": true, + "name": "directory", + "version": "0.2.0" + }, + { + "core": false, + "disabledEnvironments": [], + "enabled": true, + "name": "expiration", + "version": "0.2.0" + }, + { + "core": false, + "disabledEnvironments": [], + "enabled": true, + "name": "namespaces", + "version": "0.2.0" + }, + { + "core": false, + "disabledEnvironments": [], + "enabled": true, + "name": "policies", + "version": "0.2.0" + }, + { + "core": false, + "disabledEnvironments": [], + "enabled": true, + "name": "quotas", + "version": "0.2.0" + }, + { + "core": false, + "disabledEnvironments": [], + "enabled": true, + "name": "tiers", + "version": "0.2.0" + } + ] }, "schema": { - "$ref": "#/components/schemas/PlacementResult" + "$ref": "#/components/schemas/PluginList" } } }, - "description": "The placement that holds the first cluster for 15 minutes (created), and the clusters ranked for the namespace." + "description": "Each plugin with its version, whether plugins.yaml enables it, and where an override stops its writes." }, "401": { "content": { @@ -11895,19 +11381,10 @@ "content": { "application/problem+json": { "examples": { - "environment-forbidden": { - "value": { - "code": "environment-forbidden", - "detail": "Your roles grant capacity:read only in ['rnd'], not dev", - "status": 403, - "title": "environment forbidden", - "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" - } - }, "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission capacity:read: no role in your token grants it (roles: ['cmapi-requester'])", + "detail": "Missing permission clusters:read: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -11919,95 +11396,7 @@ } } }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`, `environment-forbidden`." - }, - "413": { - "content": { - "application/problem+json": { - "examples": { - "content-too-large": { - "value": { - "code": "content-too-large", - "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", - "maxBytes": 1048576, - "status": 413, - "title": "content too large", - "type": "https://cmapi.ephico2real.com/problems/content-too-large" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." - }, - "422": { - "content": { - "application/problem+json": { - "examples": { - "environment-not-served": { - "value": { - "code": "environment-not-served", - "detail": "qa is not served by the nonprod instance", - "instanceUrl": "https://cmapi-staging.ephico2real.com", - "portalUrl": "https://portal-staging.ephico2real.com", - "status": 422, - "title": "environment not served", - "type": "https://cmapi.ephico2real.com/problems/environment-not-served" - } - }, - "no-placement": { - "value": { - "code": "no-placement", - "detail": "No dev cluster can take 8 cores and 16Gi: every candidate was excluded", - "excluded": [ - { - "clusterId": "CRC", - "detail": "region us-central, not eu-west", - "reason": "outside-region" - } - ], - "status": 422, - "title": "no placement", - "type": "https://cmapi.ephico2real.com/problems/no-placement" - } - }, - "plugin-disabled": { - "value": { - "code": "plugin-disabled", - "detail": "The namespaces plugin takes no writes in dev on the nonprod instance: plugins.yaml disables it there", - "status": 422, - "title": "plugin disabled", - "type": "https://cmapi.ephico2real.com/problems/plugin-disabled" - } - }, - "policy-violation": { - "value": { - "code": "policy-violation", - "detail": "Metadata refused", - "status": 422, - "title": "policy violation", - "type": "https://cmapi.ephico2real.com/problems/policy-violation" - } - }, - "validation-failed": { - "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`, `environment-not-served`, `plugin-disabled`, `policy-violation`, `no-placement`." + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." }, "429": { "content": { @@ -12079,64 +11468,223 @@ "keycloak": [] } ], - "summary": "Place a new namespace: rank the clusters and hold the first", + "summary": "List this instance's plugins", "tags": [ - "capacity" + "admin" ], - "x-cmapi-permission": "capacity:read", - "x-cmapi-plugin": "capacity", - "x-cmapi-rate-limit": "place", + "x-cmapi-permission": "clusters:read", + "x-cmapi-plugin": "admin", + "x-cmapi-rate-limit": "read", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/capacity:place -H \"Authorization: Bearer $TOKEN\" -H 'Content-Type: application/json' -d '{\"constraints\": {\"region\": \"us-central\"}, \"environment\": \"dev\", \"team\": \"billing\", \"tier\": \"small\"}'" + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/admin/plugins -H \"Authorization: Bearer $TOKEN\"" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/clusters": { - "get": { - "description": "Every cluster from clusters.yaml and every imported one, with its import status and the findings\nof the six checks. A cluster with a policy entry but no import Secret shows not-imported.\n\n**Requires** `clusters:read`.", - "operationId": "core_clusters", - "responses": { - "200": { + "/api/v1/admin/prune:confirm": { + "post": { + "description": "An operator confirms that a merged delete may remove the namespace. In `argocd` delivery the\nconfirmation happens in Argo CD and the worker observes it; in `apply` delivery this call is the\nconfirmation and the worker's delivery job removes the namespace. In `gitops` delivery the deliverer\nremoves it, and a read of its absence ends the request: this call only makes the worker read again.\n\n**Requires** `operations:run`.", + "operationId": "admin_prune_confirm", + "requestBody": { + "content": { + "application/json": { + "example": { + "clusterId": "CRC", + "namespace": "search-dev" + }, + "schema": { + "$ref": "#/components/schemas/PruneConfirm" + } + } + }, + "required": true + }, + "responses": { + "200": { "content": { "application/json": { "example": { - "items": [ + "action": "delete", + "approval": { + "approvals": [ + { + "at": "2026-12-01T15:13:18.601698Z", + "comment": "", + "relayedBy": null, + "sub": "sub-amy", + "username": "amy" + } + ], + "auto": null, + "autoFallback": null, + "reasons": [ + "dev delete: 1 from approver-platform" + ], + "remaining": [], + "rule": "dev-delete", + "selfApproval": true, + "slots": [ + { + "count": 1, + "group": "approver-platform", + "reason": "dev delete: 1 from approver-platform" + } + ], + "timeoutHours": 8 + }, + "baseSha": "4afd09a1a70bbf2c03d8d2253e817b57a5812c0a", + "beyondTier": null, + "clusterId": "CRC", + "createdAt": "2026-12-01T15:13:18.496644Z", + "env": "dev", + "events": [ { - "checkedAt": "2026-11-27T20:58:53.069187Z", - "clusterId": "CRC", - "environment": "dev", - "findingDetails": [], - "findings": [], - "gitopsPath": "clusters/CRC", - "labels": { - "region": "us-central" - }, - "lastProbeAt": "2026-11-27T20:58:53.069187Z", - "secretName": "cmapi-cluster-crc", - "serverVersion": "v1.35.6-fake", - "status": "connected", - "statusSince": "2026-11-27T20:58:53.069187Z", - "tokenExpiresAt": null, - "trust": { - "downgrade": false, - "serverName": null, - "source": "trusted" - }, - "writes": true + "at": "2026-12-01T15:13:18.510655Z", + "by": "ola", + "event": "plan_needs_approval", + "note": "waiting for [('approver-platform', 1)]", + "status": "pending_approval" + }, + { + "at": "2026-12-01T15:13:18.626143Z", + "by": "amy", + "event": "approval", + "note": "", + "status": "pending_approval" + }, + { + "at": "2026-12-01T15:13:18.644510Z", + "by": "amy", + "event": "approved", + "note": "approval count met", + "status": "approved" + }, + { + "at": "2026-12-01T15:13:18.898838Z", + "by": "cmapi-bot", + "event": "branch_pushed", + "note": "cmapi/CRC/req-20261201-0008 at f33469a0 on 4afd09a1 (created)", + "status": "approved" + }, + { + "at": "2026-12-01T15:13:19.140751Z", + "by": "cmapi-bot", + "event": "pr_opened", + "note": "cmapi/CRC/req-20261201-0008 #7", + "status": "pr_open" + }, + { + "at": "2026-12-01T15:13:19.339159Z", + "by": "ci", + "event": "ci", + "note": "kubeconform: pass; kyverno: pass; cmapi check: pass", + "status": "pr_open" + }, + { + "at": "2026-12-01T15:13:19.519914Z", + "by": "worker", + "event": "merge_verified", + "note": "merged f33469a0; the folder at it is the plan's", + "status": "pr_open" + }, + { + "at": "2026-12-01T15:13:19.535474Z", + "by": "cmapi-bot", + "event": "merged", + "note": "merged f33469a0", + "status": "merged" + }, + { + "at": "2026-12-01T15:13:19.737680Z", + "by": "cmapi-deliverer", + "event": "prune_pending", + "note": "Prune=confirm: waiting for an operator to confirm the prune", + "status": "awaiting_prune" + }, + { + "at": "2026-12-01T15:13:20.879794Z", + "by": "opal", + "event": "prune_confirm", + "note": "operator confirmed the prune", + "status": "awaiting_prune" } - ] + ], + "files": { + "clusters/CRC/namespaces/search-dev/limitrange-search-dev-limits-cpu.yaml": "removed", + "clusters/CRC/namespaces/search-dev/limitrange-search-dev-limits-memory.yaml": "removed", + "clusters/CRC/namespaces/search-dev/namespace.yaml": "removed", + "clusters/CRC/namespaces/search-dev/resourcequota-search-dev-quota.yaml": "removed", + "clusters/CRC/namespaces/search-dev/token-issuer-rolebinding.yaml": "removed" + }, + "instance": "nonprod", + "justification": null, + "links": { + "events": "/api/v1/requests/req-20261201-0008/events", + "pr": "https://git.test/pulls/7", + "self": "/api/v1/requests/req-20261201-0008" + }, + "mergeSha": "f33469a0", + "namespace": "search-dev", + "planHash": "c490196334dad591c3196aa59224d119861392145360aee1d428c93109235dbe", + "plugin": "namespaces", + "pr": { + "branch": "cmapi/CRC/req-20261201-0008", + "head": "f33469a0", + "number": 7, + "url": "https://git.test/pulls/7" + }, + "reason": null, + "requestId": "req-20261201-0008", + "requester": { + "automated": false, + "requester": { + "clientId": "cmapi-portal", + "email": "ola@ephico2real.com", + "employeeId": "1001", + "familyName": "Doe", + "givenName": "Ola", + "kind": "user", + "middleName": null, + "sub": "sub-ola", + "username": "ola" + }, + "submittedBy": null, + "submittedByClient": null + }, + "status": "awaiting_prune", + "updatedAt": "2026-12-01T15:13:20.605642Z" }, "schema": { - "$ref": "#/components/schemas/ClusterList" + "$ref": "#/components/schemas/ChangeRequest" } } }, - "description": "Every cluster with its environment, import status and the findings of its checks." + "description": "The delete request, with the prune confirmed." + }, + "400": { + "content": { + "application/problem+json": { + "examples": { + "dry-run-not-supported": { + "value": { + "code": "dry-run-not-supported", + "detail": "This call has no dry run, and nothing was done", + "status": 400, + "title": "dry run not supported", + "type": "https://cmapi.ephico2real.com/problems/dry-run-not-supported" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `dry-run-not-supported`." }, "401": { "content": { @@ -12163,10 +11711,19 @@ "content": { "application/problem+json": { "examples": { + "environment-forbidden": { + "value": { + "code": "environment-forbidden", + "detail": "Your roles grant operations:run only in ['rnd'], not dev", + "status": 403, + "title": "environment forbidden", + "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" + } + }, "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission clusters:read: no role in your token grants it (roles: ['cmapi-requester'])", + "detail": "Missing permission operations:run: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -12178,20 +11735,19 @@ } } }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`, `environment-forbidden`." }, - "429": { + "409": { "content": { "application/problem+json": { "examples": { - "rate-limited": { + "nothing-to-prune": { "value": { - "code": "rate-limited", - "detail": "Too many write calls by this caller; try again in 2 s", - "retryAfter": 2, - "status": 429, - "title": "rate limited", - "type": "https://cmapi.ephico2real.com/problems/rate-limited" + "code": "nothing-to-prune", + "detail": "No delete of payments-dev is awaiting a prune", + "status": 409, + "title": "nothing to prune", + "type": "https://cmapi.ephico2real.com/problems/nothing-to-prune" } } }, @@ -12200,30 +11756,20 @@ } } }, - "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } - } - } + "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `nothing-to-prune`." }, - "503": { + "413": { "content": { "application/problem+json": { "examples": { - "idp-unavailable": { + "content-too-large": { "value": { - "code": "idp-unavailable", - "detail": "Keycloak signing keys are unreachable and this key is not cached", - "retryAfter": 30, - "status": 503, - "title": "idp unavailable", - "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" + "code": "content-too-large", + "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", + "maxBytes": 1048576, + "status": 413, + "title": "content too large", + "type": "https://cmapi.ephico2real.com/problems/content-too-large" } } }, @@ -12232,192 +11778,7 @@ } } }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } - } - } - } - }, - "security": [ - { - "keycloak": [] - } - ], - "summary": "List known clusters", - "tags": [ - "core" - ], - "x-cmapi-permission": "clusters:read", - "x-cmapi-plugin": "core", - "x-cmapi-rate-limit": "read", - "x-codeSamples": [ - { - "label": "curl", - "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/clusters -H \"Authorization: Bearer $TOKEN\"" - } - ], - "x-plugin-version": "0.2.0" - } - }, - "/api/v1/clusters/{cluster_id}/adoption/candidates": { - "get": { - "description": "The candidates of the adoption design's D1, read now from the cluster: not a built-in or configured exclusion (adoption.yaml),\nnot Terminating, not managed (`cmapi.net/managed`, or a folder in Git), not tracked by another Argo CD Application, and\nlabelled `cmapi.net/adopt: \"true\"`. `recognised` lists the adoptionLabels of metadata-keys.yaml that a namespace carries:\na mark of another tool, which never selects a namespace by itself. `missingKeys` lists each declared label and annotation\nthat a candidate lacks, which `:adopt` may add (#739), with the one value of a key that cmapi fills in or that starts the\nname.\n\n**Requires** `namespaces:write`.", - "operationId": "adoption_candidates", - "parameters": [ - { - "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", - "in": "path", - "name": "cluster_id", - "required": true, - "schema": { - "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", - "examples": [ - "CRC" - ], - "title": "Cluster Id", - "type": "string" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "example": { - "items": [ - { - "application": null, - "detail": "", - "labelled": true, - "missingKeys": [ - { - "key": "cmapi.net/team", - "kind": "label", - "required": true, - "value": null - }, - { - "key": "cmapi.net/team-dl", - "kind": "annotation", - "required": true, - "value": null - }, - { - "key": "cmapi.net/cost-center", - "kind": "label", - "required": false, - "value": null - }, - { - "key": "cmapi.net/app", - "kind": "label", - "required": false, - "value": null - }, - { - "key": "cmapi.net/rightsizing", - "kind": "label", - "required": false, - "value": null - } - ], - "name": "abc-rnd", - "recognised": [ - "company.net/provisioner=cluster-configs" - ], - "rule": null, - "state": "candidate" - } - ], - "label": "cmapi.net/adopt", - "total": 1 - }, - "schema": { - "$ref": "#/components/schemas/AdoptionList" - } - } - }, - "description": "Each namespace of the cluster that carries the opt-in label, is not excluded, is not managed and is not tracked by another Argo CD Application, by name." - }, - "401": { - "content": { - "application/problem+json": { - "examples": { - "unauthenticated": { - "value": { - "code": "unauthenticated", - "detail": "Bearer token required", - "status": 401, - "title": "unauthenticated", - "type": "https://cmapi.ephico2real.com/problems/unauthenticated" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." - }, - "403": { - "content": { - "application/problem+json": { - "examples": { - "environment-forbidden": { - "value": { - "code": "environment-forbidden", - "detail": "Your roles grant namespaces:write only in ['rnd'], not dev", - "status": 403, - "title": "environment forbidden", - "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" - } - }, - "forbidden": { - "value": { - "code": "forbidden", - "detail": "Missing permission namespaces:write: no role in your token grants it (roles: ['cmapi-requester'])", - "status": 403, - "title": "forbidden", - "type": "https://cmapi.ephico2real.com/problems/forbidden" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`, `environment-forbidden`." - }, - "404": { - "content": { - "application/problem+json": { - "examples": { - "cluster-not-found": { - "value": { - "code": "cluster-not-found", - "detail": "Unknown cluster OCP_X", - "status": 404, - "title": "cluster not found", - "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "What the path names is not known.\n\nCodes: `cluster-not-found`." + "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." }, "422": { "content": { @@ -12472,41 +11833,10 @@ } } }, - "502": { - "content": { - "application/problem+json": { - "examples": { - "git-unavailable": { - "value": { - "code": "git-unavailable", - "detail": "The Git host answered 500", - "status": 502, - "title": "git unavailable", - "type": "https://cmapi.ephico2real.com/problems/git-unavailable" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The Git host failed.\n\nCodes: `git-unavailable`." - }, "503": { "content": { "application/problem+json": { "examples": { - "cluster-unreachable": { - "value": { - "code": "cluster-unreachable", - "detail": "CRC did not answer", - "retryAfter": 30, - "status": 503, - "title": "cluster unreachable", - "type": "https://cmapi.ephico2real.com/problems/cluster-unreachable" - } - }, "idp-unavailable": { "value": { "code": "idp-unavailable", @@ -12523,7 +11853,7 @@ } } }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `cluster-unreachable`, `idp-unavailable`.", + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", "headers": { "Retry-After": { "description": "The seconds to wait before the next call: the same number as `retryAfter`.", @@ -12541,69 +11871,293 @@ "keycloak": [] } ], - "summary": "List the namespaces that can be adopted", + "summary": "Confirm the prune of a deleted namespace", "tags": [ - "adoption" + "admin" ], - "x-cmapi-permission": "namespaces:write", - "x-cmapi-plugin": "adoption", - "x-cmapi-rate-limit": "read", + "x-cmapi-permission": "operations:run", + "x-cmapi-plugin": "admin", + "x-cmapi-rate-limit": "write", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/adoption/candidates -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/admin/prune:confirm -H \"Authorization: Bearer $TOKEN\" -H 'Content-Type: application/json' -d '{\"clusterId\": \"CRC\", \"namespace\": \"search-dev\"}'" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/clusters/{cluster_id}/adoption/skipped": { + "/api/v1/capacity": { "get": { - "description": "The namespaces that carry the opt-in label and are not candidates: `rule` is `excluded`, `terminating`, `managed`\n(already adopted: the label stays and is ignored) or `tracked-elsewhere` (with the Application in `application`).\n\n**Requires** `namespaces:write`.", - "operationId": "adoption_skipped", + "description": "Each cluster of the environments where the caller holds capacity:read: what cmapi's ResourceQuotas commit against the\ncluster's size times the environment's overcommit, with the size's basis (`simulated` from clusters.yaml, or the nodes'\n`allocatable`), the nodes, the zones and a named state. Then the groups by `groupBy`, whose figures are recomputed from the\nincluded clusters: summed commitments, headroom floored at 0 per cluster, and the largest single placement.\n\nRead from each cluster's watch, never from the cluster at request time. A figure that is not known is null, never 0. The\nanswer carries a strong ETag; If-None-Match answers 304, and an If-Match that does not list it answers 412.\n\n**Requires** `capacity:read`.", + "operationId": "capacity_capacity", "parameters": [ { - "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", - "in": "path", - "name": "cluster_id", - "required": true, + "description": "The keys of the groups, comma-separated, 1 to 3 of `environment`, `region` and `label:` (a clusters.yaml label). Another value returns 422 `validation-failed`.", + "in": "query", + "name": "groupBy", + "required": false, "schema": { - "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", + "default": "region,environment", + "description": "The keys of the groups, comma-separated, 1 to 3 of `environment`, `region` and `label:` (a clusters.yaml label). Another value returns 422 `validation-failed`.", "examples": [ - "CRC" + "region,environment" ], - "title": "Cluster Id", + "title": "Groupby", "type": "string" } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "example": { - "items": [ - { - "application": "legacy-tools", - "detail": "The Argo CD Application legacy-tools tracks legacy-tools", - "labelled": true, - "missingKeys": null, - "name": "legacy-tools", - "recognised": [], - "rule": "tracked-elsewhere", - "state": "skipped" + }, + { + "description": "Only the clusters of this environment. One the instance does not serve returns 422 `environment-not-served`; one where the caller lacks capacity:read returns 403 `environment-forbidden`.", + "in": "query", + "name": "env", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only the clusters of this environment. One the instance does not serve returns 422 `environment-not-served`; one where the caller lacks capacity:read returns 403 `environment-forbidden`.", + "examples": [ + "dev" + ], + "title": "Env" + } + }, + { + "description": "Only this cluster. One that is not in the caller's scope returns 404 `cluster-not-found`, as an unknown one does.", + "in": "query", + "name": "clusterId", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only this cluster. One that is not in the caller's scope returns 404 `cluster-not-found`, as an unknown one does.", + "examples": [ + "CRC" + ], + "title": "Clusterid" + } + }, + { + "description": "The ETag of the answer the caller holds. If it is still the current one, the answer is 304 with no body.", + "in": "header", + "name": "If-None-Match", + "required": false, + "schema": { + "examples": [ + "\"1f774baf9bf093f8d4ebc497eb0d5b96\"" + ], + "type": "string" + } + }, + { + "description": "Optional on a read. The answer is sent only if one strong tag listed here is its current ETag, or if the value is `*`; otherwise it is 412 `precondition-failed`, with the current tag in `etag`. A weak tag (`W/\"...\"`) never matches. If-Match is read before If-None-Match (RFC 9110, section 13.2.2). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line.", + "in": "header", + "name": "If-Match", + "required": false, + "schema": { + "examples": [ + "\"1f774baf9bf093f8d4ebc497eb0d5b96\"" + ], + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "clusters": [ + { + "asOf": "2026-12-01T15:13:00Z", + "basis": "simulated", + "boundBy": "cpu", + "clusterId": "CRC", + "cpu": { + "allocatable": 7800, + "commitment": 0.375, + "committed": 48000, + "headroom": 80000, + "limit": 128000, + "overcommit": 2.0, + "quotaUsed": 0, + "quotaUsedMissing": 0, + "requested": null, + "simulated": 64000, + "status": "ok", + "unit": "millicores", + "usedAvg": null, + "usedPeak": null + }, + "env": "dev", + "history": null, + "managedNamespaces": 3, + "memory": { + "allocatable": 20493357056, + "commitment": 0.3, + "committed": 103079215104, + "headroom": 240518168576, + "limit": 343597383680, + "overcommit": 1.25, + "quotaUsed": 0, + "quotaUsedMissing": 0, + "requested": null, + "simulated": 274877906944, + "status": "ok", + "unit": "bytes", + "usedAvg": null, + "usedPeak": null + }, + "nodes": { + "cordoned": 0, + "counted": 1, + "notReady": 0, + "tainted": 0, + "total": 1 + }, + "nodesDetail": null, + "nodesState": "ok", + "region": "us-central", + "scopedQuotas": 0, + "snapshot": { + "detail": "no snapshot yet", + "source": null, + "state": "none", + "takenAt": null + }, + "state": "ok", + "stateDetail": null, + "status": "ok", + "writes": true, + "zones": [] } ], - "label": "cmapi.net/adopt", - "total": 1 + "groupBy": [ + "region", + "environment" + ], + "groups": [ + { + "boundBy": "cpu", + "clusterIds": [ + "CRC" + ], + "coverage": 1.0, + "cpu": { + "commitment": 0.375, + "committed": 48000, + "headroom": 80000, + "largestPlacement": { + "clusterId": "CRC", + "value": 80000 + }, + "limit": 128000, + "unit": "millicores" + }, + "excluded": [], + "included": 1, + "key": { + "environment": "dev", + "region": "us-central" + }, + "matching": 1, + "memory": { + "commitment": 0.3, + "committed": 103079215104, + "headroom": 240518168576, + "largestPlacement": { + "clusterId": "CRC", + "value": 240518168576 + }, + "limit": 343597383680, + "unit": "bytes" + }, + "name": "us-central \u00b7 dev", + "status": "ok", + "statusCounts": { + "critical": 0, + "ok": 1, + "over": 0, + "warn": 0 + } + } + ], + "hiddenClusters": 0, + "notMeasured": [ + "requested", + "usedAvg", + "usedPeak", + "history" + ], + "snapshotIntervalSeconds": 1800, + "snapshotState": "stored", + "source": "live", + "staleAfterSeconds": 3600, + "targets": [ + { + "commitment": { + "critical": 0.95, + "warn": 0.85 + }, + "env": "dev", + "overcommit": { + "cpu": 2.0, + "memory": 1.25 + }, + "overcommitDefault": false + }, + { + "commitment": { + "critical": 0.95, + "warn": 0.85 + }, + "env": "rnd", + "overcommit": { + "cpu": 2.0, + "memory": 1.25 + }, + "overcommitDefault": false + } + ] }, "schema": { - "$ref": "#/components/schemas/AdoptionList" + "$ref": "#/components/schemas/CapacityPage" } } }, - "description": "Each namespace that carries the opt-in label and is not a candidate, with the rule that stops it." + "description": "The capacity of each cluster in the caller's environments, grouped as asked, with each cluster's targets and snapshot state.", + "headers": { + "ETag": { + "description": "The strong ETag of this answer, to send back in If-None-Match.", + "schema": { + "type": "string" + } + } + } + }, + "304": { + "description": "Not modified: the ETag in If-None-Match is still the current one. Use the answer you hold; this one has no body.", + "headers": { + "ETag": { + "description": "The strong ETag of this answer, to send back in If-None-Match.", + "schema": { + "type": "string" + } + } + } }, "401": { "content": { @@ -12633,7 +12187,7 @@ "environment-forbidden": { "value": { "code": "environment-forbidden", - "detail": "Your roles grant namespaces:write only in ['rnd'], not dev", + "detail": "Your roles grant capacity:read only in ['rnd'], not dev", "status": 403, "title": "environment forbidden", "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" @@ -12642,7 +12196,7 @@ "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission namespaces:write: no role in your token grants it (roles: ['cmapi-requester'])", + "detail": "Missing permission capacity:read: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -12677,11 +12231,44 @@ }, "description": "What the path names is not known.\n\nCodes: `cluster-not-found`." }, - "422": { + "412": { "content": { "application/problem+json": { "examples": { - "validation-failed": { + "precondition-failed": { + "value": { + "code": "precondition-failed", + "detail": "If-Match does not list the current ETag of this answer: read it again", + "etag": "26d4367b57e62464bfa3089775962d25", + "status": 412, + "title": "precondition failed", + "type": "https://cmapi.ephico2real.com/problems/precondition-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "No strong tag that If-Match lists is the object's ETag: it changed since it was read, or the value named none.\n\nCodes: `precondition-failed`." + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "environment-not-served": { + "value": { + "code": "environment-not-served", + "detail": "qa is not served by the nonprod instance", + "instanceUrl": "https://cmapi-staging.ephico2real.com", + "portalUrl": "https://portal-staging.ephico2real.com", + "status": 422, + "title": "environment not served", + "type": "https://cmapi.ephico2real.com/problems/environment-not-served" + } + }, + "validation-failed": { "value": { "code": "validation-failed", "detail": "Request body is not valid", @@ -12696,7 +12283,7 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`, `environment-not-served`." }, "429": { "content": { @@ -12730,41 +12317,10 @@ } } }, - "502": { - "content": { - "application/problem+json": { - "examples": { - "git-unavailable": { - "value": { - "code": "git-unavailable", - "detail": "The Git host answered 500", - "status": 502, - "title": "git unavailable", - "type": "https://cmapi.ephico2real.com/problems/git-unavailable" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The Git host failed.\n\nCodes: `git-unavailable`." - }, "503": { "content": { "application/problem+json": { "examples": { - "cluster-unreachable": { - "value": { - "code": "cluster-unreachable", - "detail": "CRC did not answer", - "retryAfter": 30, - "status": 503, - "title": "cluster unreachable", - "type": "https://cmapi.ephico2real.com/problems/cluster-unreachable" - } - }, "idp-unavailable": { "value": { "code": "idp-unavailable", @@ -12781,7 +12337,7 @@ } } }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `cluster-unreachable`, `idp-unavailable`.", + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", "headers": { "Retry-After": { "description": "The seconds to wait before the next call: the same number as `retryAfter`.", @@ -12799,101 +12355,184 @@ "keycloak": [] } ], - "summary": "List the labelled namespaces that a rule skips", + "summary": "Get cluster capacity by group", "tags": [ - "adoption" + "capacity" ], - "x-cmapi-permission": "namespaces:write", - "x-cmapi-plugin": "adoption", + "x-cmapi-permission": "capacity:read", + "x-cmapi-plugin": "capacity", "x-cmapi-rate-limit": "read", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/adoption/skipped -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/capacity -H \"Authorization: Bearer $TOKEN\"" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/clusters/{cluster_id}/capacity": { - "get": { - "description": "The stored rows of the cluster's newest complete snapshot (docs/02, \"Cluster snapshots\"): one for the cluster, one per\nzone and one per node role, each with CPU in millicores and memory in bytes. A figure that the snapshot did not measure is\nnull, never 0: with capacity.yaml `usage.source: none` the requests, limits and use are null. The worker stores a\nsnapshot every capacity.yaml `snapshotInterval`; `snapshot.state` says whether placement can use it.\n\nGateway scope (docs/02, \"Reached only through cmapi\"): capacity:read in the cluster's environment. A cluster outside the\ncaller's environments answers 404 `cluster-not-found`, as an unknown one does.\n\n**Requires** `capacity:read`.", - "operationId": "capacity_cluster_capacity", + "/api/v1/capacity:place": { + "post": { + "description": "Ranks every cluster of the environment for a namespace of this tier, and holds the first that still fits for 15 minutes\n(placement.yaml `reservation`): 201 with its `placementId`. The create then sends `placementId`, which turns the hold into the request's own\n(docs/02, \"Placement\"). `dryRun=true` ranks and holds nothing: the portal's preview.\n\nEach cluster is either ranked, best first, or excluded with a named reason: not connected, not writable, placement disabled,\noutside the region, zones or clusterSelector, stale or partial snapshot data, no size, maxNamespaces reached, no CPU or\nmemory headroom after committed quota and active reservations, and in prod no headroom after losing its largest zone. CPU\nand memory are checked separately. Nothing calls Thanos: the facts are the stored snapshots, the watch of each cluster and\nthe active holds.\n\nRanking needs capacity:read in the environment; the hold needs namespaces:create there too. A team holds at most 3 active\nplacements in an environment: a fourth is 429 rate-limited until one is claimed or lapses. When no cluster can be held,\n422 `no-placement` lists every exclusion. plugins.yaml can stop placement in an environment: 422 `plugin-disabled`, the dry\nrun too, after the permission check.\n\n**Requires** `capacity:read`.", + "operationId": "capacity_place", "parameters": [ { - "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", - "in": "path", - "name": "cluster_id", - "required": true, + "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", + "in": "query", + "name": "dryRun", + "required": false, "schema": { - "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", + "default": false, + "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", "examples": [ - "CRC" + true ], - "title": "Cluster Id", - "type": "string" + "title": "Dryrun", + "type": "boolean" } } ], + "requestBody": { + "content": { + "application/json": { + "example": { + "constraints": { + "region": "us-central" + }, + "environment": "dev", + "team": "billing", + "tier": "small" + }, + "schema": { + "$ref": "#/components/schemas/PlacementRequest" + } + } + }, + "required": true + }, "responses": { "200": { "content": { "application/json": { "example": { - "clusterId": "CRC", - "env": "dev", - "intervalSeconds": 1800, - "scopes": [ + "asOf": "2026-12-01T15:13:31Z", + "clusterId": null, + "excluded": [], + "expiresAt": null, + "placementId": null, + "ranked": [ { + "basis": "simulated", + "boundBy": "cpu", + "clusterId": "CRC", "cpu": { - "allocatable": 7800, - "capacity": 7800, - "limits": null, - "quotaCommitted": 48000, - "requested": null, + "quotaHeadroomAfter": 72000, + "quotaHeadroomBefore": 80000, "unit": "millicores", - "usedAvg": null, - "usedPeak": null + "usageP95": null, + "zoneFailureHeadroomAfter": null + }, + "factors": { + "balance": 0.4375, + "quotaHeadroom": 0.5625, + "teamAffinity": 1.0, + "usageHeadroom": 0.0, + "zoneSpread": 0.0 }, "memory": { - "allocatable": 20493357056, - "capacity": 20493357056, - "limits": null, - "quotaCommitted": 103079215104, - "requested": null, + "quotaHeadroomAfter": 223338299392, + "quotaHeadroomBefore": 240518168576, "unit": "bytes", - "usedAvg": null, - "usedPeak": null + "usageP95": null, + "zoneFailureHeadroomAfter": null }, - "nodes": { - "diskPressure": 0, - "memoryPressure": 0, - "notReady": 0, - "schedulable": 1, - "total": 1 + "reserved": false, + "score": 39, + "snapshotAt": "2026-12-01T15:00:00Z" + } + ], + "request": { + "constraints": { + "clusterSelector": null, + "region": "us-central", + "zones": [] + }, + "cpu": 8000, + "environment": "dev", + "memory": 17179869184, + "pods": 50, + "team": "payments", + "tier": "small" + } + }, + "schema": { + "$ref": "#/components/schemas/PlacementResult" + } + } + }, + "description": "Dry run (`?dryRun=true`): the plan. The call opens no change request, takes no lock or reservation, queues no job and opens no pull request." + }, + "201": { + "content": { + "application/json": { + "example": { + "asOf": "2026-12-01T15:13:31Z", + "clusterId": "CRC", + "excluded": [], + "expiresAt": "2026-12-01T15:28:31.965297Z", + "placementId": "pl-20261201-52bb3c04", + "ranked": [ + { + "basis": "simulated", + "boundBy": "cpu", + "clusterId": "CRC", + "cpu": { + "quotaHeadroomAfter": 72000, + "quotaHeadroomBefore": 80000, + "unit": "millicores", + "usageP95": null, + "zoneFailureHeadroomAfter": null }, - "pods": { - "allocatable": 250, - "running": null + "factors": { + "balance": 0.4375, + "quotaHeadroom": 0.5625, + "teamAffinity": 0.0, + "usageHeadroom": 0.0, + "zoneSpread": 0.0 }, - "scope": "cluster" + "memory": { + "quotaHeadroomAfter": 223338299392, + "quotaHeadroomBefore": 240518168576, + "unit": "bytes", + "usageP95": null, + "zoneFailureHeadroomAfter": null + }, + "reserved": true, + "score": 29, + "snapshotAt": "2026-12-01T15:00:00Z" } ], - "snapshot": { - "detail": null, - "source": "api", - "state": "ok", - "takenAt": "2026-11-27T20:30:00Z" - }, - "staleAfterSeconds": 3600 + "request": { + "constraints": { + "clusterSelector": null, + "region": "us-central", + "zones": [] + }, + "cpu": 8000, + "environment": "dev", + "memory": 17179869184, + "pods": 50, + "team": "billing", + "tier": "small" + } }, "schema": { - "$ref": "#/components/schemas/ClusterSnapshot" + "$ref": "#/components/schemas/PlacementResult" } } }, - "description": "The cluster's newest complete capacity snapshot: the whole cluster, each zone and each node role, with its freshness as placement reads it." + "description": "The placement that holds the first cluster for 15 minutes (created), and the clusters ranked for the namespace." }, "401": { "content": { @@ -12920,10 +12559,19 @@ "content": { "application/problem+json": { "examples": { - "forbidden": { + "environment-forbidden": { "value": { - "code": "forbidden", - "detail": "Missing permission capacity:read: no role in your token grants it (roles: ['cmapi-requester'])", + "code": "environment-forbidden", + "detail": "Your roles grant capacity:read only in ['rnd'], not dev", + "status": 403, + "title": "environment forbidden", + "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" + } + }, + "forbidden": { + "value": { + "code": "forbidden", + "detail": "Missing permission capacity:read: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -12935,19 +12583,20 @@ } } }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`, `environment-forbidden`." }, - "404": { + "413": { "content": { "application/problem+json": { "examples": { - "cluster-not-found": { + "content-too-large": { "value": { - "code": "cluster-not-found", - "detail": "Unknown cluster NOPE", - "status": 404, - "title": "cluster not found", - "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" + "code": "content-too-large", + "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", + "maxBytes": 1048576, + "status": 413, + "title": "content too large", + "type": "https://cmapi.ephico2real.com/problems/content-too-large" } } }, @@ -12956,12 +12605,57 @@ } } }, - "description": "What the path names is not known.\n\nCodes: `cluster-not-found`." + "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." }, "422": { "content": { "application/problem+json": { "examples": { + "environment-not-served": { + "value": { + "code": "environment-not-served", + "detail": "qa is not served by the nonprod instance", + "instanceUrl": "https://cmapi-staging.ephico2real.com", + "portalUrl": "https://portal-staging.ephico2real.com", + "status": 422, + "title": "environment not served", + "type": "https://cmapi.ephico2real.com/problems/environment-not-served" + } + }, + "no-placement": { + "value": { + "code": "no-placement", + "detail": "No dev cluster can take 8 cores and 16Gi: every candidate was excluded", + "excluded": [ + { + "clusterId": "CRC", + "detail": "region us-central, not eu-west", + "reason": "outside-region" + } + ], + "status": 422, + "title": "no placement", + "type": "https://cmapi.ephico2real.com/problems/no-placement" + } + }, + "plugin-disabled": { + "value": { + "code": "plugin-disabled", + "detail": "The namespaces plugin takes no writes in dev on the nonprod instance: plugins.yaml disables it there", + "status": 422, + "title": "plugin disabled", + "type": "https://cmapi.ephico2real.com/problems/plugin-disabled" + } + }, + "policy-violation": { + "value": { + "code": "policy-violation", + "detail": "Metadata refused", + "status": 422, + "title": "policy violation", + "type": "https://cmapi.ephico2real.com/problems/policy-violation" + } + }, "validation-failed": { "value": { "code": "validation-failed", @@ -12977,7 +12671,7 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`, `environment-not-served`, `plugin-disabled`, `policy-violation`, `no-placement`." }, "429": { "content": { @@ -13049,78 +12743,64 @@ "keycloak": [] } ], - "summary": "Get a cluster's capacity snapshot", + "summary": "Place a new namespace: rank the clusters and hold the first", "tags": [ "capacity" ], "x-cmapi-permission": "capacity:read", "x-cmapi-plugin": "capacity", - "x-cmapi-rate-limit": "read", + "x-cmapi-rate-limit": "place", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/capacity -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/capacity:place -H \"Authorization: Bearer $TOKEN\" -H 'Content-Type: application/json' -d '{\"constraints\": {\"region\": \"us-central\"}, \"environment\": \"dev\", \"team\": \"billing\", \"tier\": \"small\"}'" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/clusters/{cluster_id}/capacity/snapshots:run": { - "post": { - "description": "Queues a snapshot of the cluster now, outside the schedule (docs/02, \"POST .../capacity/snapshots:run ... Run now\n(operations:run)\"): the worker writes the rows of the current interval again. Needs operations:run in the cluster's\nenvironment; a cluster outside it answers 404 `cluster-not-found`. plugins.yaml can stop it in an environment: 422\n`plugin-disabled`, after the permission check.\n\n**Requires** `operations:run`.", - "operationId": "capacity_run_snapshot", - "parameters": [ - { - "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", - "in": "path", - "name": "cluster_id", - "required": true, - "schema": { - "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", - "examples": [ - "CRC" - ], - "title": "Cluster Id", - "type": "string" - } - } - ], + "/api/v1/clusters": { + "get": { + "description": "Every cluster from clusters.yaml and every imported one, with its import status and the findings\nof the six checks. A cluster with a policy entry but no import Secret shows not-imported.\n\n**Requires** `clusters:read`.", + "operationId": "core_clusters", "responses": { - "202": { + "200": { "content": { "application/json": { "example": { - "clusterId": "CRC", - "queued": true - }, - "schema": { - "$ref": "#/components/schemas/SnapshotRun" - } - } - }, - "description": "The run is queued: the worker writes the cluster's snapshot of the current interval again." - }, - "400": { - "content": { - "application/problem+json": { - "examples": { - "dry-run-not-supported": { - "value": { - "code": "dry-run-not-supported", - "detail": "This call has no dry run, and nothing was done", - "status": 400, - "title": "dry run not supported", - "type": "https://cmapi.ephico2real.com/problems/dry-run-not-supported" + "items": [ + { + "checkedAt": "2026-12-01T15:12:54.018046Z", + "clusterId": "CRC", + "environment": "dev", + "findingDetails": [], + "findings": [], + "gitopsPath": "clusters/CRC", + "labels": { + "region": "us-central" + }, + "lastProbeAt": "2026-12-01T15:12:54.018046Z", + "secretName": "cmapi-cluster-crc", + "serverVersion": "v1.35.6-fake", + "status": "connected", + "statusSince": "2026-12-01T15:12:54.018046Z", + "tokenExpiresAt": null, + "trust": { + "downgrade": false, + "serverName": null, + "source": "trusted" + }, + "writes": true } - } + ] }, "schema": { - "$ref": "#/components/schemas/ProblemDetail" + "$ref": "#/components/schemas/ClusterList" } } }, - "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `dry-run-not-supported`." + "description": "Every cluster with its environment, import status and the findings of its checks." }, "401": { "content": { @@ -13150,7 +12830,7 @@ "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission operations:run: no role in your token grants it (roles: ['cmapi-requester'])", + "detail": "Missing permission clusters:read: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -13164,57 +12844,6 @@ }, "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." }, - "404": { - "content": { - "application/problem+json": { - "examples": { - "cluster-not-found": { - "value": { - "code": "cluster-not-found", - "detail": "Unknown cluster OCP_X", - "status": 404, - "title": "cluster not found", - "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "What the path names is not known.\n\nCodes: `cluster-not-found`." - }, - "422": { - "content": { - "application/problem+json": { - "examples": { - "plugin-disabled": { - "value": { - "code": "plugin-disabled", - "detail": "The namespaces plugin takes no writes in dev on the nonprod instance: plugins.yaml disables it there", - "status": 422, - "title": "plugin disabled", - "type": "https://cmapi.ephico2real.com/problems/plugin-disabled" - } - }, - "validation-failed": { - "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `plugin-disabled`, `validation-failed`." - }, "429": { "content": { "application/problem+json": { @@ -13285,27 +12914,27 @@ "keycloak": [] } ], - "summary": "Run a cluster's capacity snapshot now", + "summary": "List known clusters", "tags": [ - "capacity" + "core" ], - "x-cmapi-permission": "operations:run", - "x-cmapi-plugin": "capacity", - "x-cmapi-rate-limit": "write", + "x-cmapi-permission": "clusters:read", + "x-cmapi-plugin": "core", + "x-cmapi-rate-limit": "read", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/capacity/snapshots:run -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/clusters -H \"Authorization: Bearer $TOKEN\"" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/clusters/{cluster_id}/namespaces": { + "/api/v1/clusters/{cluster_id}/adoption/candidates": { "get": { - "description": "Every namespace labelled cmapi.net/managed=true on the cluster, from the watch cache, with the request\nholding each one's lock. The etag is only on the single-namespace read, because it comes from Git.\n\nThe lookup after a cluster is chosen (#481): `q` matches the name, the team label and the app label, names that\nstart with it first, then names that contain it, then team and app matches; `mnemonic` keeps one mnemonic's\nnamespaces; `limit` caps the answer. `total` counts every match before the cap, and `facets.mnemonics` the\nnamespaces of each mnemonic. Each item's `sync` is `pending` when a request holds it and `unknown` otherwise: the\nlist reads no Git, so it compares nothing. With none of the three parameters the list is every namespace by name.\n\n**Requires** `objects:read`.", - "operationId": "namespaces_list_namespaces", + "description": "The candidates of the adoption design's D1, read now from the cluster: not a built-in or configured exclusion (adoption.yaml),\nnot Terminating, not managed (`cmapi.net/managed`, or a folder in Git), not tracked by another Argo CD Application, and\nlabelled `cmapi.net/adopt: \"true\"`. `recognised` lists the adoptionLabels of metadata-keys.yaml that a namespace carries:\na mark of another tool, which never selects a namespace by itself. `missingKeys` lists each declared label and annotation\nthat a candidate lacks, which `:adopt` may add (#739), with the one value of a key that cmapi fills in or that starts the\nname.\n\n**Requires** `namespaces:write`.", + "operationId": "adoption_candidates", "parameters": [ { "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", @@ -13320,72 +12949,6 @@ "title": "Cluster Id", "type": "string" } - }, - { - "description": "Text that the name, the team label or the app label contains. Case does not matter. Names that start with it come first.", - "in": "query", - "name": "q", - "required": false, - "schema": { - "anyOf": [ - { - "maxLength": 63, - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Text that the name, the team label or the app label contains. Case does not matter. Names that start with it come first.", - "examples": [ - "pay" - ], - "title": "Q" - } - }, - { - "description": "Only the namespaces of this mnemonic: the value of the key that starts the namespace name (`namespacePrefix` of metadata-keys.yaml).", - "in": "query", - "name": "mnemonic", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Only the namespaces of this mnemonic: the value of the key that starts the namespace name (`namespacePrefix` of metadata-keys.yaml).", - "examples": [ - "abc" - ], - "title": "Mnemonic" - } - }, - { - "description": "The most namespaces to return: 10 when `q` or `mnemonic` is sent without it, at most 50. With none of the three, every namespace is returned, by name.", - "in": "query", - "name": "limit", - "required": false, - "schema": { - "anyOf": [ - { - "maximum": 50, - "minimum": 1, - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "The most namespaces to return: 10 when `q` or `mnemonic` is sent without it, at most 50. With none of the three, every namespace is returned, by name.", - "examples": [ - 10 - ], - "title": "Limit" - } } ], "responses": { @@ -13393,55 +12956,60 @@ "content": { "application/json": { "example": { - "facets": { - "mnemonics": {} - }, "items": [ { - "annotations": { - "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", - "cmapi.net/instance": "nonprod", - "cmapi.net/request-id": "req-20261127-0001", - "cmapi.net/requested-by": "ola@ephico2real.com", - "cmapi.net/team-dl": "payments-team@ephico2real.com" - }, - "clusterId": "CRC", - "env": "dev", - "etag": null, - "expiresAt": null, - "git": null, - "labels": { - "cmapi.net/cluster-id": "CRC", - "cmapi.net/cost-center": "cc-4410", - "cmapi.net/env": "dev", - "cmapi.net/managed": "true", - "cmapi.net/requested-by-user": "ola", - "cmapi.net/team": "payments", - "cmapi.net/tier": "small" - }, - "managed": true, - "mnemonic": null, - "name": "payments-dev", - "openRequest": null, - "protected": null, - "protectedBy": null, - "sync": { - "driftedKeys": [], - "openRequest": null, - "state": "unknown" - }, - "team": "payments", - "tier": "small" + "application": null, + "detail": "", + "labelled": true, + "missingKeys": [ + { + "key": "cmapi.net/team", + "kind": "label", + "required": true, + "value": null + }, + { + "key": "cmapi.net/team-dl", + "kind": "annotation", + "required": true, + "value": null + }, + { + "key": "cmapi.net/cost-center", + "kind": "label", + "required": false, + "value": null + }, + { + "key": "cmapi.net/app", + "kind": "label", + "required": false, + "value": null + }, + { + "key": "cmapi.net/rightsizing", + "kind": "label", + "required": false, + "value": null + } + ], + "name": "abc-rnd", + "recognised": [ + "company.net/provisioner=cluster-configs" + ], + "rule": null, + "state": "candidate" } ], + "label": "cmapi.net/adopt", "total": 1 }, "schema": { - "$ref": "#/components/schemas/NamespaceList" + "$ref": "#/components/schemas/AdoptionList" } } }, - "description": "The managed namespaces of the cluster that match the filters, with their count and the facets." + "description": "Each namespace of the cluster that carries the opt-in label, is not excluded, is not managed and is not tracked by another Argo CD Application, by name." }, "401": { "content": { @@ -13471,7 +13039,7 @@ "environment-forbidden": { "value": { "code": "environment-forbidden", - "detail": "Your roles grant objects:read only in ['rnd'], not dev", + "detail": "Your roles grant namespaces:write only in ['rnd'], not dev", "status": 403, "title": "environment forbidden", "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" @@ -13480,7 +13048,7 @@ "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission objects:read: no role in your token grants it (roles: ['cmapi-requester'])", + "detail": "Missing permission namespaces:write: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -13501,7 +13069,7 @@ "cluster-not-found": { "value": { "code": "cluster-not-found", - "detail": "Unknown cluster NOPE", + "detail": "Unknown cluster OCP_X", "status": 404, "title": "cluster not found", "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" @@ -13522,14 +13090,7 @@ "validation-failed": { "value": { "code": "validation-failed", - "detail": "The request is not valid: query.limit: Input should be greater than or equal to 1", - "errors": [ - { - "code": "greater_than_equal", - "field": "query.limit", - "message": "Input should be greater than or equal to 1" - } - ], + "detail": "Request body is not valid", "status": 422, "title": "validation failed", "type": "https://cmapi.ephico2real.com/problems/validation-failed" @@ -13575,6 +13136,27 @@ } } }, + "502": { + "content": { + "application/problem+json": { + "examples": { + "git-unavailable": { + "value": { + "code": "git-unavailable", + "detail": "The Git host answered 500", + "status": 502, + "title": "git unavailable", + "type": "https://cmapi.ephico2real.com/problems/git-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The Git host failed.\n\nCodes: `git-unavailable`." + }, "503": { "content": { "application/problem+json": { @@ -13623,25 +13205,27 @@ "keycloak": [] } ], - "summary": "List managed namespaces on a cluster", + "summary": "List the namespaces that can be adopted", "tags": [ - "namespaces" + "adoption" ], - "x-cmapi-permission": "objects:read", - "x-cmapi-plugin": "namespaces", + "x-cmapi-permission": "namespaces:write", + "x-cmapi-plugin": "adoption", "x-cmapi-rate-limit": "read", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/adoption/candidates -H \"Authorization: Bearer $TOKEN\"" } ], "x-plugin-version": "0.2.0" - }, - "post": { - "description": "Plans a new namespace on the cluster and submits a change request; the bot opens a pull request once it\nis approved. `dryRun=true` answers 200 with the plan, the capacity check and the approval that would apply,\nand opens no request. The environment is the cluster's and must be one this instance serves.\n\n**Requires** `namespaces:create`.", - "operationId": "namespaces_create_namespace", + } + }, + "/api/v1/clusters/{cluster_id}/adoption/skipped": { + "get": { + "description": "The namespaces that carry the opt-in label and are not candidates: `rule` is `excluded`, `terminating`, `managed`\n(already adopted: the label stays and is ignored) or `tracked-elsewhere` (with the Application in `application`).\n\n**Requires** `namespaces:write`.", + "operationId": "adoption_skipped", "parameters": [ { "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", @@ -13656,328 +13240,34 @@ "title": "Cluster Id", "type": "string" } - }, - { - "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", - "in": "query", - "name": "dryRun", - "required": false, - "schema": { - "default": false, - "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", - "examples": [ - true - ], - "title": "Dryrun", - "type": "boolean" - } - }, - { - "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state. The caller is the token's subject: a service that sends `onBehalfOf` holds its key, and the person cannot replay it: the person's own use of that key is a request of their own. The same key with another request is 409 `idempotency-replay`. The expiry writes do not compare `justification`: a retry that changes only it gets the original request.", - "in": "header", - "name": "Idempotency-Key", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state. The caller is the token's subject: a service that sends `onBehalfOf` holds its key, and the person cannot replay it: the person's own use of that key is a request of their own. The same key with another request is 409 `idempotency-replay`. The expiry writes do not compare `justification`: a retry that changes only it gets the original request.", - "examples": [ - "0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10" - ], - "title": "Idempotency-Key" - } } ], - "requestBody": { - "content": { - "application/json": { - "examples": { - "permanent": { - "summary": "Permanent namespace", - "value": { - "annotations": { - "cmapi.net/team-dl": "payments-team@ephico2real.com" - }, - "justification": "Payments service dev namespace", - "labels": { - "cmapi.net/cost-center": "cc-4410", - "cmapi.net/team": "payments" - }, - "namespace": "payments-dev", - "tier": "small" - } - }, - "withExpiry": { - "summary": "With expiration (choose a future date when sending)", - "value": { - "annotations": { - "cmapi.net/team-dl": "payments-team@ephico2real.com" - }, - "expiresAt": "2026-12-15", - "justification": "Payments service dev namespace", - "labels": { - "cmapi.net/cost-center": "cc-4410", - "cmapi.net/team": "payments" - }, - "namespace": "payments-dev", - "tier": "small" - } - } - }, - "schema": { - "$ref": "#/components/schemas/NamespaceCreate" - } - } - }, - "required": true - }, "responses": { "200": { "content": { "application/json": { "example": { - "adoption": null, - "approval": { - "approvals": [], - "auto": null, - "autoFallback": null, - "reasons": [ - "dev create: 1 from approver-platform", - "threshold beyondTier: +1 approver-platform" - ], - "remaining": [ - { - "group": "approver-platform", - "needed": 2 - } - ], - "rule": "dev-create", - "selfApproval": true, - "slots": [ - { - "count": 2, - "group": "approver-platform", - "reason": "dev create: 1 from approver-platform; Value beyond the tier" - } - ], - "timeoutHours": 8 - }, - "beyondTier": { - "approvals": [ - { - "count": 1, - "group": "approver-platform", - "reason": "Value beyond the tier" - } - ], - "keys": [ - { - "key": "limitRange.container.default.cpu", - "requested": "1", - "tier": "500m" - }, - { - "key": "limitRange.container.default.memory", - "requested": "1Gi", - "tier": "512Mi" - }, - { - "key": "limitRange.container.max.cpu", - "requested": "4", - "tier": "2" - }, - { - "key": "limitRange.container.max.memory", - "requested": "8Gi", - "tier": "4Gi" - }, - { - "key": "requests.storage", - "requested": "500Gi", - "tier": "200Gi" - } - ] - }, - "capacity": { - "bindingResource": "cpu", - "clusterId": "CRC", - "cpu": 0.031, - "fresh": true, - "memory": 0.025, - "reserved": { - "cpu": 0.0, - "memory": 0 - }, - "source": "simulated", - "status": "fits" - }, - "changes": { - "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "added", - "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "added", - "clusters/CRC/namespaces/payments-dev/namespace.yaml": "added", - "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "added", - "clusters/CRC/namespaces/payments-dev/token-issuer-rolebinding.yaml": "added" - }, - "etag": "0", - "files": { - "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-cpu\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: custom\n annotations:\n cmapi.net/beyond-tier: limitRange.container.default.cpu,limitRange.container.max.cpu\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 77ae5f8f5ddd\nspec:\n limits:\n - type: Container\n defaultRequest:\n cpu: 100m\n default:\n cpu: '1'\n max:\n cpu: '4'\n", - "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-memory\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: custom\n annotations:\n cmapi.net/beyond-tier: limitRange.container.default.memory,limitRange.container.max.memory\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 77ae5f8f5ddd\nspec:\n limits:\n - type: Container\n defaultRequest:\n memory: 256Mi\n default:\n memory: 1Gi\n max:\n memory: 8Gi\n", - "clusters/CRC/namespaces/payments-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: custom\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n", - "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "apiVersion: v1\nkind: ResourceQuota\nmetadata:\n name: payments-dev-quota\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: custom\n annotations:\n cmapi.net/beyond-tier: requests.storage\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 77ae5f8f5ddd\nspec:\n hard:\n requests.cpu: '4'\n requests.memory: 8Gi\n pods: '20'\n persistentvolumeclaims: '20'\n requests.storage: 500Gi\n services.loadbalancers: '0'\n services.nodeports: '0'\n", - "clusters/CRC/namespaces/payments-dev/token-issuer-rolebinding.yaml": "apiVersion: rbac.authorization.k8s.io/v1\nkind: RoleBinding\nmetadata:\n name: cmapi-token-issuer\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\nroleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: ClusterRole\n name: cmapi-token-issuer\nsubjects:\n- kind: ServiceAccount\n name: cmapi-reader\n namespace: cmapi-system\n" - }, - "findings": [], - "metadata": { - "annotations": { - "cmapi.net/team-dl": { - "source": "request", - "value": "payments-team@ephico2real.com" - } - }, - "labels": { - "cmapi.net/cost-center": { - "source": "request", - "value": "cc-4410" - }, - "cmapi.net/team": { - "source": "request", - "value": "payments" - } - }, - "namespace": "payments-dev" - }, - "metadataDiff": null, - "planHash": "581590b32816a9c0d6951dbf13ba41816b2bf074eeb6017bcbf8fc3557906a75", - "requester": { - "automated": false, - "requester": { - "clientId": "cmapi-portal", - "email": "ola@ephico2real.com", - "employeeId": "1001", - "familyName": "Doe", - "givenName": "Ola", - "kind": "user", - "middleName": null, - "sub": "sub-ola", - "username": "ola" - }, - "submittedBy": null, - "submittedByClient": null - }, - "usage": null - }, - "schema": { - "$ref": "#/components/schemas/PlanView" - } - } - }, - "description": "Dry run (`?dryRun=true`): the plan. The call opens no change request, takes no lock or reservation, queues no job and opens no pull request." - }, - "202": { - "content": { - "application/json": { - "example": { - "action": "create", - "approval": { - "approvals": [], - "auto": "auto:baseline-rnd-namespace", - "autoFallback": null, - "reasons": [ - "dev create: 1 from approver-platform", - "auto-approved by policy baseline-rnd-namespace" - ], - "remaining": [], - "rule": "dev-create", - "selfApproval": true, - "slots": [], - "timeoutHours": 8 - }, - "baseSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "beyondTier": null, - "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:54.441022Z", - "env": "dev", - "events": [ + "items": [ { - "at": "2026-11-27T20:58:54.488801Z", - "by": "ola", - "event": "plan_auto_approved", - "note": "auto:baseline-rnd-namespace", - "status": "approved" + "application": "legacy-tools", + "detail": "The Argo CD Application legacy-tools tracks legacy-tools", + "labelled": true, + "missingKeys": null, + "name": "legacy-tools", + "recognised": [], + "rule": "tracked-elsewhere", + "state": "skipped" } ], - "files": { - "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "added", - "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "added", - "clusters/CRC/namespaces/payments-dev/namespace.yaml": "added", - "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "added", - "clusters/CRC/namespaces/payments-dev/token-issuer-rolebinding.yaml": "added" - }, - "instance": "nonprod", - "justification": "Payments service dev namespace", - "links": { - "events": "/api/v1/requests/req-20261127-0001/events", - "self": "/api/v1/requests/req-20261127-0001" - }, - "mergeSha": null, - "namespace": "payments-dev", - "planHash": "9fed510537c2c36b3dc18a5b461ebfac4c2f1b7dfc2a61a394afd47b96624c09", - "plugin": "namespaces", - "pr": null, - "reason": null, - "requestId": "req-20261127-0001", - "requester": { - "automated": false, - "requester": { - "clientId": "cmapi-portal", - "email": "ola@ephico2real.com", - "employeeId": "1001", - "familyName": "Doe", - "givenName": "Ola", - "kind": "user", - "middleName": null, - "sub": "sub-ola", - "username": "ola" - }, - "submittedBy": null, - "submittedByClient": null - }, - "status": "approved", - "updatedAt": "2026-11-27T20:58:54.385979Z" - }, - "schema": { - "$ref": "#/components/schemas/ChangeRequest" - } - } - }, - "description": "The request is created. It waits for approval unless a policy approves it at once: `status` and `approval` say which, and `links.events` follows it." - }, - "400": { - "content": { - "application/problem+json": { - "examples": { - "idempotency-key-required": { - "value": { - "code": "idempotency-key-required", - "detail": "Idempotency-Key header is required on writes", - "status": 400, - "title": "idempotency key required", - "type": "https://cmapi.ephico2real.com/problems/idempotency-key-required" - } - } + "label": "cmapi.net/adopt", + "total": 1 }, "schema": { - "$ref": "#/components/schemas/ProblemDetail" + "$ref": "#/components/schemas/AdoptionList" } } }, - "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `idempotency-key-required`." + "description": "Each namespace that carries the opt-in label and is not a candidate, with the rule that stops it." }, "401": { "content": { @@ -14007,7 +13297,7 @@ "environment-forbidden": { "value": { "code": "environment-forbidden", - "detail": "Your roles grant namespaces:create only in ['rnd'], not dev", + "detail": "Your roles grant namespaces:write only in ['rnd'], not dev", "status": 403, "title": "environment forbidden", "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" @@ -14016,7 +13306,7 @@ "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission namespaces:create: no role in your token grants it (roles: ['cmapi-requester'])", + "detail": "Missing permission namespaces:write: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -14051,273 +13341,17 @@ }, "description": "What the path names is not known.\n\nCodes: `cluster-not-found`." }, - "409": { + "422": { "content": { "application/problem+json": { "examples": { - "change-pending": { + "validation-failed": { "value": { - "code": "change-pending", - "detail": "req-20261105-0001 holds payments-dev", - "status": 409, - "title": "change pending", - "type": "https://cmapi.ephico2real.com/problems/change-pending" - } - }, - "folder-not-utf8": { - "value": { - "code": "folder-not-utf8", - "detail": "The folder of payments-dev holds clusters/CRC/namespaces/payments-dev/caf\\xe9.yaml, whose name is not UTF-8: cmapi carries a folder's names and manifests as UTF-8 text. Rename it in Git, then send the request again", - "paths": [ - "clusters/CRC/namespaces/payments-dev/caf\\xe9.yaml" - ], - "status": 409, - "title": "folder not utf8", - "type": "https://cmapi.ephico2real.com/problems/folder-not-utf8" - } - }, - "folder-not-yaml": { - "value": { - "code": "folder-not-yaml", - "detail": "The folder of payments-dev holds clusters/CRC/namespaces/payments-dev/namespace.yaml, which is not YAML: expected ',' or '}', but got '' at line 4, column 1. Correct it in Git, then send the request again", - "paths": [ - "clusters/CRC/namespaces/payments-dev/namespace.yaml" - ], - "status": 409, - "title": "folder not yaml", - "type": "https://cmapi.ephico2real.com/problems/folder-not-yaml" - } - }, - "idempotency-replay": { - "value": { - "code": "idempotency-replay", - "detail": "Idempotency-Key was used for a different request", - "status": 409, - "title": "idempotency replay", - "type": "https://cmapi.ephico2real.com/problems/idempotency-replay" - } - }, - "namespace-exists": { - "value": { - "code": "namespace-exists", - "detail": "payments-dev is already in Git", - "status": 409, - "title": "namespace exists", - "type": "https://cmapi.ephico2real.com/problems/namespace-exists" - } - }, - "namespace-exists-unmanaged": { - "value": { - "code": "namespace-exists-unmanaged", - "detail": "payments-dev exists on the cluster and is not managed by cmapi", - "status": 409, - "title": "namespace exists unmanaged", - "type": "https://cmapi.ephico2real.com/problems/namespace-exists-unmanaged" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`, `namespace-exists`, `namespace-exists-unmanaged`." - }, - "413": { - "content": { - "application/problem+json": { - "examples": { - "content-too-large": { - "value": { - "code": "content-too-large", - "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", - "maxBytes": 1048576, - "status": 413, - "title": "content too large", - "type": "https://cmapi.ephico2real.com/problems/content-too-large" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." - }, - "422": { - "content": { - "application/problem+json": { - "examples": { - "capacity-exceeded": { - "value": { - "code": "capacity-exceeded", - "detail": "memory would exceed the cluster", - "status": 422, - "title": "capacity exceeded", - "type": "https://cmapi.ephico2real.com/problems/capacity-exceeded" - } - }, - "cluster-not-writable": { - "value": { - "code": "cluster-not-writable", - "detail": "CRC is imported but has no clusters.yaml entry", - "status": 422, - "title": "cluster not writable", - "type": "https://cmapi.ephico2real.com/problems/cluster-not-writable" - } - }, - "environment-not-served": { - "value": { - "code": "environment-not-served", - "detail": "qa is not served by the nonprod instance", - "instanceUrl": "https://cmapi-staging.ephico2real.com", - "portalUrl": "https://portal-staging.ephico2real.com", - "status": 422, - "title": "environment not served", - "type": "https://cmapi.ephico2real.com/problems/environment-not-served" - } - }, - "expiration-in-past": { - "value": { - "code": "expiration-in-past", - "detail": "The new date must be later than the current one", - "status": 422, - "title": "expiration in past", - "type": "https://cmapi.ephico2real.com/problems/expiration-in-past" - } - }, - "expiration-not-allowed": { - "value": { - "code": "expiration-not-allowed", - "detail": "Production namespaces never expire", - "status": 422, - "title": "expiration not allowed", - "type": "https://cmapi.ephico2real.com/problems/expiration-not-allowed" - } - }, - "identity-incomplete": { - "value": { - "code": "identity-incomplete", - "detail": "The token has no employee_id claim", - "status": 422, - "title": "identity incomplete", - "type": "https://cmapi.ephico2real.com/problems/identity-incomplete" - } - }, - "invalid-namespace-name": { - "value": { - "code": "invalid-namespace-name", - "detail": "Not a DNS-1123 label", - "status": 422, - "title": "invalid namespace name", - "type": "https://cmapi.ephico2real.com/problems/invalid-namespace-name" - } - }, - "on-behalf-of-not-allowed": { - "value": { - "code": "on-behalf-of-not-allowed", - "detail": "A person calls as themselves", - "status": 422, - "title": "on behalf of not allowed", - "type": "https://cmapi.ephico2real.com/problems/on-behalf-of-not-allowed" - } - }, - "on-behalf-of-required": { - "value": { - "code": "on-behalf-of-required", - "detail": "A service client must name the person", - "status": 422, - "title": "on behalf of required", - "type": "https://cmapi.ephico2real.com/problems/on-behalf-of-required" - } - }, - "placement-mismatch": { - "value": { - "code": "placement-mismatch", - "detail": "Placement pl-20261127-7658a163 was made for another target: the placement's team is 'billing', the create's 'payments'", - "status": 422, - "title": "placement mismatch", - "type": "https://cmapi.ephico2real.com/problems/placement-mismatch" - } - }, - "placement-not-found": { - "value": { - "code": "placement-not-found", - "detail": "No active placement pl-20260101-00000000: it expired, was used by another create, or never existed. Place again.", - "status": 422, - "title": "placement not found", - "type": "https://cmapi.ephico2real.com/problems/placement-not-found" - } - }, - "plugin-disabled": { - "value": { - "code": "plugin-disabled", - "detail": "The namespaces plugin takes no writes in dev on the nonprod instance: plugins.yaml disables it there", - "status": 422, - "title": "plugin disabled", - "type": "https://cmapi.ephico2real.com/problems/plugin-disabled" - } - }, - "policy-violation": { - "value": { - "code": "policy-violation", - "detail": "Metadata refused", - "errors": [ - { - "code": "invalid_value", - "detail": "must match ^[a-z0-9-]{2,40}$", - "key": "cmapi.net/team", - "kind": "label" - }, - { - "code": "missing_required_key", - "detail": "an address in ['ephico2real.com']", - "key": "cmapi.net/team-dl", - "kind": "annotation" - } - ], - "findings": [], - "status": 422, - "title": "policy violation", - "type": "https://cmapi.ephico2real.com/problems/policy-violation" - } - }, - "reserved-namespace": { - "value": { - "code": "reserved-namespace", - "detail": "kube-tools is reserved (kube-*)", - "pattern": "kube-*", - "status": 422, - "title": "reserved namespace", - "type": "https://cmapi.ephico2real.com/problems/reserved-namespace" - } - }, - "unknown-serviceaccount": { - "value": { - "code": "unknown-serviceaccount", - "detail": "ci-deployer is not a ServiceAccount of payments-dev", - "status": 422, - "title": "unknown serviceaccount", - "type": "https://cmapi.ephico2real.com/problems/unknown-serviceaccount" - } - }, - "unknown-user": { - "value": { - "code": "unknown-user", - "detail": "1009 is not an enabled user", - "status": 422, - "title": "unknown user", - "type": "https://cmapi.ephico2real.com/problems/unknown-user" - } - }, - "validation-failed": { - "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" } } }, @@ -14326,7 +13360,7 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `unknown-user`, `on-behalf-of-not-allowed`, `policy-violation`, `capacity-exceeded`, `unknown-serviceaccount`, `reserved-namespace`, `invalid-namespace-name`, `expiration-not-allowed`, `expiration-in-past`, `placement-not-found`, `placement-mismatch`." + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." }, "429": { "content": { @@ -14404,26 +13438,6 @@ "title": "idp unavailable", "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" } - }, - "validator-busy": { - "value": { - "code": "validator-busy", - "detail": "The policy check is temporarily busy. Try again after the delay in Retry-After.", - "retryAfter": 15, - "status": 503, - "title": "validator busy", - "type": "https://cmapi.ephico2real.com/problems/validator-busy" - } - }, - "validator-unavailable": { - "value": { - "code": "validator-unavailable", - "detail": "kubeconform did not start", - "retryAfter": 60, - "status": 503, - "title": "validator unavailable", - "type": "https://cmapi.ephico2real.com/problems/validator-unavailable" - } } }, "schema": { @@ -14431,7 +13445,7 @@ } } }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `cluster-unreachable`, `validator-unavailable`, `validator-busy`, `idp-unavailable`.", + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `cluster-unreachable`, `idp-unavailable`.", "headers": { "Retry-After": { "description": "The seconds to wait before the next call: the same number as `retryAfter`.", @@ -14449,27 +13463,27 @@ "keycloak": [] } ], - "summary": "Create a namespace", + "summary": "List the labelled namespaces that a rule skips", "tags": [ - "namespaces" + "adoption" ], - "x-cmapi-permission": "namespaces:create", - "x-cmapi-plugin": "namespaces", - "x-cmapi-rate-limit": "write", + "x-cmapi-permission": "namespaces:write", + "x-cmapi-plugin": "adoption", + "x-cmapi-rate-limit": "read", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'Content-Type: application/json' -d '{\"annotations\": {\"cmapi.net/team-dl\": \"payments-team@ephico2real.com\"}, \"justification\": \"Payments service dev namespace\", \"labels\": {\"cmapi.net/team\": \"payments\", \"cmapi.net/cost-center\": \"cc-4410\"}, \"namespace\": \"payments-dev\", \"tier\": \"small\"}'" + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/adoption/skipped -H \"Authorization: Bearer $TOKEN\"" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/clusters/{cluster_id}/namespaces/{ns}": { - "delete": { - "description": "Opens a delete request: the folder leaves Git after approval, every file of it at any depth, and the namespace waits\nin awaiting_prune until an operator confirms the prune. Needs If-Match, read as on a change: a list of tags passes when one\nof them is the current etag, and `*` is 428 `precondition-required`. A folder that holds a submodule is 409\n`folder-holds-submodule`: its removal would change `.gitmodules`, outside the folder.\n\n`dryRun=true` answers 200 with the plan and opens no request: `changes` lists every file of the namespace's folder, at\nany depth and whatever made it, as `removed`, `files` is empty, and `approval` is the approval that the delete would need\nnow. It makes the delete's planning checks, so they refuse it where they refuse the delete: the permission, If-Match, a\nprotected namespace (422 `namespace-protected`) and a submodule (409 `folder-holds-submodule`). Like every dry run it skips the Idempotency-Key and the namespace's lock: while\nanother request holds the namespace the plan is still 200, and the delete is 409 `change-pending`.\n\n**Requires** `namespaces:write`.", - "operationId": "namespaces_delete_namespace", + "/api/v1/clusters/{cluster_id}/capacity": { + "get": { + "description": "The stored rows of the cluster's newest complete snapshot (docs/02, \"Cluster snapshots\"): one for the cluster, one per\nzone and one per node role, each with CPU in millicores and memory in bytes. A figure that the snapshot did not measure is\nnull, never 0: with capacity.yaml `usage.source: none` the requests, limits and use are null. The worker stores a\nsnapshot every capacity.yaml `snapshotInterval`; `snapshot.state` says whether placement can use it.\n\nGateway scope (docs/02, \"Reached only through cmapi\"): capacity:read in the cluster's environment. A cluster outside the\ncaller's environments answers 404 `cluster-not-found`, as an unknown one does.\n\n**Requires** `capacity:read`.", + "operationId": "capacity_cluster_capacity", "parameters": [ { "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", @@ -14484,70 +13498,6 @@ "title": "Cluster Id", "type": "string" } - }, - { - "description": "The name of the namespace on that cluster.", - "in": "path", - "name": "ns", - "required": true, - "schema": { - "description": "The name of the namespace on that cluster.", - "examples": [ - "payments-dev" - ], - "title": "Ns", - "type": "string" - } - }, - { - "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", - "in": "query", - "name": "dryRun", - "required": false, - "schema": { - "default": false, - "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", - "examples": [ - true - ], - "title": "Dryrun", - "type": "boolean" - } - }, - { - "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state.", - "in": "header", - "name": "Idempotency-Key", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state.", - "examples": [ - "0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10" - ], - "title": "Idempotency-Key" - } - }, - { - "description": "The namespace's etag from `GET .../namespaces/{ns}`, in double quotes as its `ETag` header gives it. Required on a change or a delete. A list of tags passes when one of them is the current etag (RFC 9110, section 13.1.1). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line. `*` is 428 `precondition-required`: If-Match must name the etag that was read. A weak tag (`W/\"...\"`) never matches. An Idempotency-Key replay returns the original request in its current state without comparing the tag.", - "in": "header", - "name": "If-Match", - "required": true, - "schema": { - "description": "The namespace's etag from `GET .../namespaces/{ns}`, in double quotes as its `ETag` header gives it. Required on a change or a delete. A list of tags passes when one of them is the current etag (RFC 9110, section 13.1.1). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line. `*` is 428 `precondition-required`: If-Match must name the etag that was read. A weak tag (`W/\"...\"`) never matches. An Idempotency-Key replay returns the original request in its current state without comparing the tag.", - "examples": [ - "\"3f9a1c0b7e2d4a68\"" - ], - "title": "If-Match", - "type": "string" - } } ], "responses": { @@ -14555,197 +13505,71 @@ "content": { "application/json": { "example": { - "adoption": null, - "approval": { - "approvals": [], - "auto": null, - "autoFallback": null, - "reasons": [ - "dev delete: 1 from approver-platform" - ], - "remaining": [ - { - "group": "approver-platform", - "needed": 1 - } - ], - "rule": "dev-delete", - "selfApproval": true, - "slots": [ - { - "count": 1, - "group": "approver-platform", - "reason": "dev delete: 1 from approver-platform" - } - ], - "timeoutHours": 8 - }, - "beyondTier": null, - "capacity": { - "bindingResource": null, - "fresh": true, - "source": "delete", - "status": "fits" - }, - "changes": { - "clusters/CRC/namespaces/search-dev/limitrange-search-dev-limits-cpu.yaml": "removed", - "clusters/CRC/namespaces/search-dev/limitrange-search-dev-limits-memory.yaml": "removed", - "clusters/CRC/namespaces/search-dev/namespace.yaml": "removed", - "clusters/CRC/namespaces/search-dev/resourcequota-search-dev-quota.yaml": "removed", - "clusters/CRC/namespaces/search-dev/token-issuer-rolebinding.yaml": "removed" - }, - "etag": "2482d135c8aae7da", - "files": {}, - "findings": [], - "metadata": null, - "metadataDiff": null, - "planHash": "c490196334dad591c3196aa59224d119861392145360aee1d428c93109235dbe", - "requester": { - "automated": false, - "requester": { - "clientId": "cmapi-portal", - "email": "ola@ephico2real.com", - "employeeId": "1001", - "familyName": "Doe", - "givenName": "Ola", - "kind": "user", - "middleName": null, - "sub": "sub-ola", - "username": "ola" - }, - "submittedBy": null, - "submittedByClient": null + "clusterId": "CRC", + "env": "dev", + "intervalSeconds": 1800, + "scopes": [ + { + "cpu": { + "allocatable": 7800, + "capacity": 7800, + "limits": null, + "quotaCommitted": 48000, + "requested": null, + "unit": "millicores", + "usedAvg": null, + "usedPeak": null + }, + "memory": { + "allocatable": 20493357056, + "capacity": 20493357056, + "limits": null, + "quotaCommitted": 103079215104, + "requested": null, + "unit": "bytes", + "usedAvg": null, + "usedPeak": null + }, + "nodes": { + "diskPressure": 0, + "memoryPressure": 0, + "notReady": 0, + "schedulable": 1, + "total": 1 + }, + "pods": { + "allocatable": 250, + "running": null + }, + "scope": "cluster" + } + ], + "snapshot": { + "detail": null, + "source": "api", + "state": "ok", + "takenAt": "2026-12-01T15:00:00Z" }, - "usage": null + "staleAfterSeconds": 3600 }, "schema": { - "$ref": "#/components/schemas/PlanView" + "$ref": "#/components/schemas/ClusterSnapshot" } } }, - "description": "Dry run (`?dryRun=true`): the plan. The call opens no change request, takes no lock or reservation, queues no job and opens no pull request." + "description": "The cluster's newest complete capacity snapshot: the whole cluster, each zone and each node role, with its freshness as placement reads it." }, - "202": { + "401": { "content": { - "application/json": { - "example": { - "action": "delete", - "approval": { - "approvals": [], - "auto": null, - "autoFallback": null, - "reasons": [ - "dev delete: 1 from approver-platform" - ], - "remaining": [ - { - "group": "approver-platform", - "needed": 1 - } - ], - "rule": "dev-delete", - "selfApproval": true, - "slots": [ - { - "count": 1, - "group": "approver-platform", - "reason": "dev delete: 1 from approver-platform" - } - ], - "timeoutHours": 8 - }, - "baseSha": "479aab8dca85cfbd40e9c4c4b791535b8a69d428", - "beyondTier": null, - "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:05.959028Z", - "env": "dev", - "events": [ - { - "at": "2026-11-27T20:59:05.969036Z", - "by": "ola", - "event": "plan_needs_approval", - "note": "waiting for [('approver-platform', 1)]", - "status": "pending_approval" - } - ], - "files": { - "clusters/CRC/namespaces/search-dev/limitrange-search-dev-limits-cpu.yaml": "removed", - "clusters/CRC/namespaces/search-dev/limitrange-search-dev-limits-memory.yaml": "removed", - "clusters/CRC/namespaces/search-dev/namespace.yaml": "removed", - "clusters/CRC/namespaces/search-dev/resourcequota-search-dev-quota.yaml": "removed", - "clusters/CRC/namespaces/search-dev/token-issuer-rolebinding.yaml": "removed" - }, - "instance": "nonprod", - "justification": null, - "links": { - "events": "/api/v1/requests/req-20261127-0008/events", - "self": "/api/v1/requests/req-20261127-0008" - }, - "mergeSha": null, - "namespace": "search-dev", - "planHash": "c490196334dad591c3196aa59224d119861392145360aee1d428c93109235dbe", - "plugin": "namespaces", - "pr": null, - "reason": null, - "requestId": "req-20261127-0008", - "requester": { - "automated": false, - "requester": { - "clientId": "cmapi-portal", - "email": "ola@ephico2real.com", - "employeeId": "1001", - "familyName": "Doe", - "givenName": "Ola", - "kind": "user", - "middleName": null, - "sub": "sub-ola", - "username": "ola" - }, - "submittedBy": null, - "submittedByClient": null - }, - "status": "pending_approval", - "updatedAt": "2026-11-27T20:59:05.871308Z" - }, - "schema": { - "$ref": "#/components/schemas/ChangeRequest" - } - } - }, - "description": "The request is created. It waits for approval unless a policy approves it at once: `status` and `approval` say which, and `links.events` follows it." - }, - "400": { - "content": { - "application/problem+json": { - "examples": { - "idempotency-key-required": { - "value": { - "code": "idempotency-key-required", - "detail": "Idempotency-Key header is required on writes", - "status": 400, - "title": "idempotency key required", - "type": "https://cmapi.ephico2real.com/problems/idempotency-key-required" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `idempotency-key-required`." - }, - "401": { - "content": { - "application/problem+json": { - "examples": { - "unauthenticated": { - "value": { - "code": "unauthenticated", - "detail": "Bearer token required", - "status": 401, - "title": "unauthenticated", - "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + "application/problem+json": { + "examples": { + "unauthenticated": { + "value": { + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" } } }, @@ -14760,19 +13584,10 @@ "content": { "application/problem+json": { "examples": { - "environment-forbidden": { - "value": { - "code": "environment-forbidden", - "detail": "Your roles grant namespaces:write only in ['rnd'], not dev", - "status": 403, - "title": "environment forbidden", - "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" - } - }, "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission namespaces:write: no role in your token grants it (roles: ['cmapi-requester'])", + "detail": "Missing permission capacity:read: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -14784,7 +13599,7 @@ } } }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`, `environment-forbidden`." + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." }, "404": { "content": { @@ -14793,20 +13608,11 @@ "cluster-not-found": { "value": { "code": "cluster-not-found", - "detail": "Unknown cluster OCP_X", + "detail": "Unknown cluster NOPE", "status": 404, "title": "cluster not found", "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" } - }, - "object-not-found": { - "value": { - "code": "object-not-found", - "detail": "No request req-20261105-0001", - "status": 404, - "title": "object not found", - "type": "https://cmapi.ephico2real.com/problems/object-not-found" - } } }, "schema": { @@ -14814,64 +13620,19 @@ } } }, - "description": "What the path names is not known.\n\nCodes: `cluster-not-found`, `object-not-found`." + "description": "What the path names is not known.\n\nCodes: `cluster-not-found`." }, - "409": { + "422": { "content": { "application/problem+json": { "examples": { - "change-pending": { - "value": { - "code": "change-pending", - "detail": "req-20261105-0001 holds payments-dev", - "status": 409, - "title": "change pending", - "type": "https://cmapi.ephico2real.com/problems/change-pending" - } - }, - "folder-holds-submodule": { - "value": { - "code": "folder-holds-submodule", - "detail": "The folder of payments-dev holds the submodule clusters/CRC/namespaces/payments-dev/vendor", - "paths": [ - "clusters/CRC/namespaces/payments-dev/vendor" - ], - "status": 409, - "title": "folder holds submodule", - "type": "https://cmapi.ephico2real.com/problems/folder-holds-submodule" - } - }, - "folder-not-utf8": { - "value": { - "code": "folder-not-utf8", - "detail": "The folder of payments-dev holds clusters/CRC/namespaces/payments-dev/caf\\xe9.yaml, whose name is not UTF-8: cmapi carries a folder's names and manifests as UTF-8 text. Rename it in Git, then send the request again", - "paths": [ - "clusters/CRC/namespaces/payments-dev/caf\\xe9.yaml" - ], - "status": 409, - "title": "folder not utf8", - "type": "https://cmapi.ephico2real.com/problems/folder-not-utf8" - } - }, - "folder-not-yaml": { - "value": { - "code": "folder-not-yaml", - "detail": "The folder of payments-dev holds clusters/CRC/namespaces/payments-dev/namespace.yaml, which is not YAML: expected ',' or '}', but got '' at line 4, column 1. Correct it in Git, then send the request again", - "paths": [ - "clusters/CRC/namespaces/payments-dev/namespace.yaml" - ], - "status": 409, - "title": "folder not yaml", - "type": "https://cmapi.ephico2real.com/problems/folder-not-yaml" - } - }, - "idempotency-replay": { + "validation-failed": { "value": { - "code": "idempotency-replay", - "detail": "Idempotency-Key was used for a different request", - "status": 409, - "title": "idempotency replay", - "type": "https://cmapi.ephico2real.com/problems/idempotency-replay" + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" } } }, @@ -14880,19 +13641,20 @@ } } }, - "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`, `folder-holds-submodule`." + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." }, - "412": { + "429": { "content": { "application/problem+json": { "examples": { - "precondition-failed": { + "rate-limited": { "value": { - "code": "precondition-failed", - "detail": "The namespace changed in Git since you read it", - "status": 412, - "title": "precondition failed", - "type": "https://cmapi.ephico2real.com/problems/precondition-failed" + "code": "rate-limited", + "detail": "Too many write calls by this caller; try again in 2 s", + "retryAfter": 2, + "status": 429, + "title": "rate limited", + "type": "https://cmapi.ephico2real.com/problems/rate-limited" } } }, @@ -14901,75 +13663,119 @@ } } }, - "description": "No strong tag that If-Match lists is the object's ETag: it changed since it was read, or the value named none.\n\nCodes: `precondition-failed`." + "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } }, - "422": { + "503": { "content": { "application/problem+json": { "examples": { - "cluster-not-writable": { - "value": { - "code": "cluster-not-writable", - "detail": "CRC is imported but has no clusters.yaml entry", - "status": 422, - "title": "cluster not writable", - "type": "https://cmapi.ephico2real.com/problems/cluster-not-writable" - } - }, - "environment-not-served": { - "value": { - "code": "environment-not-served", - "detail": "qa is not served by the nonprod instance", - "instanceUrl": "https://cmapi-staging.ephico2real.com", - "portalUrl": "https://portal-staging.ephico2real.com", - "status": 422, - "title": "environment not served", - "type": "https://cmapi.ephico2real.com/problems/environment-not-served" - } - }, - "identity-incomplete": { - "value": { - "code": "identity-incomplete", - "detail": "The token has no employee_id claim", - "status": 422, - "title": "identity incomplete", - "type": "https://cmapi.ephico2real.com/problems/identity-incomplete" - } - }, - "namespace-protected": { - "value": { - "code": "namespace-protected", - "detail": "Protected namespaces cannot be deleted", - "status": 422, - "title": "namespace protected", - "type": "https://cmapi.ephico2real.com/problems/namespace-protected" - } - }, - "on-behalf-of-required": { - "value": { - "code": "on-behalf-of-required", - "detail": "A service client must name the person", - "status": 422, - "title": "on behalf of required", - "type": "https://cmapi.ephico2real.com/problems/on-behalf-of-required" - } - }, - "plugin-disabled": { + "idp-unavailable": { "value": { - "code": "plugin-disabled", - "detail": "The namespaces plugin takes no writes in dev on the nonprod instance: plugins.yaml disables it there", - "status": 422, - "title": "plugin disabled", - "type": "https://cmapi.ephico2real.com/problems/plugin-disabled" + "code": "idp-unavailable", + "detail": "Keycloak signing keys are unreachable and this key is not cached", + "retryAfter": 30, + "status": 503, + "title": "idp unavailable", + "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" } - }, - "validation-failed": { - "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + } + }, + "security": [ + { + "keycloak": [] + } + ], + "summary": "Get a cluster's capacity snapshot", + "tags": [ + "capacity" + ], + "x-cmapi-permission": "capacity:read", + "x-cmapi-plugin": "capacity", + "x-cmapi-rate-limit": "read", + "x-codeSamples": [ + { + "label": "curl", + "lang": "Shell", + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/capacity -H \"Authorization: Bearer $TOKEN\"" + } + ], + "x-plugin-version": "0.2.0" + } + }, + "/api/v1/clusters/{cluster_id}/capacity/snapshots:run": { + "post": { + "description": "Queues a snapshot of the cluster now, outside the schedule (docs/02, \"POST .../capacity/snapshots:run ... Run now\n(operations:run)\"): the worker writes the rows of the current interval again. Needs operations:run in the cluster's\nenvironment; a cluster outside it answers 404 `cluster-not-found`. plugins.yaml can stop it in an environment: 422\n`plugin-disabled`, after the permission check.\n\n**Requires** `operations:run`.", + "operationId": "capacity_run_snapshot", + "parameters": [ + { + "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", + "in": "path", + "name": "cluster_id", + "required": true, + "schema": { + "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", + "examples": [ + "CRC" + ], + "title": "Cluster Id", + "type": "string" + } + } + ], + "responses": { + "202": { + "content": { + "application/json": { + "example": { + "clusterId": "CRC", + "queued": true + }, + "schema": { + "$ref": "#/components/schemas/SnapshotRun" + } + } + }, + "description": "The run is queued: the worker writes the cluster's snapshot of the current interval again." + }, + "400": { + "content": { + "application/problem+json": { + "examples": { + "dry-run-not-supported": { + "value": { + "code": "dry-run-not-supported", + "detail": "This call has no dry run, and nothing was done", + "status": 400, + "title": "dry run not supported", + "type": "https://cmapi.ephico2real.com/problems/dry-run-not-supported" } } }, @@ -14978,19 +13784,19 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `namespace-protected`." + "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `dry-run-not-supported`." }, - "428": { + "401": { "content": { "application/problem+json": { "examples": { - "precondition-required": { + "unauthenticated": { "value": { - "code": "precondition-required", - "detail": "If-Match is required on a change", - "status": 428, - "title": "precondition required", - "type": "https://cmapi.ephico2real.com/problems/precondition-required" + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" } } }, @@ -14999,7 +13805,79 @@ } } }, - "description": "A change needs If-Match with the ETag of the object as it was read; `*` is not one.\n\nCodes: `precondition-required`." + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "forbidden": { + "value": { + "code": "forbidden", + "detail": "Missing permission operations:run: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + }, + "404": { + "content": { + "application/problem+json": { + "examples": { + "cluster-not-found": { + "value": { + "code": "cluster-not-found", + "detail": "Unknown cluster OCP_X", + "status": 404, + "title": "cluster not found", + "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "What the path names is not known.\n\nCodes: `cluster-not-found`." + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "plugin-disabled": { + "value": { + "code": "plugin-disabled", + "detail": "The namespaces plugin takes no writes in dev on the nonprod instance: plugins.yaml disables it there", + "status": 422, + "title": "plugin disabled", + "type": "https://cmapi.ephico2real.com/problems/plugin-disabled" + } + }, + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `plugin-disabled`, `validation-failed`." }, "429": { "content": { @@ -15033,41 +13911,10 @@ } } }, - "502": { - "content": { - "application/problem+json": { - "examples": { - "git-unavailable": { - "value": { - "code": "git-unavailable", - "detail": "The Git host answered 500", - "status": 502, - "title": "git unavailable", - "type": "https://cmapi.ephico2real.com/problems/git-unavailable" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The Git host failed.\n\nCodes: `git-unavailable`." - }, "503": { "content": { "application/problem+json": { "examples": { - "cluster-unreachable": { - "value": { - "code": "cluster-unreachable", - "detail": "CRC did not answer", - "retryAfter": 30, - "status": 503, - "title": "cluster unreachable", - "type": "https://cmapi.ephico2real.com/problems/cluster-unreachable" - } - }, "idp-unavailable": { "value": { "code": "idp-unavailable", @@ -15084,7 +13931,7 @@ } } }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `cluster-unreachable`, `idp-unavailable`.", + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", "headers": { "Retry-After": { "description": "The seconds to wait before the next call: the same number as `retryAfter`.", @@ -15102,25 +13949,27 @@ "keycloak": [] } ], - "summary": "Delete a namespace", + "summary": "Run a cluster's capacity snapshot now", "tags": [ - "namespaces" + "capacity" ], - "x-cmapi-permission": "namespaces:write", - "x-cmapi-plugin": "namespaces", + "x-cmapi-permission": "operations:run", + "x-cmapi-plugin": "capacity", "x-cmapi-rate-limit": "write", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X DELETE https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'If-Match: \"3f9a1c0b7e2d4a68\"'" + "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/capacity/snapshots:run -H \"Authorization: Bearer $TOKEN\"" } ], "x-plugin-version": "0.2.0" - }, + } + }, + "/api/v1/clusters/{cluster_id}/namespaces": { "get": { - "description": "The live namespace and the etag of its folder in Git. Send the etag as If-Match on PATCH or DELETE (the `ETag`\nheader has the same value).\n\n`labels` and `annotations` are the live ones, from the watch cache. `git` is the folder's labels and annotations, the\ndesired state, from the same read as the etag. Its `edits` give `x-cmapi-edit` of each key of Git that\nmetadata-keys.yaml does not declare, so a form can lock it or offer its removal: `mode`, the `reason` to show,\n`sensitive`, and `removable` for a key that no rule admits, which a change may remove and never set (#484). An\noperator-only key's reason names this cluster's environment (#532). The other keys' `x-cmapi-edit` are in\n`GET /api/v1/metadata-keys`. Its `missingKeys` list each declared key that Git lacks, as an adopted namespace may, which a\nchange can add, with the one value of a key that cmapi fills in or that starts the name (#732, #739). `sync` compares Git with the live namespace (#481): `pending` while a request holds it,\n`drift` when a governed, extra or operator-only key differs (each in `driftedKeys`), `in-sync` when none does, and\n`unknown` when the cluster's watch is not fresh.\n\n**Requires** `objects:read`.", - "operationId": "namespaces_get_namespace", + "description": "Every namespace labelled cmapi.net/managed=true on the cluster, from the watch cache, with the request\nholding each one's lock. The etag is only on the single-namespace read, because it comes from Git.\n\nThe lookup after a cluster is chosen (#481): `q` matches the name, the team label and the app label, names that\nstart with it first, then names that contain it, then team and app matches; `mnemonic` keeps one mnemonic's\nnamespaces; `limit` caps the answer. `total` counts every match before the cap, and `facets.mnemonics` the\nnamespaces of each mnemonic. Each item's `sync` is `pending` when a request holds it and `unknown` otherwise: the\nlist reads no Git, so it compares nothing. With none of the three parameters the list is every namespace by name.\n\n**Requires** `objects:read`.", + "operationId": "namespaces_list_namespaces", "parameters": [ { "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", @@ -15137,17 +13986,69 @@ } }, { - "description": "The name of the namespace on that cluster.", - "in": "path", - "name": "ns", - "required": true, + "description": "Text that the name, the team label or the app label contains. Case does not matter. Names that start with it come first.", + "in": "query", + "name": "q", + "required": false, "schema": { - "description": "The name of the namespace on that cluster.", + "anyOf": [ + { + "maxLength": 63, + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Text that the name, the team label or the app label contains. Case does not matter. Names that start with it come first.", "examples": [ - "payments-dev" + "pay" ], - "title": "Ns", - "type": "string" + "title": "Q" + } + }, + { + "description": "Only the namespaces of this mnemonic: the value of the key that starts the namespace name (`namespacePrefix` of metadata-keys.yaml).", + "in": "query", + "name": "mnemonic", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only the namespaces of this mnemonic: the value of the key that starts the namespace name (`namespacePrefix` of metadata-keys.yaml).", + "examples": [ + "abc" + ], + "title": "Mnemonic" + } + }, + { + "description": "The most namespaces to return: 10 when `q` or `mnemonic` is sent without it, at most 50. With none of the three, every namespace is returned, by name.", + "in": "query", + "name": "limit", + "required": false, + "schema": { + "anyOf": [ + { + "maximum": 50, + "minimum": 1, + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "The most namespaces to return: 10 when `q` or `mnemonic` is sent without it, at most 50. With none of the three, every namespace is returned, by name.", + "examples": [ + 10 + ], + "title": "Limit" } } ], @@ -15156,149 +14057,55 @@ "content": { "application/json": { "example": { - "annotations": { - "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", - "cmapi.net/instance": "nonprod", - "cmapi.net/request-id": "req-20261127-0001", - "cmapi.net/requested-by": "ola@ephico2real.com", - "cmapi.net/team-dl": "payments-team@ephico2real.com" + "facets": { + "mnemonics": {} }, - "clusterId": "CRC", - "env": "dev", - "etag": "d71165fa38f59dd4", - "expiresAt": null, - "git": { - "annotations": { - "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", - "cmapi.net/instance": "nonprod", - "cmapi.net/request-id": "req-20261127-0001", - "cmapi.net/requested-by": "ola@ephico2real.com", - "cmapi.net/team-dl": "payments-team@ephico2real.com" - }, - "edits": { + "items": [ + { "annotations": { - "argocd.argoproj.io/sync-options": { - "mode": "fixed", - "reason": "Reserved for the platform.", - "removable": false, - "sensitive": false - }, - "cmapi.net/instance": { - "mode": "fixed", - "reason": "Managed by cmapi.", - "removable": false, - "sensitive": false - }, - "cmapi.net/request-id": { - "mode": "fixed", - "reason": "Managed by cmapi.", - "removable": false, - "sensitive": false - }, - "cmapi.net/requested-by": { - "mode": "fixed", - "reason": "Managed by cmapi.", - "removable": false, - "sensitive": false - } + "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", + "cmapi.net/instance": "nonprod", + "cmapi.net/request-id": "req-20261201-0001", + "cmapi.net/requested-by": "ola@ephico2real.com", + "cmapi.net/team-dl": "payments-team@ephico2real.com" }, + "clusterId": "CRC", + "env": "dev", + "etag": null, + "expiresAt": null, + "git": null, "labels": { - "cmapi.net/cluster-id": { - "mode": "fixed", - "reason": "Managed by cmapi.", - "removable": false, - "sensitive": false - }, - "cmapi.net/env": { - "mode": "fixed", - "reason": "Managed by cmapi.", - "removable": false, - "sensitive": false - }, - "cmapi.net/managed": { - "mode": "fixed", - "reason": "Managed by cmapi.", - "removable": false, - "sensitive": false - }, - "cmapi.net/requested-by-user": { - "mode": "fixed", - "reason": "Managed by cmapi.", - "removable": false, - "sensitive": false - }, - "cmapi.net/tier": { - "mode": "fixed", - "reason": "Managed by cmapi.", - "removable": false, - "sensitive": false - } - } - }, - "labels": { - "cmapi.net/cluster-id": "CRC", - "cmapi.net/cost-center": "cc-4410", - "cmapi.net/env": "dev", - "cmapi.net/managed": "true", - "cmapi.net/requested-by-user": "ola", - "cmapi.net/team": "payments", - "cmapi.net/tier": "small" - }, - "missingKeys": [ - { - "key": "cmapi.net/app", - "kind": "label", - "required": false, - "value": null + "cmapi.net/cluster-id": "CRC", + "cmapi.net/cost-center": "cc-4410", + "cmapi.net/env": "dev", + "cmapi.net/managed": "true", + "cmapi.net/requested-by-user": "ola", + "cmapi.net/team": "payments", + "cmapi.net/tier": "small" }, - { - "key": "cmapi.net/rightsizing", - "kind": "label", - "required": false, - "value": null - } - ] - }, - "labels": { - "cmapi.net/cluster-id": "CRC", - "cmapi.net/cost-center": "cc-4410", - "cmapi.net/env": "dev", - "cmapi.net/managed": "true", - "cmapi.net/requested-by-user": "ola", - "cmapi.net/team": "payments", - "cmapi.net/tier": "small" - }, - "managed": true, - "mnemonic": null, - "name": "payments-dev", - "openRequest": null, - "protected": false, - "protectedBy": [], - "sync": { - "driftedKeys": [], - "openRequest": null, - "state": "in-sync" - }, - "team": "payments", - "tier": "small" + "managed": true, + "mnemonic": null, + "name": "payments-dev", + "openRequest": null, + "protected": null, + "protectedBy": null, + "sync": { + "driftedKeys": [], + "openRequest": null, + "state": "unknown" + }, + "team": "payments", + "tier": "small" + } + ], + "total": 1 }, "schema": { - "$ref": "#/components/schemas/NamespaceView" + "$ref": "#/components/schemas/NamespaceList" } } }, - "description": "The namespace's labels, annotations, tier and sync state as Git and the cluster hold them, with the ETag that a change sends in If-Match.", - "headers": { - "ETag": { - "description": "The namespace's entity tag, quoted: the `etag` of the body. Send it unchanged as `If-Match` on a change or a delete. It changes when the `.yaml` files directly in the namespace's folder in Git change.", - "schema": { - "examples": [ - "\"3f9a1c0b7e2d4a68\"" - ], - "type": "string" - } - } - } + "description": "The managed namespaces of the cluster that match the filters, with their count and the facets." }, "401": { "content": { @@ -15363,15 +14170,6 @@ "title": "cluster not found", "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" } - }, - "object-not-found": { - "value": { - "code": "object-not-found", - "detail": "not-there-dev is not on CRC and not in Git", - "status": 404, - "title": "object not found", - "type": "https://cmapi.ephico2real.com/problems/object-not-found" - } } }, "schema": { @@ -15379,55 +14177,26 @@ } } }, - "description": "What the path names is not known.\n\nCodes: `cluster-not-found`, `object-not-found`." + "description": "What the path names is not known.\n\nCodes: `cluster-not-found`." }, - "409": { + "422": { "content": { "application/problem+json": { "examples": { - "folder-not-utf8": { + "validation-failed": { "value": { - "code": "folder-not-utf8", - "detail": "The folder of payments-dev holds clusters/CRC/namespaces/payments-dev/caf\\xe9.yaml, whose name is not UTF-8: cmapi carries a folder's names and manifests as UTF-8 text. Rename it in Git, then send the request again", - "paths": [ - "clusters/CRC/namespaces/payments-dev/caf\\xe9.yaml" + "code": "validation-failed", + "detail": "The request is not valid: query.limit: Input should be greater than or equal to 1", + "errors": [ + { + "code": "greater_than_equal", + "field": "query.limit", + "message": "Input should be greater than or equal to 1" + } ], - "status": 409, - "title": "folder not utf8", - "type": "https://cmapi.ephico2real.com/problems/folder-not-utf8" - } - }, - "folder-not-yaml": { - "value": { - "code": "folder-not-yaml", - "detail": "The folder of payments-dev holds clusters/CRC/namespaces/payments-dev/namespace.yaml, which is not YAML: expected ',' or '}', but got '' at line 4, column 1. Correct it in Git, then send the request again", - "paths": [ - "clusters/CRC/namespaces/payments-dev/namespace.yaml" - ], - "status": 409, - "title": "folder not yaml", - "type": "https://cmapi.ephico2real.com/problems/folder-not-yaml" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `folder-not-utf8`, `folder-not-yaml`." - }, - "422": { - "content": { - "application/problem+json": { - "examples": { - "validation-failed": { - "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" } } }, @@ -15470,31 +14239,20 @@ } } }, - "502": { + "503": { "content": { "application/problem+json": { "examples": { - "git-unavailable": { + "cluster-unreachable": { "value": { - "code": "git-unavailable", - "detail": "The Git host answered 500", - "status": 502, - "title": "git unavailable", - "type": "https://cmapi.ephico2real.com/problems/git-unavailable" + "code": "cluster-unreachable", + "detail": "CRC did not answer", + "retryAfter": 30, + "status": 503, + "title": "cluster unreachable", + "type": "https://cmapi.ephico2real.com/problems/cluster-unreachable" } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The Git host failed.\n\nCodes: `git-unavailable`." - }, - "503": { - "content": { - "application/problem+json": { - "examples": { + }, "idp-unavailable": { "value": { "code": "idp-unavailable", @@ -15511,7 +14269,7 @@ } } }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `cluster-unreachable`, `idp-unavailable`.", "headers": { "Retry-After": { "description": "The seconds to wait before the next call: the same number as `retryAfter`.", @@ -15529,7 +14287,7 @@ "keycloak": [] } ], - "summary": "Get a namespace and its ETag", + "summary": "List managed namespaces on a cluster", "tags": [ "namespaces" ], @@ -15540,14 +14298,14 @@ { "label": "curl", "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces -H \"Authorization: Bearer $TOKEN\"" } ], "x-plugin-version": "0.2.0" }, - "patch": { - "description": "Changes a namespace that exists: its tier, its custom quota and limits, and its labels and annotations.\n\n**Merge patch.** `labels` and `annotations` follow JSON Merge Patch (RFC 7396, https://www.rfc-editor.org/rfc/rfc7396):\na key that the body leaves out keeps its value, a string sets it, and `null` removes it. `x-cmapi-edit` of each key,\nin `GET /api/v1/metadata-keys` and, for the keys that file does not declare, in `git.edits` of the namespace's read,\nsays how it may change: `fixed` (the value in Git stays; the same value sent back is accepted; a missing key that\nstarts the name can be added with that start), `automatic` (filled at creation; a change keeps Git's value, and a request\ncan add a missing one with the derived value), `required` (it changes and is never removed) or `optional`. A key that no\nrule admits can be removed, never set. A `sensitive` key adds one approval to the request.\n\n**Check, then submit.** With `dryRun=true` the answer is 200 with the plan, and no request is opened. `metadataDiff`\nlists each effective change by key as `before`, `after` and `source`: `before` is `null` when the key is added, `after`\nis `null` when it is removed. The same body without `dryRun`, with an Idempotency-Key, opens the request (202).\n\n**If-Match.** Send the ETag of `GET .../namespaces/{ns}` as If-Match (RFC 9110, section 13.1.1). For a new plan,\na namespace missing from Git is 404 `object-not-found` before the precondition checks. For an existing namespace,\nmissing If-Match is 428 `precondition-required` (RFC 6585, section 3), and so is `*`: it proves no read, so cmapi\nrefuses it on purpose, where RFC 9110 lets it match any namespace that exists. A list of tags, sent in one If-Match\nfield, passes when one of them is the current etag, by the strong comparison, so a weak tag (`W/\"...\"`) never matches.\nOtherwise the answer is 412 `precondition-failed` (RFC 9110, section 15.5.13) with the current `etag`: read the\nnamespace again, apply the change to it and send it.\nAn Idempotency-Key replay still requires If-Match, but does not compare it again: it returns the\noriginal request in its current state even after Git moves, and `*` is 428 there too. The Idempotency-Key parameter\nsays when a retry is a replay. A non-dry-run submission also requires Idempotency-Key (400 without it).\nOne request at a time holds a namespace: while another is open, 409 `change-pending` names it in `requestId`.\n\n**Refusals.** 422 `policy-violation` has one `errors` entry for each key that breaks a rule (`reserved_key`,\n`invalid_key`, `invalid_value`, `derived_key`, `missing_required_key`, `too_many_keys`, `annotations_too_large`).\nA key that only an operator may change is 403 `forbidden` without `namespaces:protect` in the namespace's\nenvironment. A body that changes nothing is 422 `no-change`.\n\n**Several ResourceQuotas.** cmapi changes only its own ResourceQuota (`-quota`) and LimitRanges (`-limits-*`);\nevery other one in the folder is kept as Git holds it, each in its own file (#250). When the folder holds several\nResourceQuotas, a change of `quota` or `tier` is 409 `several-resource-quotas`, which names them in `resourceQuotas`: the\nrequest cannot say which one it changes. When none of them is `-quota`, a change of `limitRange` is refused too, and\na change of labels, annotations or the expiry keeps every ResourceQuota and LimitRange.\n\n**Requires** `namespaces:write`.", - "operationId": "namespaces_update_namespace", + "post": { + "description": "Plans a new namespace on the cluster and submits a change request; the bot opens a pull request once it\nis approved. `dryRun=true` answers 200 with the plan, the capacity check and the approval that would apply,\nand opens no request. The environment is the cluster's and must be one this instance serves.\n\n**Requires** `namespaces:create`.", + "operationId": "namespaces_create_namespace", "parameters": [ { "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", @@ -15563,20 +14321,6 @@ "type": "string" } }, - { - "description": "The name of the namespace on that cluster.", - "in": "path", - "name": "ns", - "required": true, - "schema": { - "description": "The name of the namespace on that cluster.", - "examples": [ - "payments-dev" - ], - "title": "Ns", - "type": "string" - } - }, { "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", "in": "query", @@ -15612,49 +14356,46 @@ ], "title": "Idempotency-Key" } - }, - { - "description": "The namespace's etag from `GET .../namespaces/{ns}`, in double quotes as its `ETag` header gives it. Required on a change or a delete. A list of tags passes when one of them is the current etag (RFC 9110, section 13.1.1). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line. `*` is 428 `precondition-required`: If-Match must name the etag that was read. A weak tag (`W/\"...\"`) never matches. An Idempotency-Key replay returns the original request in its current state without comparing the tag.", - "in": "header", - "name": "If-Match", - "required": true, - "schema": { - "description": "The namespace's etag from `GET .../namespaces/{ns}`, in double quotes as its `ETag` header gives it. Required on a change or a delete. A list of tags passes when one of them is the current etag (RFC 9110, section 13.1.1). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line. `*` is 428 `precondition-required`: If-Match must name the etag that was read. A weak tag (`W/\"...\"`) never matches. An Idempotency-Key replay returns the original request in its current state without comparing the tag.", - "examples": [ - "\"3f9a1c0b7e2d4a68\"" - ], - "title": "If-Match", - "type": "string" - } } ], "requestBody": { "content": { "application/json": { "examples": { - "mergePatch": { - "summary": "Change labels and annotations: a value sets a key, null removes it (add dryRun=true to check)", + "permanent": { + "summary": "Permanent namespace", "value": { "annotations": { - "runbook.ephico2real.com/url": "https://wiki.ephico2real.com/payments/runbook" + "cmapi.net/team-dl": "payments-team@ephico2real.com" }, - "justification": "A smaller size after the load test, with the metadata tidied", + "justification": "Payments service dev namespace", "labels": { - "cmapi.net/cost-center": null + "cmapi.net/cost-center": "cc-4410", + "cmapi.net/team": "payments" }, - "tier": "medium" + "namespace": "payments-dev", + "tier": "small" } }, - "tier": { - "summary": "Change the tier", + "withExpiry": { + "summary": "With expiration (choose a future date when sending)", "value": { - "justification": "Load test next sprint", - "tier": "large" + "annotations": { + "cmapi.net/team-dl": "payments-team@ephico2real.com" + }, + "expiresAt": "2026-12-15", + "justification": "Payments service dev namespace", + "labels": { + "cmapi.net/cost-center": "cc-4410", + "cmapi.net/team": "payments" + }, + "namespace": "payments-dev", + "tier": "small" } } }, "schema": { - "$ref": "#/components/schemas/NamespacePatch" + "$ref": "#/components/schemas/NamespaceCreate" } } }, @@ -15668,24 +14409,71 @@ "adoption": null, "approval": { "approvals": [], - "auto": "none-required", + "auto": null, "autoFallback": null, "reasons": [ - "dev change: 0 from approver-platform" + "dev create: 1 from approver-platform", + "threshold beyondTier: +1 approver-platform" ], - "remaining": [], - "rule": "dev-change", + "remaining": [ + { + "group": "approver-platform", + "needed": 2 + } + ], + "rule": "dev-create", "selfApproval": true, - "slots": [], + "slots": [ + { + "count": 2, + "group": "approver-platform", + "reason": "dev create: 1 from approver-platform; Value beyond the tier" + } + ], "timeoutHours": 8 }, - "beyondTier": null, + "beyondTier": { + "approvals": [ + { + "count": 1, + "group": "approver-platform", + "reason": "Value beyond the tier" + } + ], + "keys": [ + { + "key": "limitRange.container.default.cpu", + "requested": "1", + "tier": "500m" + }, + { + "key": "limitRange.container.default.memory", + "requested": "1Gi", + "tier": "512Mi" + }, + { + "key": "limitRange.container.max.cpu", + "requested": "4", + "tier": "2" + }, + { + "key": "limitRange.container.max.memory", + "requested": "8Gi", + "tier": "4Gi" + }, + { + "key": "requests.storage", + "requested": "500Gi", + "tier": "200Gi" + } + ] + }, "capacity": { "bindingResource": "cpu", "clusterId": "CRC", - "cpu": 0.125, + "cpu": 0.031, "fresh": true, - "memory": 0.1, + "memory": 0.025, "reserved": { "cpu": 0.0, "memory": 0 @@ -15694,37 +14482,42 @@ "status": "fits" }, "changes": { - "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "changed", - "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "changed", - "clusters/CRC/namespaces/payments-dev/namespace.yaml": "changed", - "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "changed" + "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "added", + "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "added", + "clusters/CRC/namespaces/payments-dev/namespace.yaml": "added", + "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "added", + "clusters/CRC/namespaces/payments-dev/token-issuer-rolebinding.yaml": "added" }, - "etag": "d71165fa38f59dd4", + "etag": "0", "files": { - "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-cpu\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: medium\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 44fd85f2d7cb\nspec:\n limits:\n - type: Container\n defaultRequest:\n cpu: 100m\n default:\n cpu: 500m\n max:\n cpu: '4'\n", - "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-memory\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: medium\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 44fd85f2d7cb\nspec:\n limits:\n - type: Container\n defaultRequest:\n memory: 256Mi\n default:\n memory: 512Mi\n max:\n memory: 8Gi\n", - "clusters/CRC/namespaces/payments-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: medium\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n runbook.ephico2real.com/url: https://wiki.ephico2real.com/payments/runbook\n", - "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "apiVersion: v1\nkind: ResourceQuota\nmetadata:\n name: payments-dev-quota\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: medium\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 44fd85f2d7cb\nspec:\n hard:\n requests.cpu: '16'\n requests.memory: 32Gi\n pods: '100'\n persistentvolumeclaims: '30'\n requests.storage: 500Gi\n services.loadbalancers: '0'\n services.nodeports: '0'\n" + "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-cpu\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: custom\n annotations:\n cmapi.net/beyond-tier: limitRange.container.default.cpu,limitRange.container.max.cpu\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 77ae5f8f5ddd\nspec:\n limits:\n - type: Container\n defaultRequest:\n cpu: 100m\n default:\n cpu: '1'\n max:\n cpu: '4'\n", + "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-memory\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: custom\n annotations:\n cmapi.net/beyond-tier: limitRange.container.default.memory,limitRange.container.max.memory\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 77ae5f8f5ddd\nspec:\n limits:\n - type: Container\n defaultRequest:\n memory: 256Mi\n default:\n memory: 1Gi\n max:\n memory: 8Gi\n", + "clusters/CRC/namespaces/payments-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: custom\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n", + "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "apiVersion: v1\nkind: ResourceQuota\nmetadata:\n name: payments-dev-quota\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: custom\n annotations:\n cmapi.net/beyond-tier: requests.storage\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 77ae5f8f5ddd\nspec:\n hard:\n requests.cpu: '4'\n requests.memory: 8Gi\n pods: '20'\n persistentvolumeclaims: '20'\n requests.storage: 500Gi\n services.loadbalancers: '0'\n services.nodeports: '0'\n", + "clusters/CRC/namespaces/payments-dev/token-issuer-rolebinding.yaml": "apiVersion: rbac.authorization.k8s.io/v1\nkind: RoleBinding\nmetadata:\n name: cmapi-token-issuer\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\nroleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: ClusterRole\n name: cmapi-token-issuer\nsubjects:\n- kind: ServiceAccount\n name: cmapi-reader\n namespace: cmapi-system\n" }, "findings": [], - "metadata": null, - "metadataDiff": { + "metadata": { "annotations": { - "runbook.ephico2real.com/url": { - "after": "https://wiki.ephico2real.com/payments/runbook", - "before": null, - "source": "request" + "cmapi.net/team-dl": { + "source": "request", + "value": "payments-team@ephico2real.com" } }, "labels": { "cmapi.net/cost-center": { - "after": null, - "before": "cc-4410", - "source": "request" + "source": "request", + "value": "cc-4410" + }, + "cmapi.net/team": { + "source": "request", + "value": "payments" } - } + }, + "namespace": "payments-dev" }, - "planHash": "13472056b96785ab1172af6108e4ab3bda9d07c0663fd117bcb98fe6d7c3c4d8", + "metadataDiff": null, + "planHash": "581590b32816a9c0d6951dbf13ba41816b2bf074eeb6017bcbf8fc3557906a75", "requester": { "automated": false, "requester": { @@ -15741,35 +14534,7 @@ "submittedBy": null, "submittedByClient": null }, - "usage": { - "coverage": null, - "cpu": { - "avg7d": null, - "newOverPeak": null, - "newQuota": 16000, - "now": null, - "p95": null, - "peak": null, - "quota": 8000 - }, - "evaluatedAt": null, - "memory": { - "avg7d": null, - "newOverPeak": null, - "newQuota": 34359738368, - "now": null, - "p95": null, - "peak": null, - "quota": 17179869184 - }, - "reason": "No usage source is configured on this instance (capacity.yaml usage.source is none), so there is no 14-day usage.", - "state": "insufficient-data", - "units": { - "cpu": "millicores", - "memory": "bytes" - }, - "window": "14d" - } + "usage": null }, "schema": { "$ref": "#/components/schemas/PlanView" @@ -15782,66 +14547,55 @@ "content": { "application/json": { "example": { - "action": "update", + "action": "create", "approval": { "approvals": [], - "auto": null, + "auto": "auto:baseline-rnd-namespace", "autoFallback": null, "reasons": [ - "dev change: 0 from approver-platform", - "threshold quotaIncreasePct > 100: +1 approver-platform" - ], - "remaining": [ - { - "group": "approver-platform", - "needed": 1 - } + "dev create: 1 from approver-platform", + "auto-approved by policy baseline-rnd-namespace" ], - "rule": "dev-change", + "remaining": [], + "rule": "dev-create", "selfApproval": true, - "slots": [ - { - "count": 1, - "group": "approver-platform", - "reason": "quotaIncreasePct > 100" - } - ], + "slots": [], "timeoutHours": 8 }, - "baseSha": "80f4f1badad17a36a1e6c5d25834f76fef11435b", + "baseSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:55.923726Z", + "createdAt": "2026-12-01T15:12:55.670320Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:56.005112Z", + "at": "2026-12-01T15:12:55.724895Z", "by": "ola", - "event": "plan_needs_approval", - "note": "waiting for [('approver-platform', 1)]", - "status": "pending_approval" + "event": "plan_auto_approved", + "note": "auto:baseline-rnd-namespace", + "status": "approved" } ], "files": { - "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "changed", - "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "changed", - "clusters/CRC/namespaces/payments-dev/namespace.yaml": "changed", - "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "changed", - "clusters/CRC/namespaces/payments-dev/token-issuer-rolebinding.yaml": "unchanged" + "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "added", + "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "added", + "clusters/CRC/namespaces/payments-dev/namespace.yaml": "added", + "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "added", + "clusters/CRC/namespaces/payments-dev/token-issuer-rolebinding.yaml": "added" }, "instance": "nonprod", - "justification": "Load test next sprint", + "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0002/events", - "self": "/api/v1/requests/req-20261127-0002" + "events": "/api/v1/requests/req-20261201-0001/events", + "self": "/api/v1/requests/req-20261201-0001" }, "mergeSha": null, "namespace": "payments-dev", - "planHash": "df5602a2038007a6de28e19adf060fd6b5f8fb3d5b86637f790b31efdc510039", + "planHash": "4e9af3fc1f212f0387b6958adccca82242cc53b7fd67192be64529da18a31563", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0002", + "requestId": "req-20261201-0001", "requester": { "automated": false, "requester": { @@ -15858,8 +14612,8 @@ "submittedBy": null, "submittedByClient": null }, - "status": "pending_approval", - "updatedAt": "2026-11-27T20:58:55.904486Z" + "status": "approved", + "updatedAt": "2026-12-01T15:12:55.450056Z" }, "schema": { "$ref": "#/components/schemas/ChangeRequest" @@ -15917,7 +14671,7 @@ "environment-forbidden": { "value": { "code": "environment-forbidden", - "detail": "Your roles grant namespaces:write only in ['rnd'], not dev", + "detail": "Your roles grant namespaces:create only in ['rnd'], not dev", "status": 403, "title": "environment forbidden", "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" @@ -15926,7 +14680,7 @@ "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission namespaces:write: no role in your token grants it (roles: ['cmapi-approver'])", + "detail": "Missing permission namespaces:create: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -15947,20 +14701,11 @@ "cluster-not-found": { "value": { "code": "cluster-not-found", - "detail": "Unknown cluster NOPE", + "detail": "Unknown cluster OCP_X", "status": 404, "title": "cluster not found", "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" } - }, - "object-not-found": { - "value": { - "code": "object-not-found", - "detail": "not-there-dev is not managed on CRC", - "status": 404, - "title": "object not found", - "type": "https://cmapi.ephico2real.com/problems/object-not-found" - } } }, "schema": { @@ -15968,7 +14713,7 @@ } } }, - "description": "What the path names is not known.\n\nCodes: `cluster-not-found`, `object-not-found`." + "description": "What the path names is not known.\n\nCodes: `cluster-not-found`." }, "409": { "content": { @@ -15977,8 +14722,7 @@ "change-pending": { "value": { "code": "change-pending", - "detail": "req-20261127-0015 holds audit-dev", - "requestId": "req-20261127-0015", + "detail": "req-20261105-0001 holds payments-dev", "status": 409, "title": "change pending", "type": "https://cmapi.ephico2real.com/problems/change-pending" @@ -16012,45 +14756,27 @@ "value": { "code": "idempotency-replay", "detail": "Idempotency-Key was used for a different request", - "requestId": "req-20261127-0015", "status": 409, "title": "idempotency replay", "type": "https://cmapi.ephico2real.com/problems/idempotency-replay" } }, - "several-resource-quotas": { + "namespace-exists": { "value": { - "code": "several-resource-quotas", - "detail": "The folder of payments-dev holds 2 ResourceQuotas, payments-dev-objects, payments-dev-quota: a change of the quota or the tier must name the object it changes, and a request cannot name one. Change only labels, annotations or the expiry, or leave one ResourceQuota in the folder in Git, then send the request again", - "resourceQuotas": [ - "payments-dev-objects", - "payments-dev-quota" - ], + "code": "namespace-exists", + "detail": "payments-dev is already in Git", "status": 409, - "title": "several resource quotas", - "type": "https://cmapi.ephico2real.com/problems/several-resource-quotas" + "title": "namespace exists", + "type": "https://cmapi.ephico2real.com/problems/namespace-exists" } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`, `several-resource-quotas`." - }, - "412": { - "content": { - "application/problem+json": { - "examples": { - "precondition-failed": { + }, + "namespace-exists-unmanaged": { "value": { - "code": "precondition-failed", - "detail": "The namespace changed in Git since you read it", - "etag": "d71165fa38f59dd4", - "status": 412, - "title": "precondition failed", - "type": "https://cmapi.ephico2real.com/problems/precondition-failed" + "code": "namespace-exists-unmanaged", + "detail": "payments-dev exists on the cluster and is not managed by cmapi", + "status": 409, + "title": "namespace exists unmanaged", + "type": "https://cmapi.ephico2real.com/problems/namespace-exists-unmanaged" } } }, @@ -16059,7 +14785,7 @@ } } }, - "description": "No strong tag that If-Match lists is the object's ETag: it changed since it was read, or the value named none.\n\nCodes: `precondition-failed`." + "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`, `namespace-exists`, `namespace-exists-unmanaged`." }, "413": { "content": { @@ -16116,6 +14842,24 @@ "type": "https://cmapi.ephico2real.com/problems/environment-not-served" } }, + "expiration-in-past": { + "value": { + "code": "expiration-in-past", + "detail": "The new date must be later than the current one", + "status": 422, + "title": "expiration in past", + "type": "https://cmapi.ephico2real.com/problems/expiration-in-past" + } + }, + "expiration-not-allowed": { + "value": { + "code": "expiration-not-allowed", + "detail": "Production namespaces never expire", + "status": 422, + "title": "expiration not allowed", + "type": "https://cmapi.ephico2real.com/problems/expiration-not-allowed" + } + }, "identity-incomplete": { "value": { "code": "identity-incomplete", @@ -16125,13 +14869,13 @@ "type": "https://cmapi.ephico2real.com/problems/identity-incomplete" } }, - "no-change": { + "invalid-namespace-name": { "value": { - "code": "no-change", - "detail": "The request changes nothing", + "code": "invalid-namespace-name", + "detail": "Not a DNS-1123 label", "status": 422, - "title": "no change", - "type": "https://cmapi.ephico2real.com/problems/no-change" + "title": "invalid namespace name", + "type": "https://cmapi.ephico2real.com/problems/invalid-namespace-name" } }, "on-behalf-of-not-allowed": { @@ -16152,6 +14896,24 @@ "type": "https://cmapi.ephico2real.com/problems/on-behalf-of-required" } }, + "placement-mismatch": { + "value": { + "code": "placement-mismatch", + "detail": "Placement pl-20261201-52bb3c04 was made for another target: the placement's team is 'billing', the create's 'payments'", + "status": 422, + "title": "placement mismatch", + "type": "https://cmapi.ephico2real.com/problems/placement-mismatch" + } + }, + "placement-not-found": { + "value": { + "code": "placement-not-found", + "detail": "No active placement pl-20260101-00000000: it expired, was used by another create, or never existed. Place again.", + "status": 422, + "title": "placement not found", + "type": "https://cmapi.ephico2real.com/problems/placement-not-found" + } + }, "plugin-disabled": { "value": { "code": "plugin-disabled", @@ -16166,15 +14928,6 @@ "code": "policy-violation", "detail": "Metadata refused", "errors": [ - { - "code": "reserved_key", - "key": "cmapi.net/tier" - }, - { - "code": "invalid_key", - "detail": "prefix not allowed", - "key": "other.example/x" - }, { "code": "invalid_value", "detail": "must match ^[a-z0-9-]{2,40}$", @@ -16194,6 +14947,16 @@ "type": "https://cmapi.ephico2real.com/problems/policy-violation" } }, + "reserved-namespace": { + "value": { + "code": "reserved-namespace", + "detail": "kube-tools is reserved (kube-*)", + "pattern": "kube-*", + "status": 422, + "title": "reserved namespace", + "type": "https://cmapi.ephico2real.com/problems/reserved-namespace" + } + }, "unknown-serviceaccount": { "value": { "code": "unknown-serviceaccount", @@ -16215,14 +14978,7 @@ "validation-failed": { "value": { "code": "validation-failed", - "detail": "The request is not valid: body.labels: Input should be a valid dictionary", - "errors": [ - { - "code": "dict_type", - "field": "body.labels", - "message": "Input should be a valid dictionary" - } - ], + "detail": "Request body is not valid", "status": 422, "title": "validation failed", "type": "https://cmapi.ephico2real.com/problems/validation-failed" @@ -16234,28 +14990,7 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `unknown-user`, `on-behalf-of-not-allowed`, `policy-violation`, `capacity-exceeded`, `unknown-serviceaccount`, `no-change`." - }, - "428": { - "content": { - "application/problem+json": { - "examples": { - "precondition-required": { - "value": { - "code": "precondition-required", - "detail": "If-Match is required on a change; GET the namespace for its etag", - "status": 428, - "title": "precondition required", - "type": "https://cmapi.ephico2real.com/problems/precondition-required" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "A change needs If-Match with the ETag of the object as it was read; `*` is not one.\n\nCodes: `precondition-required`." + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `unknown-user`, `on-behalf-of-not-allowed`, `policy-violation`, `capacity-exceeded`, `unknown-serviceaccount`, `reserved-namespace`, `invalid-namespace-name`, `expiration-not-allowed`, `expiration-in-past`, `placement-not-found`, `placement-mismatch`." }, "429": { "content": { @@ -16378,27 +15113,27 @@ "keycloak": [] } ], - "summary": "Change a namespace", + "summary": "Create a namespace", "tags": [ "namespaces" ], - "x-cmapi-permission": "namespaces:write", + "x-cmapi-permission": "namespaces:create", "x-cmapi-plugin": "namespaces", "x-cmapi-rate-limit": "write", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X PATCH https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'If-Match: \"3f9a1c0b7e2d4a68\"' -H 'Content-Type: application/json' -d '{\"annotations\": {\"runbook.ephico2real.com/url\": \"https://wiki.ephico2real.com/payments/runbook\"}, \"justification\": \"A smaller size after the load test, with the metadata tidied\", \"labels\": {\"cmapi.net/cost-center\": null}, \"tier\": \"medium\"}'" + "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'Content-Type: application/json' -d '{\"annotations\": {\"cmapi.net/team-dl\": \"payments-team@ephico2real.com\"}, \"justification\": \"Payments service dev namespace\", \"labels\": {\"cmapi.net/team\": \"payments\", \"cmapi.net/cost-center\": \"cc-4410\"}, \"namespace\": \"payments-dev\", \"tier\": \"small\"}'" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/clusters/{cluster_id}/namespaces/{ns}/expiration:extend": { - "post": { - "description": "Extends the expiry by `days` (up to the environment's limit) or to `until`. A normal request: plan,\napproval, bot PR. Needs If-Match. `dryRun=true` answers 200 with the plan and the approval that would apply.\n\n**Requires** `namespaces:write`.", - "operationId": "namespaces_extend", + "/api/v1/clusters/{cluster_id}/namespaces/{ns}": { + "delete": { + "description": "Opens a delete request: the folder leaves Git after approval, every file of it at any depth, and the namespace waits\nin awaiting_prune until an operator confirms the prune. Needs If-Match, read as on a change: a list of tags passes when one\nof them is the current etag, and `*` is 428 `precondition-required`. A folder that holds a submodule is 409\n`folder-holds-submodule`: its removal would change `.gitmodules`, outside the folder.\n\n`dryRun=true` answers 200 with the plan and opens no request: `changes` lists every file of the namespace's folder, at\nany depth and whatever made it, as `removed`, `files` is empty, and `approval` is the approval that the delete would need\nnow. It makes the delete's planning checks, so they refuse it where they refuse the delete: the permission, If-Match, a\nprotected namespace (422 `namespace-protected`) and a submodule (409 `folder-holds-submodule`). Like every dry run it skips the Idempotency-Key and the namespace's lock: while\nanother request holds the namespace the plan is still 200, and the delete is 409 `change-pending`.\n\n**Requires** `namespaces:write`.", + "operationId": "namespaces_delete_namespace", "parameters": [ { "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", @@ -16444,7 +15179,7 @@ } }, { - "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state. The caller is the token's subject: a service that sends `onBehalfOf` holds its key, and the person cannot replay it: the person's own use of that key is a request of their own. The same key with another request is 409 `idempotency-replay`. The expiry writes do not compare `justification`: a retry that changes only it gets the original request.", + "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state.", "in": "header", "name": "Idempotency-Key", "required": false, @@ -16457,7 +15192,7 @@ "type": "null" } ], - "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state. The caller is the token's subject: a service that sends `onBehalfOf` holds its key, and the person cannot replay it: the person's own use of that key is a request of their own. The same key with another request is 409 `idempotency-replay`. The expiry writes do not compare `justification`: a retry that changes only it gets the original request.", + "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state.", "examples": [ "0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10" ], @@ -16479,20 +15214,6 @@ } } ], - "requestBody": { - "content": { - "application/json": { - "example": { - "days": 7, - "justification": "Another sprint" - }, - "schema": { - "$ref": "#/components/schemas/ExtendBody" - } - } - }, - "required": true - }, "responses": { "200": { "content": { @@ -16501,45 +15222,48 @@ "adoption": null, "approval": { "approvals": [], - "auto": "none-required", + "auto": null, "autoFallback": null, "reasons": [ - "dev change: 0 from approver-platform" + "dev delete: 1 from approver-platform" ], - "remaining": [], - "rule": "dev-change", + "remaining": [ + { + "group": "approver-platform", + "needed": 1 + } + ], + "rule": "dev-delete", "selfApproval": true, - "slots": [], - "timeoutHours": 8 - }, - "beyondTier": null, + "slots": [ + { + "count": 1, + "group": "approver-platform", + "reason": "dev delete: 1 from approver-platform" + } + ], + "timeoutHours": 8 + }, + "beyondTier": null, "capacity": { - "bindingResource": "cpu", - "clusterId": "CRC", - "cpu": 0.25, + "bindingResource": null, "fresh": true, - "memory": 0.2, - "reserved": { - "cpu": 24.0, - "memory": 51539607552 - }, - "source": "simulated", + "source": "delete", "status": "fits" }, "changes": { - "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed" - }, - "etag": "073bd8faea2248ce", - "files": { - "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: sprint-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2026-12-31'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" + "clusters/CRC/namespaces/search-dev/limitrange-search-dev-limits-cpu.yaml": "removed", + "clusters/CRC/namespaces/search-dev/limitrange-search-dev-limits-memory.yaml": "removed", + "clusters/CRC/namespaces/search-dev/namespace.yaml": "removed", + "clusters/CRC/namespaces/search-dev/resourcequota-search-dev-quota.yaml": "removed", + "clusters/CRC/namespaces/search-dev/token-issuer-rolebinding.yaml": "removed" }, + "etag": "ca777167c63ddb5e", + "files": {}, "findings": [], "metadata": null, - "metadataDiff": { - "annotations": {}, - "labels": {} - }, - "planHash": "45af0b7fd4a2f76619cf99f889c9d19edb65d059722e4e459866be1859ec697b", + "metadataDiff": null, + "planHash": "c490196334dad591c3196aa59224d119861392145360aee1d428c93109235dbe", "requester": { "automated": false, "requester": { @@ -16569,54 +15293,65 @@ "content": { "application/json": { "example": { - "action": "update", + "action": "delete", "approval": { "approvals": [], - "auto": "none-required", + "auto": null, "autoFallback": null, "reasons": [ - "dev change: 0 from approver-platform" + "dev delete: 1 from approver-platform" ], - "remaining": [], - "rule": "dev-change", + "remaining": [ + { + "group": "approver-platform", + "needed": 1 + } + ], + "rule": "dev-delete", "selfApproval": true, - "slots": [], + "slots": [ + { + "count": 1, + "group": "approver-platform", + "reason": "dev delete: 1 from approver-platform" + } + ], "timeoutHours": 8 }, - "baseSha": "3e8ad5005d0b72c1869d34e49299f12f1b03b5b5", + "baseSha": "4afd09a1a70bbf2c03d8d2253e817b57a5812c0a", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:59.299718Z", + "createdAt": "2026-12-01T15:13:18.496644Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:59.374768Z", + "at": "2026-12-01T15:13:18.510655Z", "by": "ola", - "event": "plan_auto_approved", - "note": "none-required", - "status": "approved" + "event": "plan_needs_approval", + "note": "waiting for [('approver-platform', 1)]", + "status": "pending_approval" } ], "files": { - "clusters/CRC/namespaces/sprint-dev/limitrange-sprint-dev-limits-cpu.yaml": "unchanged", - "clusters/CRC/namespaces/sprint-dev/limitrange-sprint-dev-limits-memory.yaml": "unchanged", - "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed", - "clusters/CRC/namespaces/sprint-dev/resourcequota-sprint-dev-quota.yaml": "unchanged", - "clusters/CRC/namespaces/sprint-dev/token-issuer-rolebinding.yaml": "unchanged" + "clusters/CRC/namespaces/search-dev/limitrange-search-dev-limits-cpu.yaml": "removed", + "clusters/CRC/namespaces/search-dev/limitrange-search-dev-limits-memory.yaml": "removed", + "clusters/CRC/namespaces/search-dev/namespace.yaml": "removed", + "clusters/CRC/namespaces/search-dev/resourcequota-search-dev-quota.yaml": "removed", + "clusters/CRC/namespaces/search-dev/token-issuer-rolebinding.yaml": "removed" }, "instance": "nonprod", - "justification": "Another sprint", + "justification": null, "links": { - "events": "/api/v1/requests/req-20261127-0004/events", - "self": "/api/v1/requests/req-20261127-0004" + "events": "/api/v1/requests/req-20261201-0008/events", + "self": "/api/v1/requests/req-20261201-0008" }, "mergeSha": null, - "namespace": "sprint-dev", - "planHash": "fd55be2f5fa99dbc2d1abb18df09cb134f778a075ba88a80375fd4004efd3024", + "namespace": "search-dev", + "planHash": "c490196334dad591c3196aa59224d119861392145360aee1d428c93109235dbe", "plugin": "namespaces", "pr": null, - "reason": "expiration:extend", - "requestId": "req-20261127-0004", + "reason": null, + "requestId": "req-20261201-0008", "requester": { "automated": false, "requester": { @@ -16633,8 +15368,8 @@ "submittedBy": null, "submittedByClient": null }, - "status": "approved", - "updatedAt": "2026-11-27T20:58:59.274371Z" + "status": "pending_approval", + "updatedAt": "2026-12-01T15:13:18.239084Z" }, "schema": { "$ref": "#/components/schemas/ChangeRequest" @@ -16758,6 +15493,18 @@ "type": "https://cmapi.ephico2real.com/problems/change-pending" } }, + "folder-holds-submodule": { + "value": { + "code": "folder-holds-submodule", + "detail": "The folder of payments-dev holds the submodule clusters/CRC/namespaces/payments-dev/vendor", + "paths": [ + "clusters/CRC/namespaces/payments-dev/vendor" + ], + "status": 409, + "title": "folder holds submodule", + "type": "https://cmapi.ephico2real.com/problems/folder-holds-submodule" + } + }, "folder-not-utf8": { "value": { "code": "folder-not-utf8", @@ -16797,7 +15544,7 @@ } } }, - "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`." + "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`, `folder-holds-submodule`." }, "412": { "content": { @@ -16820,41 +15567,10 @@ }, "description": "No strong tag that If-Match lists is the object's ETag: it changed since it was read, or the value named none.\n\nCodes: `precondition-failed`." }, - "413": { - "content": { - "application/problem+json": { - "examples": { - "content-too-large": { - "value": { - "code": "content-too-large", - "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", - "maxBytes": 1048576, - "status": 413, - "title": "content too large", - "type": "https://cmapi.ephico2real.com/problems/content-too-large" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." - }, "422": { "content": { "application/problem+json": { "examples": { - "capacity-exceeded": { - "value": { - "code": "capacity-exceeded", - "detail": "memory would exceed the cluster", - "status": 422, - "title": "capacity exceeded", - "type": "https://cmapi.ephico2real.com/problems/capacity-exceeded" - } - }, "cluster-not-writable": { "value": { "code": "cluster-not-writable", @@ -16875,42 +15591,6 @@ "type": "https://cmapi.ephico2real.com/problems/environment-not-served" } }, - "expiration-in-past": { - "value": { - "code": "expiration-in-past", - "detail": "The new date must be later than the current one", - "status": 422, - "title": "expiration in past", - "type": "https://cmapi.ephico2real.com/problems/expiration-in-past" - } - }, - "expiration-limit": { - "value": { - "code": "expiration-limit", - "detail": "An extension is at most 30 days", - "status": 422, - "title": "expiration limit", - "type": "https://cmapi.ephico2real.com/problems/expiration-limit" - } - }, - "expiration-not-allowed": { - "value": { - "code": "expiration-not-allowed", - "detail": "Production namespaces never expire", - "status": 422, - "title": "expiration not allowed", - "type": "https://cmapi.ephico2real.com/problems/expiration-not-allowed" - } - }, - "expiration-not-set": { - "value": { - "code": "expiration-not-set", - "detail": "The namespace is permanent; use :set", - "status": 422, - "title": "expiration not set", - "type": "https://cmapi.ephico2real.com/problems/expiration-not-set" - } - }, "identity-incomplete": { "value": { "code": "identity-incomplete", @@ -16920,6 +15600,15 @@ "type": "https://cmapi.ephico2real.com/problems/identity-incomplete" } }, + "namespace-protected": { + "value": { + "code": "namespace-protected", + "detail": "Protected namespaces cannot be deleted", + "status": 422, + "title": "namespace protected", + "type": "https://cmapi.ephico2real.com/problems/namespace-protected" + } + }, "on-behalf-of-required": { "value": { "code": "on-behalf-of-required", @@ -16938,24 +15627,6 @@ "type": "https://cmapi.ephico2real.com/problems/plugin-disabled" } }, - "policy-violation": { - "value": { - "code": "policy-violation", - "detail": "Metadata refused", - "status": 422, - "title": "policy violation", - "type": "https://cmapi.ephico2real.com/problems/policy-violation" - } - }, - "unknown-serviceaccount": { - "value": { - "code": "unknown-serviceaccount", - "detail": "ci-deployer is not a ServiceAccount of payments-dev", - "status": 422, - "title": "unknown serviceaccount", - "type": "https://cmapi.ephico2real.com/problems/unknown-serviceaccount" - } - }, "validation-failed": { "value": { "code": "validation-failed", @@ -16971,7 +15642,7 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `policy-violation`, `capacity-exceeded`, `unknown-serviceaccount`, `expiration-not-allowed`, `expiration-not-set`, `expiration-in-past`, `expiration-limit`." + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `namespace-protected`." }, "428": { "content": { @@ -17070,26 +15741,6 @@ "title": "idp unavailable", "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" } - }, - "validator-busy": { - "value": { - "code": "validator-busy", - "detail": "The policy check is temporarily busy. Try again after the delay in Retry-After.", - "retryAfter": 15, - "status": 503, - "title": "validator busy", - "type": "https://cmapi.ephico2real.com/problems/validator-busy" - } - }, - "validator-unavailable": { - "value": { - "code": "validator-unavailable", - "detail": "kubeconform did not start", - "retryAfter": 60, - "status": 503, - "title": "validator unavailable", - "type": "https://cmapi.ephico2real.com/problems/validator-unavailable" - } } }, "schema": { @@ -17097,7 +15748,7 @@ } } }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `cluster-unreachable`, `validator-unavailable`, `validator-busy`, `idp-unavailable`.", + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `cluster-unreachable`, `idp-unavailable`.", "headers": { "Retry-After": { "description": "The seconds to wait before the next call: the same number as `retryAfter`.", @@ -17115,7 +15766,7 @@ "keycloak": [] } ], - "summary": "Extend a namespace's expiry", + "summary": "Delete a namespace", "tags": [ "namespaces" ], @@ -17126,16 +15777,14 @@ { "label": "curl", "lang": "Shell", - "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev/expiration:extend -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'If-Match: \"3f9a1c0b7e2d4a68\"' -H 'Content-Type: application/json' -d '{\"days\": 7, \"justification\": \"Another sprint\"}'" + "source": "curl -X DELETE https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'If-Match: \"3f9a1c0b7e2d4a68\"'" } ], "x-plugin-version": "0.2.0" - } - }, - "/api/v1/clusters/{cluster_id}/namespaces/{ns}/expiration:makePermanent": { - "post": { - "description": "Removes the expiry date (`cmapi.net/expires-at` and `cmapi.net/expiry`), so the namespace no longer expires. It always\nadds an approval from approver-platform (docs/01, Namespace expiration). A namespace with no date is refused with 422\nexpiration-not-set. It is taken where expiration is now off too, so a date given while it was on can be removed. A normal request: plan, approval, bot PR. Needs If-Match. `dryRun=true` answers 200 with the plan.\n\n**Requires** `namespaces:write`.", - "operationId": "namespaces_make_permanent", + }, + "get": { + "description": "The live namespace and the etag of its folder in Git. Send the etag as If-Match on PATCH or DELETE (the `ETag`\nheader has the same value).\n\n`labels` and `annotations` are the live ones, from the watch cache. `git` is the folder's labels and annotations, the\ndesired state, from the same read as the etag. Its `edits` give `x-cmapi-edit` of each key of Git that\nmetadata-keys.yaml does not declare, so a form can lock it or offer its removal: `mode`, the `reason` to show,\n`sensitive`, and `removable` for a key that no rule admits, which a change may remove and never set (#484). An\noperator-only key's reason names this cluster's environment (#532). The other keys' `x-cmapi-edit` are in\n`GET /api/v1/metadata-keys`. Its `missingKeys` list each declared key that Git lacks, as an adopted namespace may, which a\nchange can add, with the one value of a key that cmapi fills in or that starts the name (#732, #739). `sync` compares Git with the live namespace (#481): `pending` while a request holds it,\n`drift` when a governed, extra or operator-only key differs (each in `driftedKeys`), `in-sync` when none does, and\n`unknown` when the cluster's watch is not fresh.\n\n**Requires** `objects:read`.", + "operationId": "namespaces_get_namespace", "parameters": [ { "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", @@ -17164,267 +15813,158 @@ "title": "Ns", "type": "string" } - }, - { - "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", - "in": "query", - "name": "dryRun", - "required": false, - "schema": { - "default": false, - "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", - "examples": [ - true - ], - "title": "Dryrun", - "type": "boolean" - } - }, - { - "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state. The caller is the token's subject: a service that sends `onBehalfOf` holds its key, and the person cannot replay it: the person's own use of that key is a request of their own. The same key with another request is 409 `idempotency-replay`. The expiry writes do not compare `justification`: a retry that changes only it gets the original request.", - "in": "header", - "name": "Idempotency-Key", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state. The caller is the token's subject: a service that sends `onBehalfOf` holds its key, and the person cannot replay it: the person's own use of that key is a request of their own. The same key with another request is 409 `idempotency-replay`. The expiry writes do not compare `justification`: a retry that changes only it gets the original request.", - "examples": [ - "0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10" - ], - "title": "Idempotency-Key" - } - }, - { - "description": "The namespace's etag from `GET .../namespaces/{ns}`, in double quotes as its `ETag` header gives it. Required on a change or a delete. A list of tags passes when one of them is the current etag (RFC 9110, section 13.1.1). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line. `*` is 428 `precondition-required`: If-Match must name the etag that was read. A weak tag (`W/\"...\"`) never matches. An Idempotency-Key replay returns the original request in its current state without comparing the tag.", - "in": "header", - "name": "If-Match", - "required": true, - "schema": { - "description": "The namespace's etag from `GET .../namespaces/{ns}`, in double quotes as its `ETag` header gives it. Required on a change or a delete. A list of tags passes when one of them is the current etag (RFC 9110, section 13.1.1). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line. `*` is 428 `precondition-required`: If-Match must name the etag that was read. A weak tag (`W/\"...\"`) never matches. An Idempotency-Key replay returns the original request in its current state without comparing the tag.", - "examples": [ - "\"3f9a1c0b7e2d4a68\"" - ], - "title": "If-Match", - "type": "string" - } } ], - "requestBody": { - "content": { - "application/json": { - "example": { - "justification": "In production use" - }, - "schema": { - "$ref": "#/components/schemas/PermanentBody" - } - } - }, - "required": true - }, "responses": { "200": { "content": { "application/json": { "example": { - "adoption": null, - "approval": { - "approvals": [], - "auto": null, - "autoFallback": null, - "reasons": [ - "dev change: 0 from approver-platform", - "threshold expirationBeyondLimits: +1 approver-platform" - ], - "remaining": [ - { - "group": "approver-platform", - "needed": 1 + "annotations": { + "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", + "cmapi.net/instance": "nonprod", + "cmapi.net/request-id": "req-20261201-0001", + "cmapi.net/requested-by": "ola@ephico2real.com", + "cmapi.net/team-dl": "payments-team@ephico2real.com" + }, + "clusterId": "CRC", + "env": "dev", + "etag": "1b59766bf9a3bbe7", + "expiresAt": null, + "git": { + "annotations": { + "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", + "cmapi.net/instance": "nonprod", + "cmapi.net/request-id": "req-20261201-0001", + "cmapi.net/requested-by": "ola@ephico2real.com", + "cmapi.net/team-dl": "payments-team@ephico2real.com" + }, + "edits": { + "annotations": { + "argocd.argoproj.io/sync-options": { + "mode": "fixed", + "reason": "Reserved for the platform.", + "removable": false, + "sensitive": false + }, + "cmapi.net/instance": { + "mode": "fixed", + "reason": "Managed by cmapi.", + "removable": false, + "sensitive": false + }, + "cmapi.net/request-id": { + "mode": "fixed", + "reason": "Managed by cmapi.", + "removable": false, + "sensitive": false + }, + "cmapi.net/requested-by": { + "mode": "fixed", + "reason": "Managed by cmapi.", + "removable": false, + "sensitive": false + } + }, + "labels": { + "cmapi.net/cluster-id": { + "mode": "fixed", + "reason": "Managed by cmapi.", + "removable": false, + "sensitive": false + }, + "cmapi.net/env": { + "mode": "fixed", + "reason": "Managed by cmapi.", + "removable": false, + "sensitive": false + }, + "cmapi.net/managed": { + "mode": "fixed", + "reason": "Managed by cmapi.", + "removable": false, + "sensitive": false + }, + "cmapi.net/requested-by-user": { + "mode": "fixed", + "reason": "Managed by cmapi.", + "removable": false, + "sensitive": false + }, + "cmapi.net/tier": { + "mode": "fixed", + "reason": "Managed by cmapi.", + "removable": false, + "sensitive": false + } } - ], - "rule": "dev-change", - "selfApproval": true, - "slots": [ + }, + "labels": { + "cmapi.net/cluster-id": "CRC", + "cmapi.net/cost-center": "cc-4410", + "cmapi.net/env": "dev", + "cmapi.net/managed": "true", + "cmapi.net/requested-by-user": "ola", + "cmapi.net/team": "payments", + "cmapi.net/tier": "small" + }, + "missingKeys": [ { - "count": 1, - "group": "approver-platform", - "reason": "Expiry beyond limits" + "key": "cmapi.net/app", + "kind": "label", + "required": false, + "value": null + }, + { + "key": "cmapi.net/rightsizing", + "kind": "label", + "required": false, + "value": null } - ], - "timeoutHours": 8 - }, - "beyondTier": null, - "capacity": { - "bindingResource": "cpu", - "clusterId": "CRC", - "cpu": 0.25, - "fresh": true, - "memory": 0.2, - "reserved": { - "cpu": 24.0, - "memory": 51539607552 - }, - "source": "simulated", - "status": "fits" - }, - "changes": { - "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed" - }, - "etag": "073bd8faea2248ce", - "files": { - "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: sprint-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" + ] }, - "findings": [], - "metadata": null, - "metadataDiff": { - "annotations": {}, - "labels": {} + "labels": { + "cmapi.net/cluster-id": "CRC", + "cmapi.net/cost-center": "cc-4410", + "cmapi.net/env": "dev", + "cmapi.net/managed": "true", + "cmapi.net/requested-by-user": "ola", + "cmapi.net/team": "payments", + "cmapi.net/tier": "small" }, - "planHash": "4e2f1ef26fab90b27dc41e0fd496b8e8006b2742bc192f09a8dea81ffefb031b", - "requester": { - "automated": false, - "requester": { - "clientId": "cmapi-portal", - "email": "ola@ephico2real.com", - "employeeId": "1001", - "familyName": "Doe", - "givenName": "Ola", - "kind": "user", - "middleName": null, - "sub": "sub-ola", - "username": "ola" - }, - "submittedBy": null, - "submittedByClient": null + "managed": true, + "mnemonic": null, + "name": "payments-dev", + "openRequest": null, + "protected": false, + "protectedBy": [], + "sync": { + "driftedKeys": [], + "openRequest": null, + "state": "in-sync" }, - "usage": null + "team": "payments", + "tier": "small" }, "schema": { - "$ref": "#/components/schemas/PlanView" + "$ref": "#/components/schemas/NamespaceView" } } }, - "description": "Dry run (`?dryRun=true`): the plan. The call opens no change request, takes no lock or reservation, queues no job and opens no pull request." + "description": "The namespace's labels, annotations, tier and sync state as Git and the cluster hold them, with the ETag that a change sends in If-Match.", + "headers": { + "ETag": { + "description": "The namespace's entity tag, quoted: the `etag` of the body. Send it unchanged as `If-Match` on a change or a delete. It changes when the `.yaml` files directly in the namespace's folder in Git change.", + "schema": { + "examples": [ + "\"3f9a1c0b7e2d4a68\"" + ], + "type": "string" + } + } + } }, - "202": { - "content": { - "application/json": { - "example": { - "action": "update", - "approval": { - "approvals": [], - "auto": null, - "autoFallback": null, - "reasons": [ - "dev change: 0 from approver-platform", - "threshold expirationBeyondLimits: +1 approver-platform" - ], - "remaining": [ - { - "group": "approver-platform", - "needed": 1 - } - ], - "rule": "dev-change", - "selfApproval": true, - "slots": [ - { - "count": 1, - "group": "approver-platform", - "reason": "Expiry beyond limits" - } - ], - "timeoutHours": 8 - }, - "baseSha": "ac1e81f58836d7f8a36ae1cdff67fe152c02fd02", - "beyondTier": null, - "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:12.604388Z", - "env": "dev", - "events": [ - { - "at": "2026-11-27T20:59:12.676330Z", - "by": "ola", - "event": "plan_needs_approval", - "note": "waiting for [('approver-platform', 1)]", - "status": "pending_approval" - } - ], - "files": { - "clusters/CRC/namespaces/sprint-dev/limitrange-sprint-dev-limits-cpu.yaml": "unchanged", - "clusters/CRC/namespaces/sprint-dev/limitrange-sprint-dev-limits-memory.yaml": "unchanged", - "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed", - "clusters/CRC/namespaces/sprint-dev/resourcequota-sprint-dev-quota.yaml": "unchanged", - "clusters/CRC/namespaces/sprint-dev/token-issuer-rolebinding.yaml": "unchanged" - }, - "instance": "nonprod", - "justification": "In production use", - "links": { - "events": "/api/v1/requests/req-20261127-0013/events", - "self": "/api/v1/requests/req-20261127-0013" - }, - "mergeSha": null, - "namespace": "sprint-dev", - "planHash": "b2e28a66559008829930431df326dc1a91864514d67474024f7fae04298cdfd0", - "plugin": "namespaces", - "pr": null, - "reason": "expiration:makePermanent", - "requestId": "req-20261127-0013", - "requester": { - "automated": false, - "requester": { - "clientId": "cmapi-portal", - "email": "ola@ephico2real.com", - "employeeId": "1001", - "familyName": "Doe", - "givenName": "Ola", - "kind": "user", - "middleName": null, - "sub": "sub-ola", - "username": "ola" - }, - "submittedBy": null, - "submittedByClient": null - }, - "status": "pending_approval", - "updatedAt": "2026-11-27T20:59:12.577772Z" - }, - "schema": { - "$ref": "#/components/schemas/ChangeRequest" - } - } - }, - "description": "The request is created. It waits for approval unless a policy approves it at once: `status` and `approval` say which, and `links.events` follows it." - }, - "400": { - "content": { - "application/problem+json": { - "examples": { - "idempotency-key-required": { - "value": { - "code": "idempotency-key-required", - "detail": "Idempotency-Key header is required on writes", - "status": 400, - "title": "idempotency key required", - "type": "https://cmapi.ephico2real.com/problems/idempotency-key-required" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `idempotency-key-required`." - }, - "401": { + "401": { "content": { "application/problem+json": { "examples": { @@ -17452,7 +15992,7 @@ "environment-forbidden": { "value": { "code": "environment-forbidden", - "detail": "Your roles grant namespaces:write only in ['rnd'], not dev", + "detail": "Your roles grant objects:read only in ['rnd'], not dev", "status": 403, "title": "environment forbidden", "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" @@ -17461,7 +16001,7 @@ "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission namespaces:write: no role in your token grants it (roles: ['cmapi-requester'])", + "detail": "Missing permission objects:read: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -17482,7 +16022,7 @@ "cluster-not-found": { "value": { "code": "cluster-not-found", - "detail": "Unknown cluster OCP_X", + "detail": "Unknown cluster NOPE", "status": 404, "title": "cluster not found", "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" @@ -17491,7 +16031,7 @@ "object-not-found": { "value": { "code": "object-not-found", - "detail": "No request req-20261105-0001", + "detail": "not-there-dev is not on CRC and not in Git", "status": 404, "title": "object not found", "type": "https://cmapi.ephico2real.com/problems/object-not-found" @@ -17509,15 +16049,6 @@ "content": { "application/problem+json": { "examples": { - "change-pending": { - "value": { - "code": "change-pending", - "detail": "req-20261105-0001 holds payments-dev", - "status": 409, - "title": "change pending", - "type": "https://cmapi.ephico2real.com/problems/change-pending" - } - }, "folder-not-utf8": { "value": { "code": "folder-not-utf8", @@ -17541,15 +16072,6 @@ "title": "folder not yaml", "type": "https://cmapi.ephico2real.com/problems/folder-not-yaml" } - }, - "idempotency-replay": { - "value": { - "code": "idempotency-replay", - "detail": "Idempotency-Key was used for a different request", - "status": 409, - "title": "idempotency replay", - "type": "https://cmapi.ephico2real.com/problems/idempotency-replay" - } } }, "schema": { @@ -17557,19 +16079,19 @@ } } }, - "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`." + "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `folder-not-utf8`, `folder-not-yaml`." }, - "412": { + "422": { "content": { "application/problem+json": { "examples": { - "precondition-failed": { + "validation-failed": { "value": { - "code": "precondition-failed", - "detail": "The namespace changed in Git since you read it", - "status": 412, - "title": "precondition failed", - "type": "https://cmapi.ephico2real.com/problems/precondition-failed" + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" } } }, @@ -17578,20 +16100,20 @@ } } }, - "description": "No strong tag that If-Match lists is the object's ETag: it changed since it was read, or the value named none.\n\nCodes: `precondition-failed`." + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." }, - "413": { + "429": { "content": { "application/problem+json": { "examples": { - "content-too-large": { + "rate-limited": { "value": { - "code": "content-too-large", - "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", - "maxBytes": 1048576, - "status": 413, - "title": "content too large", - "type": "https://cmapi.ephico2real.com/problems/content-too-large" + "code": "rate-limited", + "detail": "Too many write calls by this caller; try again in 2 s", + "retryAfter": 2, + "status": 429, + "title": "rate limited", + "type": "https://cmapi.ephico2real.com/problems/rate-limited" } } }, @@ -17600,237 +16122,51 @@ } } }, - "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." + "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } }, - "422": { + "502": { "content": { "application/problem+json": { "examples": { - "capacity-exceeded": { - "value": { - "code": "capacity-exceeded", - "detail": "memory would exceed the cluster", - "status": 422, - "title": "capacity exceeded", - "type": "https://cmapi.ephico2real.com/problems/capacity-exceeded" - } - }, - "cluster-not-writable": { - "value": { - "code": "cluster-not-writable", - "detail": "CRC is imported but has no clusters.yaml entry", - "status": 422, - "title": "cluster not writable", - "type": "https://cmapi.ephico2real.com/problems/cluster-not-writable" - } - }, - "environment-not-served": { - "value": { - "code": "environment-not-served", - "detail": "qa is not served by the nonprod instance", - "instanceUrl": "https://cmapi-staging.ephico2real.com", - "portalUrl": "https://portal-staging.ephico2real.com", - "status": 422, - "title": "environment not served", - "type": "https://cmapi.ephico2real.com/problems/environment-not-served" - } - }, - "expiration-not-allowed": { - "value": { - "code": "expiration-not-allowed", - "detail": "Production namespaces never expire", - "status": 422, - "title": "expiration not allowed", - "type": "https://cmapi.ephico2real.com/problems/expiration-not-allowed" - } - }, - "expiration-not-set": { - "value": { - "code": "expiration-not-set", - "detail": "The namespace is permanent; use :set", - "status": 422, - "title": "expiration not set", - "type": "https://cmapi.ephico2real.com/problems/expiration-not-set" - } - }, - "identity-incomplete": { - "value": { - "code": "identity-incomplete", - "detail": "The token has no employee_id claim", - "status": 422, - "title": "identity incomplete", - "type": "https://cmapi.ephico2real.com/problems/identity-incomplete" - } - }, - "on-behalf-of-required": { + "git-unavailable": { "value": { - "code": "on-behalf-of-required", - "detail": "A service client must name the person", - "status": 422, - "title": "on behalf of required", - "type": "https://cmapi.ephico2real.com/problems/on-behalf-of-required" + "code": "git-unavailable", + "detail": "The Git host answered 500", + "status": 502, + "title": "git unavailable", + "type": "https://cmapi.ephico2real.com/problems/git-unavailable" } - }, - "plugin-disabled": { + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The Git host failed.\n\nCodes: `git-unavailable`." + }, + "503": { + "content": { + "application/problem+json": { + "examples": { + "idp-unavailable": { "value": { - "code": "plugin-disabled", - "detail": "The namespaces plugin takes no writes in dev on the nonprod instance: plugins.yaml disables it there", - "status": 422, - "title": "plugin disabled", - "type": "https://cmapi.ephico2real.com/problems/plugin-disabled" - } - }, - "policy-violation": { - "value": { - "code": "policy-violation", - "detail": "Metadata refused", - "status": 422, - "title": "policy violation", - "type": "https://cmapi.ephico2real.com/problems/policy-violation" - } - }, - "unknown-serviceaccount": { - "value": { - "code": "unknown-serviceaccount", - "detail": "ci-deployer is not a ServiceAccount of payments-dev", - "status": 422, - "title": "unknown serviceaccount", - "type": "https://cmapi.ephico2real.com/problems/unknown-serviceaccount" - } - }, - "validation-failed": { - "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `policy-violation`, `capacity-exceeded`, `unknown-serviceaccount`, `expiration-not-allowed`, `expiration-not-set`." - }, - "428": { - "content": { - "application/problem+json": { - "examples": { - "precondition-required": { - "value": { - "code": "precondition-required", - "detail": "If-Match is required on a change", - "status": 428, - "title": "precondition required", - "type": "https://cmapi.ephico2real.com/problems/precondition-required" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "A change needs If-Match with the ETag of the object as it was read; `*` is not one.\n\nCodes: `precondition-required`." - }, - "429": { - "content": { - "application/problem+json": { - "examples": { - "rate-limited": { - "value": { - "code": "rate-limited", - "detail": "Too many write calls by this caller; try again in 2 s", - "retryAfter": 2, - "status": 429, - "title": "rate limited", - "type": "https://cmapi.ephico2real.com/problems/rate-limited" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } - } - } - }, - "502": { - "content": { - "application/problem+json": { - "examples": { - "git-unavailable": { - "value": { - "code": "git-unavailable", - "detail": "The Git host answered 500", - "status": 502, - "title": "git unavailable", - "type": "https://cmapi.ephico2real.com/problems/git-unavailable" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "The Git host failed.\n\nCodes: `git-unavailable`." - }, - "503": { - "content": { - "application/problem+json": { - "examples": { - "cluster-unreachable": { - "value": { - "code": "cluster-unreachable", - "detail": "CRC did not answer", - "retryAfter": 30, - "status": 503, - "title": "cluster unreachable", - "type": "https://cmapi.ephico2real.com/problems/cluster-unreachable" - } - }, - "idp-unavailable": { - "value": { - "code": "idp-unavailable", - "detail": "Keycloak signing keys are unreachable and this key is not cached", - "retryAfter": 30, - "status": 503, - "title": "idp unavailable", - "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" - } - }, - "validator-busy": { - "value": { - "code": "validator-busy", - "detail": "The policy check is temporarily busy. Try again after the delay in Retry-After.", - "retryAfter": 15, - "status": 503, - "title": "validator busy", - "type": "https://cmapi.ephico2real.com/problems/validator-busy" - } - }, - "validator-unavailable": { - "value": { - "code": "validator-unavailable", - "detail": "kubeconform did not start", - "retryAfter": 60, - "status": 503, - "title": "validator unavailable", - "type": "https://cmapi.ephico2real.com/problems/validator-unavailable" + "code": "idp-unavailable", + "detail": "Keycloak signing keys are unreachable and this key is not cached", + "retryAfter": 30, + "status": 503, + "title": "idp unavailable", + "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" } } }, @@ -17839,7 +16175,7 @@ } } }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `cluster-unreachable`, `validator-unavailable`, `validator-busy`, `idp-unavailable`.", + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", "headers": { "Retry-After": { "description": "The seconds to wait before the next call: the same number as `retryAfter`.", @@ -17857,27 +16193,25 @@ "keycloak": [] } ], - "summary": "Remove a namespace's expiry", + "summary": "Get a namespace and its ETag", "tags": [ "namespaces" ], - "x-cmapi-permission": "namespaces:write", + "x-cmapi-permission": "objects:read", "x-cmapi-plugin": "namespaces", - "x-cmapi-rate-limit": "write", + "x-cmapi-rate-limit": "read", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev/expiration:makePermanent -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'If-Match: \"3f9a1c0b7e2d4a68\"' -H 'Content-Type: application/json' -d '{\"justification\": \"In production use\"}'" + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev -H \"Authorization: Bearer $TOKEN\"" } ], "x-plugin-version": "0.2.0" - } - }, - "/api/v1/clusters/{cluster_id}/namespaces/{ns}/expiration:set": { - "post": { - "description": "Gives a namespace that has no expiry the date `until`: after today, and at most the environment's maxExtensionDays\naway. A namespace that has a date is refused with 422 expiration-already-set: use :extend. A normal request: plan,\napproval, bot PR. Needs If-Match. `dryRun=true` answers 200 with the plan and the approval that would apply.\n\n**Requires** `namespaces:write`.", - "operationId": "namespaces_set_expiry", + }, + "patch": { + "description": "Changes a namespace that exists: its tier, its custom quota and limits, and its labels and annotations.\n\n**Merge patch.** `labels` and `annotations` follow JSON Merge Patch (RFC 7396, https://www.rfc-editor.org/rfc/rfc7396):\na key that the body leaves out keeps its value, a string sets it, and `null` removes it. `x-cmapi-edit` of each key,\nin `GET /api/v1/metadata-keys` and, for the keys that file does not declare, in `git.edits` of the namespace's read,\nsays how it may change: `fixed` (the value in Git stays; the same value sent back is accepted; a missing key that\nstarts the name can be added with that start), `automatic` (filled at creation; a change keeps Git's value, and a request\ncan add a missing one with the derived value), `required` (it changes and is never removed) or `optional`. A key that no\nrule admits can be removed, never set. A `sensitive` key adds one approval to the request.\n\n**Check, then submit.** With `dryRun=true` the answer is 200 with the plan, and no request is opened. `metadataDiff`\nlists each effective change by key as `before`, `after` and `source`: `before` is `null` when the key is added, `after`\nis `null` when it is removed. The same body without `dryRun`, with an Idempotency-Key, opens the request (202).\n\n**If-Match.** Send the ETag of `GET .../namespaces/{ns}` as If-Match (RFC 9110, section 13.1.1). For a new plan,\na namespace missing from Git is 404 `object-not-found` before the precondition checks. For an existing namespace,\nmissing If-Match is 428 `precondition-required` (RFC 6585, section 3), and so is `*`: it proves no read, so cmapi\nrefuses it on purpose, where RFC 9110 lets it match any namespace that exists. A list of tags, sent in one If-Match\nfield, passes when one of them is the current etag, by the strong comparison, so a weak tag (`W/\"...\"`) never matches.\nOtherwise the answer is 412 `precondition-failed` (RFC 9110, section 15.5.13) with the current `etag`: read the\nnamespace again, apply the change to it and send it.\nAn Idempotency-Key replay still requires If-Match, but does not compare it again: it returns the\noriginal request in its current state even after Git moves, and `*` is 428 there too. The Idempotency-Key parameter\nsays when a retry is a replay. A non-dry-run submission also requires Idempotency-Key (400 without it).\nOne request at a time holds a namespace: while another is open, 409 `change-pending` names it in `requestId`.\n\n**Refusals.** 422 `policy-violation` has one `errors` entry for each key that breaks a rule (`reserved_key`,\n`invalid_key`, `invalid_value`, `derived_key`, `missing_required_key`, `too_many_keys`, `annotations_too_large`).\nA key that only an operator may change is 403 `forbidden` without `namespaces:protect` in the namespace's\nenvironment. A body that changes nothing is 422 `no-change`.\n\n**Several ResourceQuotas.** cmapi changes only its own ResourceQuota (`-quota`) and LimitRanges (`-limits-*`);\nevery other one in the folder is kept as Git holds it, each in its own file (#250). When the folder holds several\nResourceQuotas, a change of `quota` or `tier` is 409 `several-resource-quotas`, which names them in `resourceQuotas`: the\nrequest cannot say which one it changes. When none of them is `-quota`, a change of `limitRange` is refused too, and\na change of labels, annotations or the expiry keeps every ResourceQuota and LimitRange.\n\n**Requires** `namespaces:write`.", + "operationId": "namespaces_update_namespace", "parameters": [ { "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", @@ -17961,12 +16295,30 @@ "requestBody": { "content": { "application/json": { - "example": { - "justification": "A load test this sprint", - "until": "2026-12-18" + "examples": { + "mergePatch": { + "summary": "Change labels and annotations: a value sets a key, null removes it (add dryRun=true to check)", + "value": { + "annotations": { + "runbook.ephico2real.com/url": "https://wiki.ephico2real.com/payments/runbook" + }, + "justification": "A smaller size after the load test, with the metadata tidied", + "labels": { + "cmapi.net/cost-center": null + }, + "tier": "medium" + } + }, + "tier": { + "summary": "Change the tier", + "value": { + "justification": "Load test next sprint", + "tier": "large" + } + } }, "schema": { - "$ref": "#/components/schemas/SetBody" + "$ref": "#/components/schemas/NamespacePatch" } } }, @@ -17995,30 +16347,48 @@ "capacity": { "bindingResource": "cpu", "clusterId": "CRC", - "cpu": 0.25, + "cpu": 0.125, "fresh": true, - "memory": 0.2, + "memory": 0.1, "reserved": { - "cpu": 24.0, - "memory": 51539607552 + "cpu": 0.0, + "memory": 0 }, "source": "simulated", "status": "fits" }, "changes": { - "clusters/CRC/namespaces/notes-dev/namespace.yaml": "changed" + "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "changed", + "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "changed", + "clusters/CRC/namespaces/payments-dev/namespace.yaml": "changed", + "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "changed" }, - "etag": "2763b4eb2ce407b5", + "etag": "1b59766bf9a3bbe7", "files": { - "clusters/CRC/namespaces/notes-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: notes-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2026-12-18'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" + "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-cpu\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: medium\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 44fd85f2d7cb\nspec:\n limits:\n - type: Container\n defaultRequest:\n cpu: 100m\n default:\n cpu: 500m\n max:\n cpu: '4'\n", + "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-memory\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: medium\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 44fd85f2d7cb\nspec:\n limits:\n - type: Container\n defaultRequest:\n memory: 256Mi\n default:\n memory: 512Mi\n max:\n memory: 8Gi\n", + "clusters/CRC/namespaces/payments-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: medium\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n runbook.ephico2real.com/url: https://wiki.ephico2real.com/payments/runbook\n", + "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "apiVersion: v1\nkind: ResourceQuota\nmetadata:\n name: payments-dev-quota\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: medium\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 44fd85f2d7cb\nspec:\n hard:\n requests.cpu: '16'\n requests.memory: 32Gi\n pods: '100'\n persistentvolumeclaims: '30'\n requests.storage: 500Gi\n services.loadbalancers: '0'\n services.nodeports: '0'\n" }, "findings": [], "metadata": null, "metadataDiff": { - "annotations": {}, - "labels": {} + "annotations": { + "runbook.ephico2real.com/url": { + "after": "https://wiki.ephico2real.com/payments/runbook", + "before": null, + "source": "request" + } + }, + "labels": { + "cmapi.net/cost-center": { + "after": null, + "before": "cc-4410", + "source": "request" + } + } }, - "planHash": "38d5d19ff384c206da94f3e9d1844ceeb7e15bedcd639467c71f7677117614a3", + "planHash": "3409c7cab6683ab5c6280d06452d63623f90b3231e915bb31b5b4efee19b9adc", "requester": { "automated": false, "requester": { @@ -18035,7 +16405,35 @@ "submittedBy": null, "submittedByClient": null }, - "usage": null + "usage": { + "coverage": null, + "cpu": { + "avg7d": null, + "newOverPeak": null, + "newQuota": 16000, + "now": null, + "p95": null, + "peak": null, + "quota": 8000 + }, + "evaluatedAt": null, + "memory": { + "avg7d": null, + "newOverPeak": null, + "newQuota": 34359738368, + "now": null, + "p95": null, + "peak": null, + "quota": 17179869184 + }, + "reason": "No usage source is configured on this instance (capacity.yaml usage.source is none), so there is no 14-day usage.", + "state": "insufficient-data", + "units": { + "cpu": "millicores", + "memory": "bytes" + }, + "window": "14d" + } }, "schema": { "$ref": "#/components/schemas/PlanView" @@ -18051,51 +16449,63 @@ "action": "update", "approval": { "approvals": [], - "auto": "none-required", + "auto": null, "autoFallback": null, "reasons": [ - "dev change: 0 from approver-platform" + "dev change: 0 from approver-platform", + "threshold quotaIncreasePct > 100: +1 approver-platform" + ], + "remaining": [ + { + "group": "approver-platform", + "needed": 1 + } ], - "remaining": [], "rule": "dev-change", "selfApproval": true, - "slots": [], + "slots": [ + { + "count": 1, + "group": "approver-platform", + "reason": "quotaIncreasePct > 100" + } + ], "timeoutHours": 8 }, - "baseSha": "2b2f51e093acbd69fb6b2fb05c5acbef76ecb749", + "baseSha": "513f40b0ee251859ba80791976ccc3addcfdf1ba", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:11.598086Z", + "createdAt": "2026-12-01T15:12:57.455807Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:11.671849Z", + "at": "2026-12-01T15:12:57.536560Z", "by": "ola", - "event": "plan_auto_approved", - "note": "none-required", - "status": "approved" + "event": "plan_needs_approval", + "note": "waiting for [('approver-platform', 1)]", + "status": "pending_approval" } ], "files": { - "clusters/CRC/namespaces/notes-dev/limitrange-notes-dev-limits-cpu.yaml": "unchanged", - "clusters/CRC/namespaces/notes-dev/limitrange-notes-dev-limits-memory.yaml": "unchanged", - "clusters/CRC/namespaces/notes-dev/namespace.yaml": "changed", - "clusters/CRC/namespaces/notes-dev/resourcequota-notes-dev-quota.yaml": "unchanged", - "clusters/CRC/namespaces/notes-dev/token-issuer-rolebinding.yaml": "unchanged" + "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "changed", + "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "changed", + "clusters/CRC/namespaces/payments-dev/namespace.yaml": "changed", + "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "changed", + "clusters/CRC/namespaces/payments-dev/token-issuer-rolebinding.yaml": "unchanged" }, "instance": "nonprod", - "justification": "A load test this sprint", + "justification": "Load test next sprint", "links": { - "events": "/api/v1/requests/req-20261127-0012/events", - "self": "/api/v1/requests/req-20261127-0012" + "events": "/api/v1/requests/req-20261201-0002/events", + "self": "/api/v1/requests/req-20261201-0002" }, "mergeSha": null, - "namespace": "notes-dev", - "planHash": "9b232cebe5e7f6c7322d8707f3ec6242b41b2249fb7589b4e77ef7413540258c", + "namespace": "payments-dev", + "planHash": "7aebcbffedf4cef6b095bd7594ab08df7c4f3964ede6f8138b15048c990b9ed3", "plugin": "namespaces", "pr": null, - "reason": "expiration:set", - "requestId": "req-20261127-0012", + "reason": null, + "requestId": "req-20261201-0002", "requester": { "automated": false, "requester": { @@ -18112,8 +16522,8 @@ "submittedBy": null, "submittedByClient": null }, - "status": "approved", - "updatedAt": "2026-11-27T20:59:11.573014Z" + "status": "pending_approval", + "updatedAt": "2026-12-01T15:12:57.263260Z" }, "schema": { "$ref": "#/components/schemas/ChangeRequest" @@ -18180,7 +16590,7 @@ "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission namespaces:write: no role in your token grants it (roles: ['cmapi-requester'])", + "detail": "Missing permission namespaces:write: no role in your token grants it (roles: ['cmapi-approver'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -18201,7 +16611,7 @@ "cluster-not-found": { "value": { "code": "cluster-not-found", - "detail": "Unknown cluster OCP_X", + "detail": "Unknown cluster NOPE", "status": 404, "title": "cluster not found", "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" @@ -18210,7 +16620,7 @@ "object-not-found": { "value": { "code": "object-not-found", - "detail": "No request req-20261105-0001", + "detail": "not-there-dev is not managed on CRC", "status": 404, "title": "object not found", "type": "https://cmapi.ephico2real.com/problems/object-not-found" @@ -18231,7 +16641,8 @@ "change-pending": { "value": { "code": "change-pending", - "detail": "req-20261105-0001 holds payments-dev", + "detail": "req-20261201-0015 holds audit-dev", + "requestId": "req-20261201-0015", "status": 409, "title": "change pending", "type": "https://cmapi.ephico2real.com/problems/change-pending" @@ -18265,10 +16676,24 @@ "value": { "code": "idempotency-replay", "detail": "Idempotency-Key was used for a different request", + "requestId": "req-20261201-0015", "status": 409, "title": "idempotency replay", "type": "https://cmapi.ephico2real.com/problems/idempotency-replay" } + }, + "several-resource-quotas": { + "value": { + "code": "several-resource-quotas", + "detail": "The folder of payments-dev holds 2 ResourceQuotas, payments-dev-objects, payments-dev-quota: a change of the quota or the tier must name the object it changes, and a request cannot name one. Change only labels, annotations or the expiry, or leave one ResourceQuota in the folder in Git, then send the request again", + "resourceQuotas": [ + "payments-dev-objects", + "payments-dev-quota" + ], + "status": 409, + "title": "several resource quotas", + "type": "https://cmapi.ephico2real.com/problems/several-resource-quotas" + } } }, "schema": { @@ -18276,7 +16701,7 @@ } } }, - "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`." + "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`, `several-resource-quotas`." }, "412": { "content": { @@ -18286,6 +16711,7 @@ "value": { "code": "precondition-failed", "detail": "The namespace changed in Git since you read it", + "etag": "1b59766bf9a3bbe7", "status": 412, "title": "precondition failed", "type": "https://cmapi.ephico2real.com/problems/precondition-failed" @@ -18354,49 +16780,31 @@ "type": "https://cmapi.ephico2real.com/problems/environment-not-served" } }, - "expiration-already-set": { - "value": { - "code": "expiration-already-set", - "detail": "Use :extend to move an existing date", - "status": 422, - "title": "expiration already set", - "type": "https://cmapi.ephico2real.com/problems/expiration-already-set" - } - }, - "expiration-in-past": { - "value": { - "code": "expiration-in-past", - "detail": "The new date must be later than the current one", - "status": 422, - "title": "expiration in past", - "type": "https://cmapi.ephico2real.com/problems/expiration-in-past" - } - }, - "expiration-limit": { + "identity-incomplete": { "value": { - "code": "expiration-limit", - "detail": "An extension is at most 30 days", + "code": "identity-incomplete", + "detail": "The token has no employee_id claim", "status": 422, - "title": "expiration limit", - "type": "https://cmapi.ephico2real.com/problems/expiration-limit" + "title": "identity incomplete", + "type": "https://cmapi.ephico2real.com/problems/identity-incomplete" } }, - "expiration-not-allowed": { + "no-change": { "value": { - "code": "expiration-not-allowed", - "detail": "Production namespaces never expire", + "code": "no-change", + "detail": "The request changes nothing", "status": 422, - "title": "expiration not allowed", - "type": "https://cmapi.ephico2real.com/problems/expiration-not-allowed" + "title": "no change", + "type": "https://cmapi.ephico2real.com/problems/no-change" } }, - "identity-incomplete": { + "on-behalf-of-not-allowed": { "value": { - "code": "identity-incomplete", - "detail": "The token has no employee_id claim", + "code": "on-behalf-of-not-allowed", + "detail": "A person calls as themselves", "status": 422, - "title": "identity incomplete", - "type": "https://cmapi.ephico2real.com/problems/identity-incomplete" + "title": "on behalf of not allowed", + "type": "https://cmapi.ephico2real.com/problems/on-behalf-of-not-allowed" } }, "on-behalf-of-required": { @@ -18421,6 +16829,30 @@ "value": { "code": "policy-violation", "detail": "Metadata refused", + "errors": [ + { + "code": "reserved_key", + "key": "cmapi.net/tier" + }, + { + "code": "invalid_key", + "detail": "prefix not allowed", + "key": "other.example/x" + }, + { + "code": "invalid_value", + "detail": "must match ^[a-z0-9-]{2,40}$", + "key": "cmapi.net/team", + "kind": "label" + }, + { + "code": "missing_required_key", + "detail": "an address in ['ephico2real.com']", + "key": "cmapi.net/team-dl", + "kind": "annotation" + } + ], + "findings": [], "status": 422, "title": "policy violation", "type": "https://cmapi.ephico2real.com/problems/policy-violation" @@ -18435,10 +16867,26 @@ "type": "https://cmapi.ephico2real.com/problems/unknown-serviceaccount" } }, + "unknown-user": { + "value": { + "code": "unknown-user", + "detail": "1009 is not an enabled user", + "status": 422, + "title": "unknown user", + "type": "https://cmapi.ephico2real.com/problems/unknown-user" + } + }, "validation-failed": { "value": { "code": "validation-failed", - "detail": "Request body is not valid", + "detail": "The request is not valid: body.labels: Input should be a valid dictionary", + "errors": [ + { + "code": "dict_type", + "field": "body.labels", + "message": "Input should be a valid dictionary" + } + ], "status": 422, "title": "validation failed", "type": "https://cmapi.ephico2real.com/problems/validation-failed" @@ -18450,7 +16898,7 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `policy-violation`, `capacity-exceeded`, `unknown-serviceaccount`, `expiration-not-allowed`, `expiration-already-set`, `expiration-in-past`, `expiration-limit`." + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `unknown-user`, `on-behalf-of-not-allowed`, `policy-violation`, `capacity-exceeded`, `unknown-serviceaccount`, `no-change`." }, "428": { "content": { @@ -18459,7 +16907,7 @@ "precondition-required": { "value": { "code": "precondition-required", - "detail": "If-Match is required on a change", + "detail": "If-Match is required on a change; GET the namespace for its etag", "status": 428, "title": "precondition required", "type": "https://cmapi.ephico2real.com/problems/precondition-required" @@ -18594,7 +17042,7 @@ "keycloak": [] } ], - "summary": "Give a permanent namespace an expiry date", + "summary": "Change a namespace", "tags": [ "namespaces" ], @@ -18605,16 +17053,16 @@ { "label": "curl", "lang": "Shell", - "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev/expiration:set -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'If-Match: \"3f9a1c0b7e2d4a68\"' -H 'Content-Type: application/json' -d '{\"justification\": \"A load test this sprint\", \"until\": \"2026-12-18\"}'" + "source": "curl -X PATCH https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'If-Match: \"3f9a1c0b7e2d4a68\"' -H 'Content-Type: application/json' -d '{\"annotations\": {\"runbook.ephico2real.com/url\": \"https://wiki.ephico2real.com/payments/runbook\"}, \"justification\": \"A smaller size after the load test, with the metadata tidied\", \"labels\": {\"cmapi.net/cost-center\": null}, \"tier\": \"medium\"}'" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/clusters/{cluster_id}/namespaces/{ns}:adopt": { + "/api/v1/clusters/{cluster_id}/namespaces/{ns}/expiration:extend": { "post": { - "description": "Plans the adoption of a namespace that exists on the cluster and that cmapi does not manage, and submits it as a change\nrequest (plugin `adoption`, action `adopt`). The namespace must carry `cmapi.net/adopt: \"true\"`; any other is 409\n`namespace-not-adoptable`, whose `rule` says why.\n\ncmapi reads the live Namespace and each of its ResourceQuotas and LimitRanges, and writes them to the namespace's folder\nas they are: only what the API server sets is dropped, and each key under a skip prefix of adoption.yaml only when that\nchanges nothing on the cluster. It adds its own system keys and the tier `custom`; each ResourceQuota and LimitRange keeps\nits name, in its own file. Each difference from the instance's rules is a finding of the plan, never a change: a wrong or\nmissing key, a value beyond the custom bounds, a policy failure that the namespace already holds (`policy-ratcheted`).\n\n`labels` and `annotations` add keys that the namespace lacks (#739), so a team can supply the required metadata with the\nadoption: the candidates list and the plan's `adoption.missingKeys` name them. Each is checked as a change request checks\na key it adds: by its rule, and a key that cmapi fills in or that starts the name only with its one `value`. A key the\nnamespace already has is 422 `adoption-key-held`. Each key added is written to `namespace.yaml`, listed in `metadataDiff`\nand `adoption.supplied`, and a required one drops its `missing-required-key` finding. Leave both out to add nothing.\n\nThe request needs one approver of approver-platform, and one more when the plan has findings; no automatic approval covers\nit. After approval the bot opens the pull request. cmapi reads the objects again before it pushes the branch and in the pull\nrequest's check: a change since the plan fails the request (`adoption-plan-stale`), and the label removed cancels it.\n\n`dryRun=true` answers 200 with the plan, its files, findings and approval, and opens no request.\n\n**Requires** `namespaces:write`.", - "operationId": "adoption_adopt", + "description": "Extends the expiry by `days` (up to the environment's limit) or to `until`. A normal request: plan,\napproval, bot PR. Needs If-Match. `dryRun=true` answers 200 with the plan and the approval that would apply.\n\n**Requires** `namespaces:write`.", + "operationId": "namespaces_extend", "parameters": [ { "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", @@ -18679,327 +17127,83 @@ ], "title": "Idempotency-Key" } + }, + { + "description": "The namespace's etag from `GET .../namespaces/{ns}`, in double quotes as its `ETag` header gives it. Required on a change or a delete. A list of tags passes when one of them is the current etag (RFC 9110, section 13.1.1). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line. `*` is 428 `precondition-required`: If-Match must name the etag that was read. A weak tag (`W/\"...\"`) never matches. An Idempotency-Key replay returns the original request in its current state without comparing the tag.", + "in": "header", + "name": "If-Match", + "required": true, + "schema": { + "description": "The namespace's etag from `GET .../namespaces/{ns}`, in double quotes as its `ETag` header gives it. Required on a change or a delete. A list of tags passes when one of them is the current etag (RFC 9110, section 13.1.1). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line. `*` is 428 `precondition-required`: If-Match must name the etag that was read. A weak tag (`W/\"...\"`) never matches. An Idempotency-Key replay returns the original request in its current state without comparing the tag.", + "examples": [ + "\"3f9a1c0b7e2d4a68\"" + ], + "title": "If-Match", + "type": "string" + } } ], "requestBody": { "content": { "application/json": { "example": { - "annotations": { - "cmapi.net/team-dl": "abc-team@ephico2real.com" - }, - "justification": "Bring abc-rnd under cmapi", - "labels": { - "cmapi.net/team": "abc" - } + "days": 7, + "justification": "Another sprint" }, "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/AdoptBody" - }, - { - "type": "null" - } - ], - "title": "Body" + "$ref": "#/components/schemas/ExtendBody" } } - } + }, + "required": true }, "responses": { "200": { "content": { "application/json": { "example": { - "adoption": { - "keys": [ - { - "kept": false, - "key": "kubernetes.io/metadata.name", - "kind": "label", - "managers": [ - "kube-apiserver" - ], - "why": "none of its managers is kubectl-client-side-apply, whose fields Argo CD's client-side apply migration takes over, so it stays on the cluster" - }, - { - "kept": false, - "key": "pod-security.kubernetes.io/audit", - "kind": "label", - "managers": [ - "pod-security-admission-label-synchronization-controller" - ], - "why": "none of its managers is kubectl-client-side-apply, whose fields Argo CD's client-side apply migration takes over, so it stays on the cluster" - } - ], - "label": "cmapi.net/adopt", - "missingKeys": [ - { - "key": "cmapi.net/team", - "kind": "label", - "required": true, - "value": null - }, - { - "key": "cmapi.net/team-dl", - "kind": "annotation", - "required": true, - "value": null - }, - { - "key": "cmapi.net/cost-center", - "kind": "label", - "required": false, - "value": null - }, - { - "key": "cmapi.net/app", - "kind": "label", - "required": false, - "value": null - }, - { - "key": "cmapi.net/rightsizing", - "kind": "label", - "required": false, - "value": null - } - ], - "notAdopted": { - "RoleBinding": 0, - "ServiceAccount": 0 - }, - "objects": [ - { - "kind": "Namespace", - "name": "abc-rnd", - "resourceVersion": "100", - "uid": "uid-ns-1" - }, - { - "kind": "ResourceQuota", - "name": "abc-rnd-quota", - "resourceVersion": "101", - "uid": "uid-rq-1" - }, - { - "kind": "LimitRange", - "name": "abc-rnd-limits-cpu", - "resourceVersion": "102", - "uid": "uid-lr-cpu" - }, - { - "kind": "LimitRange", - "name": "abc-rnd-limits-memory", - "resourceVersion": "102", - "uid": "uid-lr-memory" - } - ], - "recognised": [ - "company.net/provisioner=cluster-configs" - ], - "snapshotHash": "4faf2e011429cbd08f98b6a27fd293c9bb220471dc4084f383d8e48d4dcc9435", - "supplied": { - "annotations": {}, - "labels": {} - } - }, - "approval": { - "approvals": [], - "auto": null, - "autoFallback": null, - "reasons": [ - "dev change: 0 from approver-platform", - "threshold beyondTier: +1 approver-platform", - "threshold plugin == \"adoption\": +1 approver-platform", - "threshold plugin == \"adoption\" and actionableFindingCount > 0: +1 approver-platform" - ], - "remaining": [ - { - "group": "approver-platform", - "needed": 3 - } + "adoption": null, + "approval": { + "approvals": [], + "auto": "none-required", + "autoFallback": null, + "reasons": [ + "dev change: 0 from approver-platform" ], + "remaining": [], "rule": "dev-change", "selfApproval": true, - "slots": [ - { - "count": 3, - "group": "approver-platform", - "reason": "Value beyond the tier; Adoption of an existing namespace; Adoption with findings" - } - ], + "slots": [], "timeoutHours": 8 }, - "beyondTier": { - "approvals": [ - { - "count": 1, - "group": "approver-platform", - "reason": "Value beyond the tier" - } - ], - "keys": [ - { - "key": "requests.cpu", - "requested": "40", - "tier": "32" - } - ] - }, + "beyondTier": null, "capacity": { - "bindingResource": null, + "bindingResource": "cpu", + "clusterId": "CRC", + "cpu": 0.25, "fresh": true, - "source": "adoption", + "memory": 0.2, + "reserved": { + "cpu": 24.0, + "memory": 51539607552 + }, + "source": "simulated", "status": "fits" }, "changes": { - "clusters/CRC/namespaces/abc-rnd/limitrange-abc-rnd-limits-cpu.yaml": "added", - "clusters/CRC/namespaces/abc-rnd/limitrange-abc-rnd-limits-memory.yaml": "added", - "clusters/CRC/namespaces/abc-rnd/namespace.yaml": "added", - "clusters/CRC/namespaces/abc-rnd/resourcequota-abc-rnd-quota.yaml": "added" + "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed" }, - "etag": "0", + "etag": "917c7a62361f9e08", "files": { - "clusters/CRC/namespaces/abc-rnd/limitrange-abc-rnd-limits-cpu.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: abc-rnd-limits-cpu\n namespace: abc-rnd\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: custom\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\nspec:\n limits:\n - type: Container\n defaultRequest:\n cpu: 100m\n max:\n cpu: '2'\n", - "clusters/CRC/namespaces/abc-rnd/limitrange-abc-rnd-limits-memory.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: abc-rnd-limits-memory\n namespace: abc-rnd\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: custom\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\nspec:\n limits:\n - type: Container\n defaultRequest:\n memory: 128Mi\n max:\n memory: 4Gi\n", - "clusters/CRC/namespaces/abc-rnd/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: abc-rnd\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: custom\n company.net/provisioner: cluster-configs\n cmapi.net/adopt: 'true'\n company.net/app-environment: rnd\n company.net/cl: '1'\n company.net/lob: amgsst\n company.net/mnemonic: abc\n company.net/mnemonic-confluence: ''\n company.net/mnemonic-group-contact: ''\n name: aao-rnd\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n company.net/app-environment: rnd\n", - "clusters/CRC/namespaces/abc-rnd/resourcequota-abc-rnd-quota.yaml": "apiVersion: v1\nkind: ResourceQuota\nmetadata:\n name: abc-rnd-quota\n namespace: abc-rnd\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: custom\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\nspec:\n hard:\n requests.cpu: '40'\n requests.memory: 64Gi\n pods: '100'\n scopes:\n - NotTerminating\n" + "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: sprint-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2027-01-04'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" }, - "findings": [ - { - "kyvernoRule": null, - "message": "label company.net/app-environment: no rule of this instance admits the label company.net/app-environment: kept; a request may remove it, never set it", - "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", - "rule": "unknown-key", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "label company.net/cl: no rule of this instance admits the label company.net/cl: kept; a request may remove it, never set it", - "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", - "rule": "unknown-key", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "label company.net/lob: no rule of this instance admits the label company.net/lob: kept; a request may remove it, never set it", - "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", - "rule": "unknown-key", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "label company.net/mnemonic: no rule of this instance admits the label company.net/mnemonic: kept; a request may remove it, never set it", - "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", - "rule": "unknown-key", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "label company.net/mnemonic-confluence: no rule of this instance admits the label company.net/mnemonic-confluence: kept; a request may remove it, never set it", - "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", - "rule": "unknown-key", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "label company.net/mnemonic-group-contact: no rule of this instance admits the label company.net/mnemonic-group-contact: kept; a request may remove it, never set it", - "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", - "rule": "unknown-key", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "label company.net/provisioner: company.net/provisioner=cluster-configs marks a namespace that another tool made (recognised): kept as it is", - "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", - "rule": "adoption-label", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "annotation company.net/app-environment: no rule of this instance admits the annotation company.net/app-environment: kept; a request may remove it, never set it", - "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", - "rule": "unknown-key", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "label cmapi.net/team: the required label cmapi.net/team is missing: never forced; each plan lists it until a request sets it", - "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", - "rule": "missing-required-key", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "annotation cmapi.net/team-dl: the required annotation cmapi.net/team-dl is missing: never forced; each plan lists it until a request sets it", - "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", - "rule": "missing-required-key", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "label kubernetes.io/metadata.name: left out of Git, none of its managers is kubectl-client-side-apply, whose fields Argo CD's client-side apply migration takes over, so it stays on the cluster (managers: kube-apiserver)", - "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", - "rule": "skipped-key", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "label pod-security.kubernetes.io/audit: left out of Git, none of its managers is kubectl-client-side-apply, whose fields Argo CD's client-side apply migration takes over, so it stays on the cluster (managers: pod-security-admission-label-synchronization-controller)", - "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", - "rule": "skipped-key", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "abc-rnd-quota: requests.cpu is 40, above the custom maximum 32: adopted as it is; a later change of it is checked and approved as usual", - "path": "clusters/CRC/namespaces/abc-rnd/resourcequota-abc-rnd-quota.yaml", - "rule": "beyond-custom-bounds", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "Only the scoped quotas abc-rnd-quota hold pods: its figure for the namespace is not known", - "path": "clusters/CRC/namespaces/abc-rnd/", - "rule": "scoped-only", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "Only the scoped quotas abc-rnd-quota hold requests.cpu: its figure for the namespace is not known", - "path": "clusters/CRC/namespaces/abc-rnd/", - "rule": "scoped-only", - "severity": "warning", - "source": "cmapi" - }, - { - "kyvernoRule": null, - "message": "Only the scoped quotas abc-rnd-quota hold requests.memory: its figure for the namespace is not known", - "path": "clusters/CRC/namespaces/abc-rnd/", - "rule": "scoped-only", - "severity": "warning", - "source": "cmapi" - } - ], + "findings": [], "metadata": null, - "metadataDiff": null, - "planHash": "f0e04fd12b310dc184cec1612861bc4fbf0a48c0f5e4f54f80e6cb144a954a2c", + "metadataDiff": { + "annotations": {}, + "labels": {} + }, + "planHash": "1f9cb50d801c839f9d81f17c0bdfa248ec47c1aa58de25faff503e675da9a4f6", "requester": { "automated": false, "requester": { @@ -19029,82 +17233,54 @@ "content": { "application/json": { "example": { - "action": "adopt", + "action": "update", "approval": { "approvals": [], - "auto": null, + "auto": "none-required", "autoFallback": null, "reasons": [ - "dev change: 0 from approver-platform", - "threshold beyondTier: +1 approver-platform", - "threshold plugin == \"adoption\": +1 approver-platform", - "threshold plugin == \"adoption\" and actionableFindingCount > 0: +1 approver-platform" - ], - "remaining": [ - { - "group": "approver-platform", - "needed": 3 - } + "dev change: 0 from approver-platform" ], + "remaining": [], "rule": "dev-change", "selfApproval": true, - "slots": [ - { - "count": 3, - "group": "approver-platform", - "reason": "Value beyond the tier; Adoption of an existing namespace; Adoption with findings" - } - ], + "slots": [], "timeoutHours": 8 }, - "baseSha": "ca16e8cc000b1d1f2305f2259948a58c6035e62a", - "beyondTier": { - "approvals": [ - { - "count": 1, - "group": "approver-platform", - "reason": "Value beyond the tier" - } - ], - "keys": [ - { - "key": "requests.cpu", - "requested": "40", - "tier": "32" - } - ] - }, + "baseSha": "fff48c23f20c46278e17f5d0f1143fbe488baf9f", + "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:16.210356Z", + "createdAt": "2026-12-01T15:13:04.324648Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:16.232805Z", + "at": "2026-12-01T15:13:04.427407Z", "by": "ola", - "event": "plan_needs_approval", - "note": "waiting for [('approver-platform', 3)]", - "status": "pending_approval" + "event": "plan_auto_approved", + "note": "none-required", + "status": "approved" } ], "files": { - "clusters/CRC/namespaces/abc-rnd/limitrange-abc-rnd-limits-cpu.yaml": "added", - "clusters/CRC/namespaces/abc-rnd/limitrange-abc-rnd-limits-memory.yaml": "added", - "clusters/CRC/namespaces/abc-rnd/namespace.yaml": "added", - "clusters/CRC/namespaces/abc-rnd/resourcequota-abc-rnd-quota.yaml": "added" + "clusters/CRC/namespaces/sprint-dev/limitrange-sprint-dev-limits-cpu.yaml": "unchanged", + "clusters/CRC/namespaces/sprint-dev/limitrange-sprint-dev-limits-memory.yaml": "unchanged", + "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed", + "clusters/CRC/namespaces/sprint-dev/resourcequota-sprint-dev-quota.yaml": "unchanged", + "clusters/CRC/namespaces/sprint-dev/token-issuer-rolebinding.yaml": "unchanged" }, "instance": "nonprod", - "justification": "Bring abc-rnd under cmapi", + "justification": "Another sprint", "links": { - "events": "/api/v1/requests/req-20261127-0016/events", - "self": "/api/v1/requests/req-20261127-0016" + "events": "/api/v1/requests/req-20261201-0004/events", + "self": "/api/v1/requests/req-20261201-0004" }, "mergeSha": null, - "namespace": "abc-rnd", - "planHash": "7630777637466bdb231a248db34b6e67aafe718082ab15403db130f4b28b73ee", - "plugin": "adoption", + "namespace": "sprint-dev", + "planHash": "94647a196d1eadd68a6e7f32e52ece621b84b432d66fe07079e993d28f81f1a4", + "plugin": "namespaces", "pr": null, - "reason": null, - "requestId": "req-20261127-0016", + "reason": "expiration:extend", + "requestId": "req-20261201-0004", "requester": { "automated": false, "requester": { @@ -19121,8 +17297,8 @@ "submittedBy": null, "submittedByClient": null }, - "status": "pending_approval", - "updatedAt": "2026-11-27T20:59:16.134586Z" + "status": "approved", + "updatedAt": "2026-12-01T15:13:04.155474Z" }, "schema": { "$ref": "#/components/schemas/ChangeRequest" @@ -19278,17 +17454,26 @@ "title": "idempotency replay", "type": "https://cmapi.ephico2real.com/problems/idempotency-replay" } - }, - "namespace-not-adoptable": { + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`." + }, + "412": { + "content": { + "application/problem+json": { + "examples": { + "precondition-failed": { "value": { - "application": "legacy-tools", - "code": "namespace-not-adoptable", - "detail": "legacy-tools is not a candidate for adoption: The Argo CD Application legacy-tools tracks legacy-tools", - "rule": "tracked-elsewhere", - "state": "skipped", - "status": 409, - "title": "namespace not adoptable", - "type": "https://cmapi.ephico2real.com/problems/namespace-not-adoptable" + "code": "precondition-failed", + "detail": "The namespace changed in Git since you read it", + "status": 412, + "title": "precondition failed", + "type": "https://cmapi.ephico2real.com/problems/precondition-failed" } } }, @@ -19297,7 +17482,7 @@ } } }, - "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`, `namespace-not-adoptable`." + "description": "No strong tag that If-Match lists is the object's ETag: it changed since it was read, or the value named none.\n\nCodes: `precondition-failed`." }, "413": { "content": { @@ -19325,19 +17510,13 @@ "content": { "application/problem+json": { "examples": { - "adoption-key-held": { + "capacity-exceeded": { "value": { - "code": "adoption-key-held", - "detail": "abc-rnd already has the label company.net/lob: an adoption keeps each key it finds as it is. Leave it out, and change it with a request after the adoption", - "keys": [ - { - "key": "company.net/lob", - "kind": "label" - } - ], + "code": "capacity-exceeded", + "detail": "memory would exceed the cluster", "status": 422, - "title": "adoption key held", - "type": "https://cmapi.ephico2real.com/problems/adoption-key-held" + "title": "capacity exceeded", + "type": "https://cmapi.ephico2real.com/problems/capacity-exceeded" } }, "cluster-not-writable": { @@ -19360,6 +17539,42 @@ "type": "https://cmapi.ephico2real.com/problems/environment-not-served" } }, + "expiration-in-past": { + "value": { + "code": "expiration-in-past", + "detail": "The new date must be later than the current one", + "status": 422, + "title": "expiration in past", + "type": "https://cmapi.ephico2real.com/problems/expiration-in-past" + } + }, + "expiration-limit": { + "value": { + "code": "expiration-limit", + "detail": "An extension is at most 30 days", + "status": 422, + "title": "expiration limit", + "type": "https://cmapi.ephico2real.com/problems/expiration-limit" + } + }, + "expiration-not-allowed": { + "value": { + "code": "expiration-not-allowed", + "detail": "Production namespaces never expire", + "status": 422, + "title": "expiration not allowed", + "type": "https://cmapi.ephico2real.com/problems/expiration-not-allowed" + } + }, + "expiration-not-set": { + "value": { + "code": "expiration-not-set", + "detail": "The namespace is permanent; use :set", + "status": 422, + "title": "expiration not set", + "type": "https://cmapi.ephico2real.com/problems/expiration-not-set" + } + }, "identity-incomplete": { "value": { "code": "identity-incomplete", @@ -19396,6 +17611,15 @@ "type": "https://cmapi.ephico2real.com/problems/policy-violation" } }, + "unknown-serviceaccount": { + "value": { + "code": "unknown-serviceaccount", + "detail": "ci-deployer is not a ServiceAccount of payments-dev", + "status": 422, + "title": "unknown serviceaccount", + "type": "https://cmapi.ephico2real.com/problems/unknown-serviceaccount" + } + }, "validation-failed": { "value": { "code": "validation-failed", @@ -19411,7 +17635,28 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `adoption-key-held`, `policy-violation`." + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `policy-violation`, `capacity-exceeded`, `unknown-serviceaccount`, `expiration-not-allowed`, `expiration-not-set`, `expiration-in-past`, `expiration-limit`." + }, + "428": { + "content": { + "application/problem+json": { + "examples": { + "precondition-required": { + "value": { + "code": "precondition-required", + "detail": "If-Match is required on a change", + "status": 428, + "title": "precondition required", + "type": "https://cmapi.ephico2real.com/problems/precondition-required" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A change needs If-Match with the ETag of the object as it was read; `*` is not one.\n\nCodes: `precondition-required`." }, "429": { "content": { @@ -19534,151 +17779,305 @@ "keycloak": [] } ], - "summary": "Adopt an existing namespace", + "summary": "Extend a namespace's expiry", "tags": [ - "adoption" + "namespaces" ], "x-cmapi-permission": "namespaces:write", - "x-cmapi-plugin": "adoption", + "x-cmapi-plugin": "namespaces", "x-cmapi-rate-limit": "write", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev:adopt -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'Content-Type: application/json' -d '{\"annotations\": {\"cmapi.net/team-dl\": \"abc-team@ephico2real.com\"}, \"justification\": \"Bring abc-rnd under cmapi\", \"labels\": {\"cmapi.net/team\": \"abc\"}}'" + "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev/expiration:extend -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'If-Match: \"3f9a1c0b7e2d4a68\"' -H 'Content-Type: application/json' -d '{\"days\": 7, \"justification\": \"Another sprint\"}'" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/clusters/{id}:probe": { + "/api/v1/clusters/{cluster_id}/namespaces/{ns}/expiration:makePermanent": { "post": { - "description": "Run the relist checks on this cluster's last discovered import and return its current diagnostics.\nNo Secret or cluster resource is changed. A known cluster without an import returns its not-imported view.\n\n**Requires** `operations:run`.", - "operationId": "core_probe", + "description": "Removes the expiry date (`cmapi.net/expires-at` and `cmapi.net/expiry`), so the namespace no longer expires. It always\nadds an approval from approver-platform (docs/01, Namespace expiration). A namespace with no date is refused with 422\nexpiration-not-set. It is taken where expiration is now off too, so a date given while it was on can be removed. A normal request: plan, approval, bot PR. Needs If-Match. `dryRun=true` answers 200 with the plan.\n\n**Requires** `namespaces:write`.", + "operationId": "namespaces_make_permanent", "parameters": [ { "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", "in": "path", - "name": "id", + "name": "cluster_id", "required": true, "schema": { "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", "examples": [ "CRC" ], - "title": "Id", + "title": "Cluster Id", "type": "string" } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "example": { - "checkedAt": "2026-11-27T20:58:53.587291Z", - "clusterId": "CRC", - "environment": "dev", - "findingDetails": [], - "findings": [], - "gitopsPath": "clusters/CRC", - "labels": { - "region": "us-central" - }, - "lastProbeAt": "2026-11-27T20:58:53.587291Z", - "secretName": "cmapi-cluster-crc", - "serverVersion": "v1.35.6-fake", - "status": "connected", - "statusSince": "2026-11-27T20:58:53.069187Z", - "tokenExpiresAt": null, - "trust": { - "downgrade": false, - "serverName": null, - "source": "trusted" - }, - "writes": true - }, - "schema": { - "$ref": "#/components/schemas/ClusterView" - } - } - }, - "description": "The cluster's diagnostics after the checks ran again: status, findings, server version and token expiry." }, - "400": { - "content": { - "application/problem+json": { - "examples": { - "dry-run-not-supported": { - "value": { - "code": "dry-run-not-supported", - "detail": "This call has no dry run, and nothing was done", - "status": 400, - "title": "dry run not supported", - "type": "https://cmapi.ephico2real.com/problems/dry-run-not-supported" - } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `dry-run-not-supported`." + { + "description": "The name of the namespace on that cluster.", + "in": "path", + "name": "ns", + "required": true, + "schema": { + "description": "The name of the namespace on that cluster.", + "examples": [ + "payments-dev" + ], + "title": "Ns", + "type": "string" + } }, - "401": { - "content": { - "application/problem+json": { - "examples": { - "unauthenticated": { - "value": { - "code": "unauthenticated", - "detail": "Bearer token required", - "status": 401, - "title": "unauthenticated", - "type": "https://cmapi.ephico2real.com/problems/unauthenticated" - } - } + { + "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", + "in": "query", + "name": "dryRun", + "required": false, + "schema": { + "default": false, + "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", + "examples": [ + true + ], + "title": "Dryrun", + "type": "boolean" + } + }, + { + "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state. The caller is the token's subject: a service that sends `onBehalfOf` holds its key, and the person cannot replay it: the person's own use of that key is a request of their own. The same key with another request is 409 `idempotency-replay`. The expiry writes do not compare `justification`: a retry that changes only it gets the original request.", + "in": "header", + "name": "Idempotency-Key", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state. The caller is the token's subject: a service that sends `onBehalfOf` holds its key, and the person cannot replay it: the person's own use of that key is a request of their own. The same key with another request is 409 `idempotency-replay`. The expiry writes do not compare `justification`: a retry that changes only it gets the original request.", + "examples": [ + "0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10" + ], + "title": "Idempotency-Key" + } + }, + { + "description": "The namespace's etag from `GET .../namespaces/{ns}`, in double quotes as its `ETag` header gives it. Required on a change or a delete. A list of tags passes when one of them is the current etag (RFC 9110, section 13.1.1). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line. `*` is 428 `precondition-required`: If-Match must name the etag that was read. A weak tag (`W/\"...\"`) never matches. An Idempotency-Key replay returns the original request in its current state without comparing the tag.", + "in": "header", + "name": "If-Match", + "required": true, + "schema": { + "description": "The namespace's etag from `GET .../namespaces/{ns}`, in double quotes as its `ETag` header gives it. Required on a change or a delete. A list of tags passes when one of them is the current etag (RFC 9110, section 13.1.1). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line. `*` is 428 `precondition-required`: If-Match must name the etag that was read. A weak tag (`W/\"...\"`) never matches. An Idempotency-Key replay returns the original request in its current state without comparing the tag.", + "examples": [ + "\"3f9a1c0b7e2d4a68\"" + ], + "title": "If-Match", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "example": { + "justification": "In production use" + }, + "schema": { + "$ref": "#/components/schemas/PermanentBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "adoption": null, + "approval": { + "approvals": [], + "auto": null, + "autoFallback": null, + "reasons": [ + "dev change: 0 from approver-platform", + "threshold expirationBeyondLimits: +1 approver-platform" + ], + "remaining": [ + { + "group": "approver-platform", + "needed": 1 + } + ], + "rule": "dev-change", + "selfApproval": true, + "slots": [ + { + "count": 1, + "group": "approver-platform", + "reason": "Expiry beyond limits" + } + ], + "timeoutHours": 8 + }, + "beyondTier": null, + "capacity": { + "bindingResource": "cpu", + "clusterId": "CRC", + "cpu": 0.25, + "fresh": true, + "memory": 0.2, + "reserved": { + "cpu": 24.0, + "memory": 51539607552 + }, + "source": "simulated", + "status": "fits" + }, + "changes": { + "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed" + }, + "etag": "917c7a62361f9e08", + "files": { + "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: sprint-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" + }, + "findings": [], + "metadata": null, + "metadataDiff": { + "annotations": {}, + "labels": {} + }, + "planHash": "70bbacf492d9d66211a7592e0a14a89dcac6317e2376b7674bc0ee2f01e6b85f", + "requester": { + "automated": false, + "requester": { + "clientId": "cmapi-portal", + "email": "ola@ephico2real.com", + "employeeId": "1001", + "familyName": "Doe", + "givenName": "Ola", + "kind": "user", + "middleName": null, + "sub": "sub-ola", + "username": "ola" + }, + "submittedBy": null, + "submittedByClient": null + }, + "usage": null }, "schema": { - "$ref": "#/components/schemas/ProblemDetail" + "$ref": "#/components/schemas/PlanView" } } }, - "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + "description": "Dry run (`?dryRun=true`): the plan. The call opens no change request, takes no lock or reservation, queues no job and opens no pull request." }, - "403": { + "202": { "content": { - "application/problem+json": { - "examples": { - "forbidden": { - "value": { - "code": "forbidden", - "detail": "Missing permission operations:run: no role in your token grants it (roles: ['cmapi-requester'])", - "status": 403, - "title": "forbidden", - "type": "https://cmapi.ephico2real.com/problems/forbidden" + "application/json": { + "example": { + "action": "update", + "approval": { + "approvals": [], + "auto": null, + "autoFallback": null, + "reasons": [ + "dev change: 0 from approver-platform", + "threshold expirationBeyondLimits: +1 approver-platform" + ], + "remaining": [ + { + "group": "approver-platform", + "needed": 1 + } + ], + "rule": "dev-change", + "selfApproval": true, + "slots": [ + { + "count": 1, + "group": "approver-platform", + "reason": "Expiry beyond limits" + } + ], + "timeoutHours": 8 + }, + "baseSha": "feb3ec3f7d9810aff0adcce6cd4aa4a92b85fefd", + "beyondTier": null, + "clusterId": "CRC", + "createdAt": "2026-12-01T15:13:30.640365Z", + "env": "dev", + "events": [ + { + "at": "2026-12-01T15:13:30.783091Z", + "by": "ola", + "event": "plan_needs_approval", + "note": "waiting for [('approver-platform', 1)]", + "status": "pending_approval" } - } + ], + "files": { + "clusters/CRC/namespaces/sprint-dev/limitrange-sprint-dev-limits-cpu.yaml": "unchanged", + "clusters/CRC/namespaces/sprint-dev/limitrange-sprint-dev-limits-memory.yaml": "unchanged", + "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed", + "clusters/CRC/namespaces/sprint-dev/resourcequota-sprint-dev-quota.yaml": "unchanged", + "clusters/CRC/namespaces/sprint-dev/token-issuer-rolebinding.yaml": "unchanged" + }, + "instance": "nonprod", + "justification": "In production use", + "links": { + "events": "/api/v1/requests/req-20261201-0013/events", + "self": "/api/v1/requests/req-20261201-0013" + }, + "mergeSha": null, + "namespace": "sprint-dev", + "planHash": "7e351d77c635272d0628a10556f6e2a86b180aac067848e44417651013b36b00", + "plugin": "namespaces", + "pr": null, + "reason": "expiration:makePermanent", + "requestId": "req-20261201-0013", + "requester": { + "automated": false, + "requester": { + "clientId": "cmapi-portal", + "email": "ola@ephico2real.com", + "employeeId": "1001", + "familyName": "Doe", + "givenName": "Ola", + "kind": "user", + "middleName": null, + "sub": "sub-ola", + "username": "ola" + }, + "submittedBy": null, + "submittedByClient": null + }, + "status": "pending_approval", + "updatedAt": "2026-12-01T15:13:30.497696Z" }, "schema": { - "$ref": "#/components/schemas/ProblemDetail" + "$ref": "#/components/schemas/ChangeRequest" } } }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + "description": "The request is created. It waits for approval unless a policy approves it at once: `status` and `approval` say which, and `links.events` follows it." }, - "404": { + "400": { "content": { "application/problem+json": { "examples": { - "cluster-not-found": { + "idempotency-key-required": { "value": { - "code": "cluster-not-found", - "detail": "Unknown cluster OCP_X", - "status": 404, - "title": "cluster not found", - "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" + "code": "idempotency-key-required", + "detail": "Idempotency-Key header is required on writes", + "status": 400, + "title": "idempotency key required", + "type": "https://cmapi.ephico2real.com/problems/idempotency-key-required" } } }, @@ -19687,19 +18086,19 @@ } } }, - "description": "What the path names is not known.\n\nCodes: `cluster-not-found`." + "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `idempotency-key-required`." }, - "422": { + "401": { "content": { "application/problem+json": { "examples": { - "validation-failed": { + "unauthenticated": { "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" } } }, @@ -19708,20 +18107,28 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." }, - "429": { + "403": { "content": { "application/problem+json": { "examples": { - "rate-limited": { + "environment-forbidden": { "value": { - "code": "rate-limited", - "detail": "Too many write calls by this caller; try again in 2 s", - "retryAfter": 2, - "status": 429, - "title": "rate limited", - "type": "https://cmapi.ephico2real.com/problems/rate-limited" + "code": "environment-forbidden", + "detail": "Your roles grant namespaces:write only in ['rnd'], not dev", + "status": 403, + "title": "environment forbidden", + "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" + } + }, + "forbidden": { + "value": { + "code": "forbidden", + "detail": "Missing permission namespaces:write: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" } } }, @@ -19730,30 +18137,28 @@ } } }, - "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } - } - } + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`, `environment-forbidden`." }, - "503": { + "404": { "content": { "application/problem+json": { "examples": { - "idp-unavailable": { + "cluster-not-found": { "value": { - "code": "idp-unavailable", - "detail": "Keycloak signing keys are unreachable and this key is not cached", - "retryAfter": 30, - "status": 503, - "title": "idp unavailable", - "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" + "code": "cluster-not-found", + "detail": "Unknown cluster OCP_X", + "status": 404, + "title": "cluster not found", + "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" + } + }, + "object-not-found": { + "value": { + "code": "object-not-found", + "detail": "No request req-20261105-0001", + "status": 404, + "title": "object not found", + "type": "https://cmapi.ephico2real.com/problems/object-not-found" } } }, @@ -19762,94 +18167,52 @@ } } }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } - } - } - } - }, - "security": [ - { - "keycloak": [] - } - ], - "summary": "Probe one cluster's held credential", - "tags": [ - "core" - ], - "x-cmapi-permission": "operations:run", - "x-cmapi-plugin": "core", - "x-cmapi-rate-limit": "write", - "x-codeSamples": [ - { - "label": "curl", - "lang": "Shell", - "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC:probe -H \"Authorization: Bearer $TOKEN\"" - } - ], - "x-plugin-version": "0.2.0" - } - }, - "/api/v1/directory/users": { - "get": { - "description": "Up to ten people matching the text, for the portal's people picker. The employee ID is returned to an\noperator (namespaces:protect) only.\n\n**Requires** `objects:read`.", - "operationId": "directory_search", - "parameters": [ - { - "description": "Two or more characters of a username, a name or an email address.", - "in": "query", - "name": "q", - "required": true, - "schema": { - "description": "Two or more characters of a username, a name or an email address.", - "examples": [ - "ada" - ], - "minLength": 2, - "title": "Q", - "type": "string" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "example": { - "items": [ - { - "email": "ola@ephico2real.com", - "employeeId": null, - "name": "Ola Adeyemi", - "username": "ola" - } - ] - }, - "schema": { - "$ref": "#/components/schemas/DirectoryUsers" - } - } - }, - "description": "The people whose username, name or email address matches." + "description": "What the path names is not known.\n\nCodes: `cluster-not-found`, `object-not-found`." }, - "401": { + "409": { "content": { "application/problem+json": { "examples": { - "unauthenticated": { + "change-pending": { "value": { - "code": "unauthenticated", - "detail": "Bearer token required", - "status": 401, - "title": "unauthenticated", - "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + "code": "change-pending", + "detail": "req-20261105-0001 holds payments-dev", + "status": 409, + "title": "change pending", + "type": "https://cmapi.ephico2real.com/problems/change-pending" + } + }, + "folder-not-utf8": { + "value": { + "code": "folder-not-utf8", + "detail": "The folder of payments-dev holds clusters/CRC/namespaces/payments-dev/caf\\xe9.yaml, whose name is not UTF-8: cmapi carries a folder's names and manifests as UTF-8 text. Rename it in Git, then send the request again", + "paths": [ + "clusters/CRC/namespaces/payments-dev/caf\\xe9.yaml" + ], + "status": 409, + "title": "folder not utf8", + "type": "https://cmapi.ephico2real.com/problems/folder-not-utf8" + } + }, + "folder-not-yaml": { + "value": { + "code": "folder-not-yaml", + "detail": "The folder of payments-dev holds clusters/CRC/namespaces/payments-dev/namespace.yaml, which is not YAML: expected ',' or '}', but got '' at line 4, column 1. Correct it in Git, then send the request again", + "paths": [ + "clusters/CRC/namespaces/payments-dev/namespace.yaml" + ], + "status": 409, + "title": "folder not yaml", + "type": "https://cmapi.ephico2real.com/problems/folder-not-yaml" + } + }, + "idempotency-replay": { + "value": { + "code": "idempotency-replay", + "detail": "Idempotency-Key was used for a different request", + "status": 409, + "title": "idempotency replay", + "type": "https://cmapi.ephico2real.com/problems/idempotency-replay" } } }, @@ -19858,19 +18221,19 @@ } } }, - "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`." }, - "403": { + "412": { "content": { "application/problem+json": { "examples": { - "forbidden": { + "precondition-failed": { "value": { - "code": "forbidden", - "detail": "Missing permission objects:read: no role in your token grants it (roles: ['cmapi-requester'])", - "status": 403, - "title": "forbidden", - "type": "https://cmapi.ephico2real.com/problems/forbidden" + "code": "precondition-failed", + "detail": "The namespace changed in Git since you read it", + "status": 412, + "title": "precondition failed", + "type": "https://cmapi.ephico2real.com/problems/precondition-failed" } } }, @@ -19879,19 +18242,20 @@ } } }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + "description": "No strong tag that If-Match lists is the object's ETag: it changed since it was read, or the value named none.\n\nCodes: `precondition-failed`." }, - "422": { + "413": { "content": { "application/problem+json": { "examples": { - "validation-failed": { + "content-too-large": { "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" + "code": "content-too-large", + "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", + "maxBytes": 1048576, + "status": 413, + "title": "content too large", + "type": "https://cmapi.ephico2real.com/problems/content-too-large" } } }, @@ -19900,27 +18264,161 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." }, - "429": { + "422": { "content": { "application/problem+json": { "examples": { - "rate-limited": { + "capacity-exceeded": { "value": { - "code": "rate-limited", - "detail": "Too many write calls by this caller; try again in 2 s", - "retryAfter": 2, - "status": 429, - "title": "rate limited", - "type": "https://cmapi.ephico2real.com/problems/rate-limited" + "code": "capacity-exceeded", + "detail": "memory would exceed the cluster", + "status": 422, + "title": "capacity exceeded", + "type": "https://cmapi.ephico2real.com/problems/capacity-exceeded" } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } + }, + "cluster-not-writable": { + "value": { + "code": "cluster-not-writable", + "detail": "CRC is imported but has no clusters.yaml entry", + "status": 422, + "title": "cluster not writable", + "type": "https://cmapi.ephico2real.com/problems/cluster-not-writable" + } + }, + "environment-not-served": { + "value": { + "code": "environment-not-served", + "detail": "qa is not served by the nonprod instance", + "instanceUrl": "https://cmapi-staging.ephico2real.com", + "portalUrl": "https://portal-staging.ephico2real.com", + "status": 422, + "title": "environment not served", + "type": "https://cmapi.ephico2real.com/problems/environment-not-served" + } + }, + "expiration-not-allowed": { + "value": { + "code": "expiration-not-allowed", + "detail": "Production namespaces never expire", + "status": 422, + "title": "expiration not allowed", + "type": "https://cmapi.ephico2real.com/problems/expiration-not-allowed" + } + }, + "expiration-not-set": { + "value": { + "code": "expiration-not-set", + "detail": "The namespace is permanent; use :set", + "status": 422, + "title": "expiration not set", + "type": "https://cmapi.ephico2real.com/problems/expiration-not-set" + } + }, + "identity-incomplete": { + "value": { + "code": "identity-incomplete", + "detail": "The token has no employee_id claim", + "status": 422, + "title": "identity incomplete", + "type": "https://cmapi.ephico2real.com/problems/identity-incomplete" + } + }, + "on-behalf-of-required": { + "value": { + "code": "on-behalf-of-required", + "detail": "A service client must name the person", + "status": 422, + "title": "on behalf of required", + "type": "https://cmapi.ephico2real.com/problems/on-behalf-of-required" + } + }, + "plugin-disabled": { + "value": { + "code": "plugin-disabled", + "detail": "The namespaces plugin takes no writes in dev on the nonprod instance: plugins.yaml disables it there", + "status": 422, + "title": "plugin disabled", + "type": "https://cmapi.ephico2real.com/problems/plugin-disabled" + } + }, + "policy-violation": { + "value": { + "code": "policy-violation", + "detail": "Metadata refused", + "status": 422, + "title": "policy violation", + "type": "https://cmapi.ephico2real.com/problems/policy-violation" + } + }, + "unknown-serviceaccount": { + "value": { + "code": "unknown-serviceaccount", + "detail": "ci-deployer is not a ServiceAccount of payments-dev", + "status": 422, + "title": "unknown serviceaccount", + "type": "https://cmapi.ephico2real.com/problems/unknown-serviceaccount" + } + }, + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `policy-violation`, `capacity-exceeded`, `unknown-serviceaccount`, `expiration-not-allowed`, `expiration-not-set`." + }, + "428": { + "content": { + "application/problem+json": { + "examples": { + "precondition-required": { + "value": { + "code": "precondition-required", + "detail": "If-Match is required on a change", + "status": 428, + "title": "precondition required", + "type": "https://cmapi.ephico2real.com/problems/precondition-required" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A change needs If-Match with the ETag of the object as it was read; `*` is not one.\n\nCodes: `precondition-required`." + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate-limited": { + "value": { + "code": "rate-limited", + "detail": "Too many write calls by this caller; try again in 2 s", + "retryAfter": 2, + "status": 429, + "title": "rate limited", + "type": "https://cmapi.ephico2real.com/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } }, "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", "headers": { @@ -19934,10 +18432,41 @@ } } }, + "502": { + "content": { + "application/problem+json": { + "examples": { + "git-unavailable": { + "value": { + "code": "git-unavailable", + "detail": "The Git host answered 500", + "status": 502, + "title": "git unavailable", + "type": "https://cmapi.ephico2real.com/problems/git-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The Git host failed.\n\nCodes: `git-unavailable`." + }, "503": { "content": { "application/problem+json": { "examples": { + "cluster-unreachable": { + "value": { + "code": "cluster-unreachable", + "detail": "CRC did not answer", + "retryAfter": 30, + "status": 503, + "title": "cluster unreachable", + "type": "https://cmapi.ephico2real.com/problems/cluster-unreachable" + } + }, "idp-unavailable": { "value": { "code": "idp-unavailable", @@ -19947,6 +18476,26 @@ "title": "idp unavailable", "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" } + }, + "validator-busy": { + "value": { + "code": "validator-busy", + "detail": "The policy check is temporarily busy. Try again after the delay in Retry-After.", + "retryAfter": 15, + "status": 503, + "title": "validator busy", + "type": "https://cmapi.ephico2real.com/problems/validator-busy" + } + }, + "validator-unavailable": { + "value": { + "code": "validator-unavailable", + "detail": "kubeconform did not start", + "retryAfter": 60, + "status": 503, + "title": "validator unavailable", + "type": "https://cmapi.ephico2real.com/problems/validator-unavailable" + } } }, "schema": { @@ -19954,7 +18503,7 @@ } } }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `cluster-unreachable`, `validator-unavailable`, `validator-busy`, `idp-unavailable`.", "headers": { "Retry-After": { "description": "The seconds to wait before the next call: the same number as `retryAfter`.", @@ -19972,113 +18521,282 @@ "keycloak": [] } ], - "summary": "Search people", + "summary": "Remove a namespace's expiry", "tags": [ - "directory" + "namespaces" ], - "x-cmapi-permission": "objects:read", - "x-cmapi-plugin": "directory", - "x-cmapi-rate-limit": "read", + "x-cmapi-permission": "namespaces:write", + "x-cmapi-plugin": "namespaces", + "x-cmapi-rate-limit": "write", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X GET 'https://cmapi-nonprod.ephico2real.com/api/v1/directory/users?q=ada' -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev/expiration:makePermanent -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'If-Match: \"3f9a1c0b7e2d4a68\"' -H 'Content-Type: application/json' -d '{\"justification\": \"In production use\"}'" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/directory/users/{username}": { - "get": { - "description": "A person by username (cached 15 minutes, served from the cache when Keycloak is unreachable).\n\n**Requires** `objects:read`.", - "operationId": "directory_get_user", + "/api/v1/clusters/{cluster_id}/namespaces/{ns}/expiration:set": { + "post": { + "description": "Gives a namespace that has no expiry the date `until`: after today, and at most the environment's maxExtensionDays\naway. A namespace that has a date is refused with 422 expiration-already-set: use :extend. A normal request: plan,\napproval, bot PR. Needs If-Match. `dryRun=true` answers 200 with the plan and the approval that would apply.\n\n**Requires** `namespaces:write`.", + "operationId": "namespaces_set_expiry", "parameters": [ { - "description": "The person's username in Keycloak (`preferred_username`).", + "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", "in": "path", - "name": "username", + "name": "cluster_id", "required": true, "schema": { - "description": "The person's username in Keycloak (`preferred_username`).", + "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", "examples": [ - "cmapi.requester" + "CRC" ], - "title": "Username", + "title": "Cluster Id", "type": "string" } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "example": { - "email": "ola@ephico2real.com", - "employeeId": null, - "name": "Ola Adeyemi", - "username": "ola" - }, - "schema": { - "$ref": "#/components/schemas/DirectoryUser" - } - } - }, - "description": "The person's username, name and email address, and the employee ID for an operator only." }, - "401": { - "content": { - "application/problem+json": { - "examples": { - "unauthenticated": { - "value": { - "code": "unauthenticated", - "detail": "Bearer token required", - "status": 401, - "title": "unauthenticated", - "type": "https://cmapi.ephico2real.com/problems/unauthenticated" - } - } - }, + { + "description": "The name of the namespace on that cluster.", + "in": "path", + "name": "ns", + "required": true, + "schema": { + "description": "The name of the namespace on that cluster.", + "examples": [ + "payments-dev" + ], + "title": "Ns", + "type": "string" + } + }, + { + "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", + "in": "query", + "name": "dryRun", + "required": false, + "schema": { + "default": false, + "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", + "examples": [ + true + ], + "title": "Dryrun", + "type": "boolean" + } + }, + { + "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state. The caller is the token's subject: a service that sends `onBehalfOf` holds its key, and the person cannot replay it: the person's own use of that key is a request of their own. The same key with another request is 409 `idempotency-replay`. The expiry writes do not compare `justification`: a retry that changes only it gets the original request.", + "in": "header", + "name": "Idempotency-Key", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state. The caller is the token's subject: a service that sends `onBehalfOf` holds its key, and the person cannot replay it: the person's own use of that key is a request of their own. The same key with another request is 409 `idempotency-replay`. The expiry writes do not compare `justification`: a retry that changes only it gets the original request.", + "examples": [ + "0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10" + ], + "title": "Idempotency-Key" + } + }, + { + "description": "The namespace's etag from `GET .../namespaces/{ns}`, in double quotes as its `ETag` header gives it. Required on a change or a delete. A list of tags passes when one of them is the current etag (RFC 9110, section 13.1.1). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line. `*` is 428 `precondition-required`: If-Match must name the etag that was read. A weak tag (`W/\"...\"`) never matches. An Idempotency-Key replay returns the original request in its current state without comparing the tag.", + "in": "header", + "name": "If-Match", + "required": true, + "schema": { + "description": "The namespace's etag from `GET .../namespaces/{ns}`, in double quotes as its `ETag` header gives it. Required on a change or a delete. A list of tags passes when one of them is the current etag (RFC 9110, section 13.1.1). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line. `*` is 428 `precondition-required`: If-Match must name the etag that was read. A weak tag (`W/\"...\"`) never matches. An Idempotency-Key replay returns the original request in its current state without comparing the tag.", + "examples": [ + "\"3f9a1c0b7e2d4a68\"" + ], + "title": "If-Match", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "example": { + "justification": "A load test this sprint", + "until": "2026-12-22" + }, + "schema": { + "$ref": "#/components/schemas/SetBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "adoption": null, + "approval": { + "approvals": [], + "auto": "none-required", + "autoFallback": null, + "reasons": [ + "dev change: 0 from approver-platform" + ], + "remaining": [], + "rule": "dev-change", + "selfApproval": true, + "slots": [], + "timeoutHours": 8 + }, + "beyondTier": null, + "capacity": { + "bindingResource": "cpu", + "clusterId": "CRC", + "cpu": 0.25, + "fresh": true, + "memory": 0.2, + "reserved": { + "cpu": 24.0, + "memory": 51539607552 + }, + "source": "simulated", + "status": "fits" + }, + "changes": { + "clusters/CRC/namespaces/notes-dev/namespace.yaml": "changed" + }, + "etag": "fc99df943d89d3a5", + "files": { + "clusters/CRC/namespaces/notes-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: notes-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2026-12-22'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" + }, + "findings": [], + "metadata": null, + "metadataDiff": { + "annotations": {}, + "labels": {} + }, + "planHash": "9c1158dfa0d79c5c9f0c241dec6a32d5b2a292a37433713da86353035f89f39e", + "requester": { + "automated": false, + "requester": { + "clientId": "cmapi-portal", + "email": "ola@ephico2real.com", + "employeeId": "1001", + "familyName": "Doe", + "givenName": "Ola", + "kind": "user", + "middleName": null, + "sub": "sub-ola", + "username": "ola" + }, + "submittedBy": null, + "submittedByClient": null + }, + "usage": null + }, "schema": { - "$ref": "#/components/schemas/ProblemDetail" + "$ref": "#/components/schemas/PlanView" } } }, - "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + "description": "Dry run (`?dryRun=true`): the plan. The call opens no change request, takes no lock or reservation, queues no job and opens no pull request." }, - "403": { + "202": { "content": { - "application/problem+json": { - "examples": { - "forbidden": { - "value": { - "code": "forbidden", - "detail": "Missing permission objects:read: no role in your token grants it (roles: ['cmapi-requester'])", - "status": 403, - "title": "forbidden", - "type": "https://cmapi.ephico2real.com/problems/forbidden" + "application/json": { + "example": { + "action": "update", + "approval": { + "approvals": [], + "auto": "none-required", + "autoFallback": null, + "reasons": [ + "dev change: 0 from approver-platform" + ], + "remaining": [], + "rule": "dev-change", + "selfApproval": true, + "slots": [], + "timeoutHours": 8 + }, + "baseSha": "efebfc8bb689241a62f847984e2721f3262dc61f", + "beyondTier": null, + "clusterId": "CRC", + "createdAt": "2026-12-01T15:13:28.971548Z", + "env": "dev", + "events": [ + { + "at": "2026-12-01T15:13:29.129136Z", + "by": "ola", + "event": "plan_auto_approved", + "note": "none-required", + "status": "approved" } - } + ], + "files": { + "clusters/CRC/namespaces/notes-dev/limitrange-notes-dev-limits-cpu.yaml": "unchanged", + "clusters/CRC/namespaces/notes-dev/limitrange-notes-dev-limits-memory.yaml": "unchanged", + "clusters/CRC/namespaces/notes-dev/namespace.yaml": "changed", + "clusters/CRC/namespaces/notes-dev/resourcequota-notes-dev-quota.yaml": "unchanged", + "clusters/CRC/namespaces/notes-dev/token-issuer-rolebinding.yaml": "unchanged" + }, + "instance": "nonprod", + "justification": "A load test this sprint", + "links": { + "events": "/api/v1/requests/req-20261201-0012/events", + "self": "/api/v1/requests/req-20261201-0012" + }, + "mergeSha": null, + "namespace": "notes-dev", + "planHash": "e03939885c418d98170f15ddf95c7ff62ccfa9557329000845f1b4171c55cc30", + "plugin": "namespaces", + "pr": null, + "reason": "expiration:set", + "requestId": "req-20261201-0012", + "requester": { + "automated": false, + "requester": { + "clientId": "cmapi-portal", + "email": "ola@ephico2real.com", + "employeeId": "1001", + "familyName": "Doe", + "givenName": "Ola", + "kind": "user", + "middleName": null, + "sub": "sub-ola", + "username": "ola" + }, + "submittedBy": null, + "submittedByClient": null + }, + "status": "approved", + "updatedAt": "2026-12-01T15:13:28.855961Z" }, "schema": { - "$ref": "#/components/schemas/ProblemDetail" + "$ref": "#/components/schemas/ChangeRequest" } } }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + "description": "The request is created. It waits for approval unless a policy approves it at once: `status` and `approval` say which, and `links.events` follows it." }, - "404": { + "400": { "content": { "application/problem+json": { "examples": { - "object-not-found": { + "idempotency-key-required": { "value": { - "code": "object-not-found", - "detail": "No request req-20261105-0001", - "status": 404, - "title": "object not found", - "type": "https://cmapi.ephico2real.com/problems/object-not-found" + "code": "idempotency-key-required", + "detail": "Idempotency-Key header is required on writes", + "status": 400, + "title": "idempotency key required", + "type": "https://cmapi.ephico2real.com/problems/idempotency-key-required" } } }, @@ -20087,19 +18805,19 @@ } } }, - "description": "What the path names is not known.\n\nCodes: `object-not-found`." + "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `idempotency-key-required`." }, - "422": { + "401": { "content": { "application/problem+json": { "examples": { - "validation-failed": { + "unauthenticated": { "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" } } }, @@ -20108,20 +18826,28 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." }, - "429": { + "403": { "content": { "application/problem+json": { "examples": { - "rate-limited": { + "environment-forbidden": { "value": { - "code": "rate-limited", - "detail": "Too many write calls by this caller; try again in 2 s", - "retryAfter": 2, - "status": 429, - "title": "rate limited", - "type": "https://cmapi.ephico2real.com/problems/rate-limited" + "code": "environment-forbidden", + "detail": "Your roles grant namespaces:write only in ['rnd'], not dev", + "status": 403, + "title": "environment forbidden", + "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" + } + }, + "forbidden": { + "value": { + "code": "forbidden", + "detail": "Missing permission namespaces:write: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" } } }, @@ -20130,30 +18856,28 @@ } } }, - "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } - } - } + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`, `environment-forbidden`." }, - "503": { + "404": { "content": { "application/problem+json": { "examples": { - "idp-unavailable": { + "cluster-not-found": { "value": { - "code": "idp-unavailable", - "detail": "Keycloak signing keys are unreachable and this key is not cached", - "retryAfter": 30, - "status": 503, - "title": "idp unavailable", - "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" + "code": "cluster-not-found", + "detail": "Unknown cluster OCP_X", + "status": 404, + "title": "cluster not found", + "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" + } + }, + "object-not-found": { + "value": { + "code": "object-not-found", + "detail": "No request req-20261105-0001", + "status": 404, + "title": "object not found", + "type": "https://cmapi.ephico2real.com/problems/object-not-found" } } }, @@ -20162,373 +18886,226 @@ } } }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", - "headers": { - "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, - "schema": { - "minimum": 1, - "type": "integer" - } - } - } - } - }, - "security": [ - { - "keycloak": [] - } - ], - "summary": "Get a directory user", - "tags": [ - "directory" - ], - "x-cmapi-permission": "objects:read", - "x-cmapi-plugin": "directory", - "x-cmapi-rate-limit": "read", - "x-codeSamples": [ - { - "label": "curl", - "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/directory/users/cmapi.requester -H \"Authorization: Bearer $TOKEN\"" - } - ], - "x-plugin-version": "0.2.0" - } - }, - "/api/v1/expirations": { - "get": { - "description": "One page of the managed namespaces that can expire, in the caller's environments: each one's expiry date from the\nwatch cache, the days left, its state and the notices sent, the count of each state over the other filters, and the\nrules of each environment. Where expiration is off (no entry in expiration.yaml, or enabled: false, such as prod), only a\nnamespace that kept a date from before is listed, with :makePermanent as its one action, and the environment has no\nrules. `today` is the day the API counts from.\n\n**Requires** `objects:read`.", - "operationId": "expiration_expirations", - "parameters": [ - { - "description": "Text that the name, the team label or the app label contains. Case does not matter.", - "in": "query", - "name": "q", - "required": false, - "schema": { - "default": "", - "description": "Text that the name, the team label or the app label contains. Case does not matter.", - "examples": [ - "payments" - ], - "title": "Q", - "type": "string" - } + "description": "What the path names is not known.\n\nCodes: `cluster-not-found`, `object-not-found`." }, - { - "description": "Only the namespaces of this environment (`cmapi.net/env`).", - "in": "query", - "name": "env", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" + "409": { + "content": { + "application/problem+json": { + "examples": { + "change-pending": { + "value": { + "code": "change-pending", + "detail": "req-20261105-0001 holds payments-dev", + "status": 409, + "title": "change pending", + "type": "https://cmapi.ephico2real.com/problems/change-pending" + } + }, + "folder-not-utf8": { + "value": { + "code": "folder-not-utf8", + "detail": "The folder of payments-dev holds clusters/CRC/namespaces/payments-dev/caf\\xe9.yaml, whose name is not UTF-8: cmapi carries a folder's names and manifests as UTF-8 text. Rename it in Git, then send the request again", + "paths": [ + "clusters/CRC/namespaces/payments-dev/caf\\xe9.yaml" + ], + "status": 409, + "title": "folder not utf8", + "type": "https://cmapi.ephico2real.com/problems/folder-not-utf8" + } + }, + "folder-not-yaml": { + "value": { + "code": "folder-not-yaml", + "detail": "The folder of payments-dev holds clusters/CRC/namespaces/payments-dev/namespace.yaml, which is not YAML: expected ',' or '}', but got '' at line 4, column 1. Correct it in Git, then send the request again", + "paths": [ + "clusters/CRC/namespaces/payments-dev/namespace.yaml" + ], + "status": 409, + "title": "folder not yaml", + "type": "https://cmapi.ephico2real.com/problems/folder-not-yaml" + } + }, + "idempotency-replay": { + "value": { + "code": "idempotency-replay", + "detail": "Idempotency-Key was used for a different request", + "status": 409, + "title": "idempotency replay", + "type": "https://cmapi.ephico2real.com/problems/idempotency-replay" + } + } }, - { - "type": "null" + "schema": { + "$ref": "#/components/schemas/ProblemDetail" } - ], - "description": "Only the namespaces of this environment (`cmapi.net/env`).", - "examples": [ - "dev" - ], - "title": "Env" - } + } + }, + "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`." }, - { - "description": "Only the namespaces on this cluster.", - "in": "query", - "name": "clusterId", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" + "412": { + "content": { + "application/problem+json": { + "examples": { + "precondition-failed": { + "value": { + "code": "precondition-failed", + "detail": "The namespace changed in Git since you read it", + "status": 412, + "title": "precondition failed", + "type": "https://cmapi.ephico2real.com/problems/precondition-failed" + } + } }, - { - "type": "null" + "schema": { + "$ref": "#/components/schemas/ProblemDetail" } - ], - "description": "Only the namespaces on this cluster.", - "examples": [ - "CRC" - ], - "title": "Clusterid" - } + } + }, + "description": "No strong tag that If-Match lists is the object's ETag: it changed since it was read, or the value named none.\n\nCodes: `precondition-failed`." }, - { - "description": "Only the namespaces of this team (`cmapi.net/team`).", - "in": "query", - "name": "team", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" + "413": { + "content": { + "application/problem+json": { + "examples": { + "content-too-large": { + "value": { + "code": "content-too-large", + "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", + "maxBytes": 1048576, + "status": 413, + "title": "content too large", + "type": "https://cmapi.ephico2real.com/problems/content-too-large" + } + } }, - { - "type": "null" + "schema": { + "$ref": "#/components/schemas/ProblemDetail" } - ], - "description": "Only the namespaces of this team (`cmapi.net/team`).", - "examples": [ - "payments" - ], - "title": "Team" - } + } + }, + "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." }, - { - "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`.", - "in": "query", - "name": "state", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "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`.", - "examples": [ - "attention" - ], - "title": "State" - } - }, - { - "description": "`urgency` puts the most urgent first: grace, expiring, pending_delete, active, then permanent, and in each the fewest days left first. `name` sorts by name, A to Z.", - "in": "query", - "name": "sort", - "required": false, - "schema": { - "default": "urgency", - "description": "`urgency` puts the most urgent first: grace, expiring, pending_delete, active, then permanent, and in each the fewest days left first. `name` sorts by name, A to Z.", - "examples": [ - "urgency" - ], - "title": "Sort", - "type": "string" - } - }, - { - "description": "The number of rows in one page: 25, 50 or 100, and never more than 200. A larger result is not cut: `page.nextCursor` gives the next page.", - "in": "query", - "name": "limit", - "required": false, - "schema": { - "default": 50, - "description": "The number of rows in one page: 25, 50 or 100, and never more than 200. A larger result is not cut: `page.nextCursor` gives the next page.", - "examples": [ - 50 - ], - "title": "Limit", - "type": "integer" - } - }, - { - "description": "`page.nextCursor` or `page.prevCursor` of an earlier page of the same filters and sort. A cursor of other filters returns 400 `invalid-cursor`.", - "in": "query", - "name": "cursor", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "`page.nextCursor` or `page.prevCursor` of an earlier page of the same filters and sort. A cursor of other filters returns 400 `invalid-cursor`.", - "examples": [ - "eyJrIjpbInBheW1lbnRzLWRldiIsIkNSQyJdLCJkIjoibmV4dCJ9.2f1c" - ], - "title": "Cursor" - } - } - ], - "responses": { - "200": { + "422": { "content": { - "application/json": { - "example": { - "facets": { - "active": 2, - "attention": 0, - "expiring": 0, - "grace": 0, - "pending_delete": 0, - "permanent": 1 - }, - "items": [ - { - "actions": [ - "extend", - "makePermanent" - ], - "app": null, - "clusterId": "CRC", - "created": "2026-11-27", - "daysLeft": 21, - "env": "dev", - "expiresAt": "2026-12-18", - "graceEnds": "2026-12-25", - "lifetimeDays": 21, - "name": "notes-dev", - "noticesSent": 0, - "openRequest": null, - "state": "active", - "team": "payments" - }, - { - "actions": [ - "extend", - "makePermanent" - ], - "app": null, - "clusterId": "CRC", - "created": "2026-11-27", - "daysLeft": 27, - "env": "dev", - "expiresAt": "2026-12-24", - "graceEnds": "2026-12-31", - "lifetimeDays": 27, - "name": "sprint-dev", - "noticesSent": 0, - "openRequest": "req-20261127-0013", - "state": "active", - "team": "payments" - }, - { - "actions": [ - "set" - ], - "app": null, - "clusterId": "CRC", - "created": "2026-11-27", - "daysLeft": null, - "env": "dev", - "expiresAt": null, - "graceEnds": null, - "lifetimeDays": null, - "name": "payments-dev", - "noticesSent": 0, - "openRequest": "req-20261127-0002", - "state": "permanent", - "team": "payments" + "application/problem+json": { + "examples": { + "capacity-exceeded": { + "value": { + "code": "capacity-exceeded", + "detail": "memory would exceed the cluster", + "status": 422, + "title": "capacity exceeded", + "type": "https://cmapi.ephico2real.com/problems/capacity-exceeded" } - ], - "letters": { - "N": 1, - "P": 1, - "S": 1 }, - "page": { - "from": 1, - "limit": 25, - "nextCursor": null, - "prevCursor": null, - "to": 3, - "total": 3 + "cluster-not-writable": { + "value": { + "code": "cluster-not-writable", + "detail": "CRC is imported but has no clusters.yaml entry", + "status": 422, + "title": "cluster not writable", + "type": "https://cmapi.ephico2real.com/problems/cluster-not-writable" + } }, - "rules": { - "dev": { - "graceDays": 7, - "maxExtensionDays": 30, - "maxLifetimeDays": 180, - "notifyDaysBefore": [ - 14, - 7, - 1 - ] + "environment-not-served": { + "value": { + "code": "environment-not-served", + "detail": "qa is not served by the nonprod instance", + "instanceUrl": "https://cmapi-staging.ephico2real.com", + "portalUrl": "https://portal-staging.ephico2real.com", + "status": 422, + "title": "environment not served", + "type": "https://cmapi.ephico2real.com/problems/environment-not-served" } }, - "today": "2026-11-27" - }, - "schema": { - "$ref": "#/components/schemas/ExpirationPage" - } - } - }, - "description": "One page of the namespaces that can expire, with their dates, days left and notices, the count of each state, and each environment's rules." - }, - "400": { - "content": { - "application/problem+json": { - "examples": { - "invalid-cursor": { + "expiration-already-set": { "value": { - "code": "invalid-cursor", - "detail": "The cursor is not valid", - "status": 400, - "title": "invalid cursor", - "type": "https://cmapi.ephico2real.com/problems/invalid-cursor" + "code": "expiration-already-set", + "detail": "Use :extend to move an existing date", + "status": 422, + "title": "expiration already set", + "type": "https://cmapi.ephico2real.com/problems/expiration-already-set" } }, - "invalid-limit": { + "expiration-in-past": { "value": { - "code": "invalid-limit", - "detail": "limit is one of (25, 50, 100), at most 200", - "status": 400, - "title": "invalid limit", - "type": "https://cmapi.ephico2real.com/problems/invalid-limit" + "code": "expiration-in-past", + "detail": "The new date must be later than the current one", + "status": 422, + "title": "expiration in past", + "type": "https://cmapi.ephico2real.com/problems/expiration-in-past" } }, - "invalid-sort": { + "expiration-limit": { "value": { - "code": "invalid-sort", - "detail": "Unknown sort used2", - "status": 400, - "title": "invalid sort", - "type": "https://cmapi.ephico2real.com/problems/invalid-sort" + "code": "expiration-limit", + "detail": "An extension is at most 30 days", + "status": 422, + "title": "expiration limit", + "type": "https://cmapi.ephico2real.com/problems/expiration-limit" } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `invalid-cursor`, `invalid-sort`, `invalid-limit`." - }, - "401": { - "content": { - "application/problem+json": { - "examples": { - "unauthenticated": { + }, + "expiration-not-allowed": { "value": { - "code": "unauthenticated", - "detail": "Bearer token required", - "status": 401, - "title": "unauthenticated", - "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + "code": "expiration-not-allowed", + "detail": "Production namespaces never expire", + "status": 422, + "title": "expiration not allowed", + "type": "https://cmapi.ephico2real.com/problems/expiration-not-allowed" } - } - }, - "schema": { - "$ref": "#/components/schemas/ProblemDetail" - } - } - }, - "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." - }, - "403": { - "content": { - "application/problem+json": { - "examples": { - "forbidden": { + }, + "identity-incomplete": { "value": { - "code": "forbidden", - "detail": "Missing permission objects:read: no role in your token grants it (roles: ['cmapi-requester'])", - "status": 403, - "title": "forbidden", - "type": "https://cmapi.ephico2real.com/problems/forbidden" + "code": "identity-incomplete", + "detail": "The token has no employee_id claim", + "status": 422, + "title": "identity incomplete", + "type": "https://cmapi.ephico2real.com/problems/identity-incomplete" + } + }, + "on-behalf-of-required": { + "value": { + "code": "on-behalf-of-required", + "detail": "A service client must name the person", + "status": 422, + "title": "on behalf of required", + "type": "https://cmapi.ephico2real.com/problems/on-behalf-of-required" + } + }, + "plugin-disabled": { + "value": { + "code": "plugin-disabled", + "detail": "The namespaces plugin takes no writes in dev on the nonprod instance: plugins.yaml disables it there", + "status": 422, + "title": "plugin disabled", + "type": "https://cmapi.ephico2real.com/problems/plugin-disabled" + } + }, + "policy-violation": { + "value": { + "code": "policy-violation", + "detail": "Metadata refused", + "status": 422, + "title": "policy violation", + "type": "https://cmapi.ephico2real.com/problems/policy-violation" + } + }, + "unknown-serviceaccount": { + "value": { + "code": "unknown-serviceaccount", + "detail": "ci-deployer is not a ServiceAccount of payments-dev", + "status": 422, + "title": "unknown serviceaccount", + "type": "https://cmapi.ephico2real.com/problems/unknown-serviceaccount" + } + }, + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" } } }, @@ -20537,19 +19114,19 @@ } } }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `policy-violation`, `capacity-exceeded`, `unknown-serviceaccount`, `expiration-not-allowed`, `expiration-already-set`, `expiration-in-past`, `expiration-limit`." }, - "422": { + "428": { "content": { "application/problem+json": { "examples": { - "validation-failed": { + "precondition-required": { "value": { - "code": "validation-failed", - "detail": "Request body is not valid", - "status": 422, - "title": "validation failed", - "type": "https://cmapi.ephico2real.com/problems/validation-failed" + "code": "precondition-required", + "detail": "If-Match is required on a change", + "status": 428, + "title": "precondition required", + "type": "https://cmapi.ephico2real.com/problems/precondition-required" } } }, @@ -20558,7 +19135,7 @@ } } }, - "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + "description": "A change needs If-Match with the ETag of the object as it was read; `*` is not one.\n\nCodes: `precondition-required`." }, "429": { "content": { @@ -20592,10 +19169,41 @@ } } }, + "502": { + "content": { + "application/problem+json": { + "examples": { + "git-unavailable": { + "value": { + "code": "git-unavailable", + "detail": "The Git host answered 500", + "status": 502, + "title": "git unavailable", + "type": "https://cmapi.ephico2real.com/problems/git-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The Git host failed.\n\nCodes: `git-unavailable`." + }, "503": { "content": { "application/problem+json": { "examples": { + "cluster-unreachable": { + "value": { + "code": "cluster-unreachable", + "detail": "CRC did not answer", + "retryAfter": 30, + "status": 503, + "title": "cluster unreachable", + "type": "https://cmapi.ephico2real.com/problems/cluster-unreachable" + } + }, "idp-unavailable": { "value": { "code": "idp-unavailable", @@ -20605,6 +19213,26 @@ "title": "idp unavailable", "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" } + }, + "validator-busy": { + "value": { + "code": "validator-busy", + "detail": "The policy check is temporarily busy. Try again after the delay in Retry-After.", + "retryAfter": 15, + "status": 503, + "title": "validator busy", + "type": "https://cmapi.ephico2real.com/problems/validator-busy" + } + }, + "validator-unavailable": { + "value": { + "code": "validator-unavailable", + "detail": "kubeconform did not start", + "retryAfter": 60, + "status": 503, + "title": "validator unavailable", + "type": "https://cmapi.ephico2real.com/problems/validator-unavailable" + } } }, "schema": { @@ -20612,7 +19240,7 @@ } } }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `cluster-unreachable`, `validator-unavailable`, `validator-busy`, `idp-unavailable`.", "headers": { "Retry-After": { "description": "The seconds to wait before the next call: the same number as `retryAfter`.", @@ -20630,94 +19258,3170 @@ "keycloak": [] } ], - "summary": "List namespaces by expiry", + "summary": "Give a permanent namespace an expiry date", "tags": [ - "expiration" + "namespaces" ], - "x-cmapi-permission": "objects:read", - "x-cmapi-plugin": "expiration", - "x-cmapi-rate-limit": "read", + "x-cmapi-permission": "namespaces:write", + "x-cmapi-plugin": "namespaces", + "x-cmapi-rate-limit": "write", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/expirations -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev/expiration:set -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'If-Match: \"3f9a1c0b7e2d4a68\"' -H 'Content-Type: application/json' -d '{\"justification\": \"A load test this sprint\", \"until\": \"2026-12-22\"}'" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/me": { - "get": { - "description": "The caller's identity as cmapi records it, the roles and groups in the token, and the permissions\neach role grants with the environments it covers. The first thing to check when a call returns 403. `operator` says\nwhether the caller may set the operator-only keys (namespaces:protect), and `operatorEnvironments` where (#366).", - "operationId": "core_me", + "/api/v1/clusters/{cluster_id}/namespaces/{ns}:adopt": { + "post": { + "description": "Plans the adoption of a namespace that exists on the cluster and that cmapi does not manage, and submits it as a change\nrequest (plugin `adoption`, action `adopt`). The namespace must carry `cmapi.net/adopt: \"true\"`; any other is 409\n`namespace-not-adoptable`, whose `rule` says why.\n\ncmapi reads the live Namespace and each of its ResourceQuotas and LimitRanges, and writes them to the namespace's folder\nas they are: only what the API server sets is dropped, and each key under a skip prefix of adoption.yaml only when that\nchanges nothing on the cluster. It adds its own system keys and the tier `custom`; each ResourceQuota and LimitRange keeps\nits name, in its own file. Each difference from the instance's rules is a finding of the plan, never a change: a wrong or\nmissing key, a value beyond the custom bounds, a policy failure that the namespace already holds (`policy-ratcheted`).\n\n`labels` and `annotations` add keys that the namespace lacks (#739), so a team can supply the required metadata with the\nadoption: the candidates list and the plan's `adoption.missingKeys` name them. Each is checked as a change request checks\na key it adds: by its rule, and a key that cmapi fills in or that starts the name only with its one `value`. A key the\nnamespace already has is 422 `adoption-key-held`. Each key added is written to `namespace.yaml`, listed in `metadataDiff`\nand `adoption.supplied`, and a required one drops its `missing-required-key` finding. Leave both out to add nothing.\n\nThe request needs one approver of approver-platform, and one more when the plan has findings; no automatic approval covers\nit. After approval the bot opens the pull request. cmapi reads the objects again before it pushes the branch and in the pull\nrequest's check: a change since the plan fails the request (`adoption-plan-stale`), and the label removed cancels it.\n\n`dryRun=true` answers 200 with the plan, its files, findings and approval, and opens no request.\n\n**Requires** `namespaces:write`.", + "operationId": "adoption_adopt", + "parameters": [ + { + "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", + "in": "path", + "name": "cluster_id", + "required": true, + "schema": { + "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", + "examples": [ + "CRC" + ], + "title": "Cluster Id", + "type": "string" + } + }, + { + "description": "The name of the namespace on that cluster.", + "in": "path", + "name": "ns", + "required": true, + "schema": { + "description": "The name of the namespace on that cluster.", + "examples": [ + "payments-dev" + ], + "title": "Ns", + "type": "string" + } + }, + { + "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", + "in": "query", + "name": "dryRun", + "required": false, + "schema": { + "default": false, + "description": "With `true`, the call returns the plan with status 200 and needs no Idempotency-Key. It opens no change request, takes no lock or reservation and opens no pull request. Send it at most once: a repeated `dryRun` is 422 `validation-failed`.", + "examples": [ + true + ], + "title": "Dryrun", + "type": "boolean" + } + }, + { + "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state. The caller is the token's subject: a service that sends `onBehalfOf` holds its key, and the person cannot replay it: the person's own use of that key is a request of their own. The same key with another request is 409 `idempotency-replay`. The expiry writes do not compare `justification`: a retry that changes only it gets the original request.", + "in": "header", + "name": "Idempotency-Key", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "A new random value for each new request, such as a UUID, of at most 100 characters. Required, except with `dryRun=true`. For 24 hours, the same caller retrying the same request with the same key gets the original request in its current state. The caller is the token's subject: a service that sends `onBehalfOf` holds its key, and the person cannot replay it: the person's own use of that key is a request of their own. The same key with another request is 409 `idempotency-replay`. The expiry writes do not compare `justification`: a retry that changes only it gets the original request.", + "examples": [ + "0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10" + ], + "title": "Idempotency-Key" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "example": { + "annotations": { + "cmapi.net/team-dl": "abc-team@ephico2real.com" + }, + "justification": "Bring abc-rnd under cmapi", + "labels": { + "cmapi.net/team": "abc" + } + }, + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/AdoptBody" + }, + { + "type": "null" + } + ], + "title": "Body" + } + } + } + }, "responses": { "200": { "content": { "application/json": { "example": { - "access": { - "permissions": [ - "capacity:read", - "clusters:read", - "grants:write", - "namespaces:create", - "namespaces:write", - "objects:read", - "quotas:write", - "requests:cancel", - "requests:read", - "serviceaccounts:write" - ], - "roles": [ + "adoption": { + "keys": [ { - "environments": "all", - "permissions": [ - "capacity:read", - "clusters:read", - "grants:write", - "namespaces:create", - "namespaces:write", - "objects:read", - "quotas:write", - "requests:cancel", - "requests:read", - "serviceaccounts:write" + "kept": false, + "key": "kubernetes.io/metadata.name", + "kind": "label", + "managers": [ + "kube-apiserver" ], - "role": "cmapi-requester" + "why": "none of its managers is kubectl-client-side-apply, whose fields Argo CD's client-side apply migration takes over, so it stays on the cluster" + }, + { + "kept": false, + "key": "pod-security.kubernetes.io/audit", + "kind": "label", + "managers": [ + "pod-security-admission-label-synchronization-controller" + ], + "why": "none of its managers is kubectl-client-side-apply, whose fields Argo CD's client-side apply migration takes over, so it stays on the cluster" + } + ], + "label": "cmapi.net/adopt", + "missingKeys": [ + { + "key": "cmapi.net/team", + "kind": "label", + "required": true, + "value": null + }, + { + "key": "cmapi.net/team-dl", + "kind": "annotation", + "required": true, + "value": null + }, + { + "key": "cmapi.net/cost-center", + "kind": "label", + "required": false, + "value": null + }, + { + "key": "cmapi.net/app", + "kind": "label", + "required": false, + "value": null + }, + { + "key": "cmapi.net/rightsizing", + "kind": "label", + "required": false, + "value": null + } + ], + "notAdopted": { + "RoleBinding": 0, + "ServiceAccount": 0 + }, + "objects": [ + { + "kind": "Namespace", + "name": "abc-rnd", + "resourceVersion": "100", + "uid": "uid-ns-1" + }, + { + "kind": "ResourceQuota", + "name": "abc-rnd-quota", + "resourceVersion": "101", + "uid": "uid-rq-1" + }, + { + "kind": "LimitRange", + "name": "abc-rnd-limits-cpu", + "resourceVersion": "102", + "uid": "uid-lr-cpu" + }, + { + "kind": "LimitRange", + "name": "abc-rnd-limits-memory", + "resourceVersion": "102", + "uid": "uid-lr-memory" + } + ], + "recognised": [ + "company.net/provisioner=cluster-configs" + ], + "snapshotHash": "4faf2e011429cbd08f98b6a27fd293c9bb220471dc4084f383d8e48d4dcc9435", + "supplied": { + "annotations": {}, + "labels": {} + } + }, + "approval": { + "approvals": [], + "auto": null, + "autoFallback": null, + "reasons": [ + "dev change: 0 from approver-platform", + "threshold beyondTier: +1 approver-platform", + "threshold plugin == \"adoption\": +1 approver-platform", + "threshold plugin == \"adoption\" and actionableFindingCount > 0: +1 approver-platform" + ], + "remaining": [ + { + "group": "approver-platform", + "needed": 3 + } + ], + "rule": "dev-change", + "selfApproval": true, + "slots": [ + { + "count": 3, + "group": "approver-platform", + "reason": "Value beyond the tier; Adoption of an existing namespace; Adoption with findings" + } + ], + "timeoutHours": 8 + }, + "beyondTier": { + "approvals": [ + { + "count": 1, + "group": "approver-platform", + "reason": "Value beyond the tier" + } + ], + "keys": [ + { + "key": "requests.cpu", + "requested": "40", + "tier": "32" } ] }, - "client": "cmapi-portal", - "groups": [ - "/cmapi/app-cmapi-rbac-requester" - ], - "identity": { - "clientId": "cmapi-portal", - "email": "ola@ephico2real.com", - "employeeId": "1001", - "familyName": "Doe", - "givenName": "Ola", - "kind": "user", - "middleName": null, - "sub": "sub-ola", - "username": "ola" + "capacity": { + "bindingResource": null, + "fresh": true, + "source": "adoption", + "status": "fits" }, - "instance": "nonprod", - "kind": "user", - "operator": false, - "operatorEnvironments": [], - "roles": [ - "cmapi-requester" - ], - "username": "ola" + "changes": { + "clusters/CRC/namespaces/abc-rnd/limitrange-abc-rnd-limits-cpu.yaml": "added", + "clusters/CRC/namespaces/abc-rnd/limitrange-abc-rnd-limits-memory.yaml": "added", + "clusters/CRC/namespaces/abc-rnd/namespace.yaml": "added", + "clusters/CRC/namespaces/abc-rnd/resourcequota-abc-rnd-quota.yaml": "added" + }, + "etag": "0", + "files": { + "clusters/CRC/namespaces/abc-rnd/limitrange-abc-rnd-limits-cpu.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: abc-rnd-limits-cpu\n namespace: abc-rnd\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: custom\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\nspec:\n limits:\n - type: Container\n defaultRequest:\n cpu: 100m\n max:\n cpu: '2'\n", + "clusters/CRC/namespaces/abc-rnd/limitrange-abc-rnd-limits-memory.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: abc-rnd-limits-memory\n namespace: abc-rnd\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: custom\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\nspec:\n limits:\n - type: Container\n defaultRequest:\n memory: 128Mi\n max:\n memory: 4Gi\n", + "clusters/CRC/namespaces/abc-rnd/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: abc-rnd\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: custom\n company.net/provisioner: cluster-configs\n cmapi.net/adopt: 'true'\n company.net/app-environment: rnd\n company.net/cl: '1'\n company.net/lob: amgsst\n company.net/mnemonic: abc\n company.net/mnemonic-confluence: ''\n company.net/mnemonic-group-contact: ''\n name: aao-rnd\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n company.net/app-environment: rnd\n", + "clusters/CRC/namespaces/abc-rnd/resourcequota-abc-rnd-quota.yaml": "apiVersion: v1\nkind: ResourceQuota\nmetadata:\n name: abc-rnd-quota\n namespace: abc-rnd\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: custom\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\nspec:\n hard:\n requests.cpu: '40'\n requests.memory: 64Gi\n pods: '100'\n scopes:\n - NotTerminating\n" + }, + "findings": [ + { + "kyvernoRule": null, + "message": "label company.net/app-environment: no rule of this instance admits the label company.net/app-environment: kept; a request may remove it, never set it", + "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", + "rule": "unknown-key", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "label company.net/cl: no rule of this instance admits the label company.net/cl: kept; a request may remove it, never set it", + "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", + "rule": "unknown-key", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "label company.net/lob: no rule of this instance admits the label company.net/lob: kept; a request may remove it, never set it", + "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", + "rule": "unknown-key", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "label company.net/mnemonic: no rule of this instance admits the label company.net/mnemonic: kept; a request may remove it, never set it", + "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", + "rule": "unknown-key", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "label company.net/mnemonic-confluence: no rule of this instance admits the label company.net/mnemonic-confluence: kept; a request may remove it, never set it", + "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", + "rule": "unknown-key", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "label company.net/mnemonic-group-contact: no rule of this instance admits the label company.net/mnemonic-group-contact: kept; a request may remove it, never set it", + "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", + "rule": "unknown-key", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "label company.net/provisioner: company.net/provisioner=cluster-configs marks a namespace that another tool made (recognised): kept as it is", + "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", + "rule": "adoption-label", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "annotation company.net/app-environment: no rule of this instance admits the annotation company.net/app-environment: kept; a request may remove it, never set it", + "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", + "rule": "unknown-key", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "label cmapi.net/team: the required label cmapi.net/team is missing: never forced; each plan lists it until a request sets it", + "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", + "rule": "missing-required-key", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "annotation cmapi.net/team-dl: the required annotation cmapi.net/team-dl is missing: never forced; each plan lists it until a request sets it", + "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", + "rule": "missing-required-key", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "label kubernetes.io/metadata.name: left out of Git, none of its managers is kubectl-client-side-apply, whose fields Argo CD's client-side apply migration takes over, so it stays on the cluster (managers: kube-apiserver)", + "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", + "rule": "skipped-key", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "label pod-security.kubernetes.io/audit: left out of Git, none of its managers is kubectl-client-side-apply, whose fields Argo CD's client-side apply migration takes over, so it stays on the cluster (managers: pod-security-admission-label-synchronization-controller)", + "path": "clusters/CRC/namespaces/abc-rnd/namespace.yaml", + "rule": "skipped-key", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "abc-rnd-quota: requests.cpu is 40, above the custom maximum 32: adopted as it is; a later change of it is checked and approved as usual", + "path": "clusters/CRC/namespaces/abc-rnd/resourcequota-abc-rnd-quota.yaml", + "rule": "beyond-custom-bounds", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "Only the scoped quotas abc-rnd-quota hold pods: its figure for the namespace is not known", + "path": "clusters/CRC/namespaces/abc-rnd/", + "rule": "scoped-only", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "Only the scoped quotas abc-rnd-quota hold requests.cpu: its figure for the namespace is not known", + "path": "clusters/CRC/namespaces/abc-rnd/", + "rule": "scoped-only", + "severity": "warning", + "source": "cmapi" + }, + { + "kyvernoRule": null, + "message": "Only the scoped quotas abc-rnd-quota hold requests.memory: its figure for the namespace is not known", + "path": "clusters/CRC/namespaces/abc-rnd/", + "rule": "scoped-only", + "severity": "warning", + "source": "cmapi" + } + ], + "metadata": null, + "metadataDiff": null, + "planHash": "f0e04fd12b310dc184cec1612861bc4fbf0a48c0f5e4f54f80e6cb144a954a2c", + "requester": { + "automated": false, + "requester": { + "clientId": "cmapi-portal", + "email": "ola@ephico2real.com", + "employeeId": "1001", + "familyName": "Doe", + "givenName": "Ola", + "kind": "user", + "middleName": null, + "sub": "sub-ola", + "username": "ola" + }, + "submittedBy": null, + "submittedByClient": null + }, + "usage": null + }, + "schema": { + "$ref": "#/components/schemas/PlanView" + } + } + }, + "description": "Dry run (`?dryRun=true`): the plan. The call opens no change request, takes no lock or reservation, queues no job and opens no pull request." + }, + "202": { + "content": { + "application/json": { + "example": { + "action": "adopt", + "approval": { + "approvals": [], + "auto": null, + "autoFallback": null, + "reasons": [ + "dev change: 0 from approver-platform", + "threshold beyondTier: +1 approver-platform", + "threshold plugin == \"adoption\": +1 approver-platform", + "threshold plugin == \"adoption\" and actionableFindingCount > 0: +1 approver-platform" + ], + "remaining": [ + { + "group": "approver-platform", + "needed": 3 + } + ], + "rule": "dev-change", + "selfApproval": true, + "slots": [ + { + "count": 3, + "group": "approver-platform", + "reason": "Value beyond the tier; Adoption of an existing namespace; Adoption with findings" + } + ], + "timeoutHours": 8 + }, + "baseSha": "e33ccf390a5fc196bb270e81c03752e59a2385f7", + "beyondTier": { + "approvals": [ + { + "count": 1, + "group": "approver-platform", + "reason": "Value beyond the tier" + } + ], + "keys": [ + { + "key": "requests.cpu", + "requested": "40", + "tier": "32" + } + ] + }, + "clusterId": "CRC", + "createdAt": "2026-12-01T15:13:36.361990Z", + "env": "dev", + "events": [ + { + "at": "2026-12-01T15:13:36.396117Z", + "by": "ola", + "event": "plan_needs_approval", + "note": "waiting for [('approver-platform', 3)]", + "status": "pending_approval" + } + ], + "files": { + "clusters/CRC/namespaces/abc-rnd/limitrange-abc-rnd-limits-cpu.yaml": "added", + "clusters/CRC/namespaces/abc-rnd/limitrange-abc-rnd-limits-memory.yaml": "added", + "clusters/CRC/namespaces/abc-rnd/namespace.yaml": "added", + "clusters/CRC/namespaces/abc-rnd/resourcequota-abc-rnd-quota.yaml": "added" + }, + "instance": "nonprod", + "justification": "Bring abc-rnd under cmapi", + "links": { + "events": "/api/v1/requests/req-20261201-0016/events", + "self": "/api/v1/requests/req-20261201-0016" + }, + "mergeSha": null, + "namespace": "abc-rnd", + "planHash": "49c73db929d9a990a0acdf6bd9c262076939964693858d51f17c7de254db4939", + "plugin": "adoption", + "pr": null, + "reason": null, + "requestId": "req-20261201-0016", + "requester": { + "automated": false, + "requester": { + "clientId": "cmapi-portal", + "email": "ola@ephico2real.com", + "employeeId": "1001", + "familyName": "Doe", + "givenName": "Ola", + "kind": "user", + "middleName": null, + "sub": "sub-ola", + "username": "ola" + }, + "submittedBy": null, + "submittedByClient": null + }, + "status": "pending_approval", + "updatedAt": "2026-12-01T15:13:36.123405Z" + }, + "schema": { + "$ref": "#/components/schemas/ChangeRequest" + } + } + }, + "description": "The request is created. It waits for approval unless a policy approves it at once: `status` and `approval` say which, and `links.events` follows it." + }, + "400": { + "content": { + "application/problem+json": { + "examples": { + "idempotency-key-required": { + "value": { + "code": "idempotency-key-required", + "detail": "Idempotency-Key header is required on writes", + "status": 400, + "title": "idempotency key required", + "type": "https://cmapi.ephico2real.com/problems/idempotency-key-required" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `idempotency-key-required`." + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthenticated": { + "value": { + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "environment-forbidden": { + "value": { + "code": "environment-forbidden", + "detail": "Your roles grant namespaces:write only in ['rnd'], not dev", + "status": 403, + "title": "environment forbidden", + "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" + } + }, + "forbidden": { + "value": { + "code": "forbidden", + "detail": "Missing permission namespaces:write: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`, `environment-forbidden`." + }, + "404": { + "content": { + "application/problem+json": { + "examples": { + "cluster-not-found": { + "value": { + "code": "cluster-not-found", + "detail": "Unknown cluster OCP_X", + "status": 404, + "title": "cluster not found", + "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" + } + }, + "object-not-found": { + "value": { + "code": "object-not-found", + "detail": "No request req-20261105-0001", + "status": 404, + "title": "object not found", + "type": "https://cmapi.ephico2real.com/problems/object-not-found" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "What the path names is not known.\n\nCodes: `cluster-not-found`, `object-not-found`." + }, + "409": { + "content": { + "application/problem+json": { + "examples": { + "change-pending": { + "value": { + "code": "change-pending", + "detail": "req-20261105-0001 holds payments-dev", + "status": 409, + "title": "change pending", + "type": "https://cmapi.ephico2real.com/problems/change-pending" + } + }, + "folder-not-utf8": { + "value": { + "code": "folder-not-utf8", + "detail": "The folder of payments-dev holds clusters/CRC/namespaces/payments-dev/caf\\xe9.yaml, whose name is not UTF-8: cmapi carries a folder's names and manifests as UTF-8 text. Rename it in Git, then send the request again", + "paths": [ + "clusters/CRC/namespaces/payments-dev/caf\\xe9.yaml" + ], + "status": 409, + "title": "folder not utf8", + "type": "https://cmapi.ephico2real.com/problems/folder-not-utf8" + } + }, + "folder-not-yaml": { + "value": { + "code": "folder-not-yaml", + "detail": "The folder of payments-dev holds clusters/CRC/namespaces/payments-dev/namespace.yaml, which is not YAML: expected ',' or '}', but got '' at line 4, column 1. Correct it in Git, then send the request again", + "paths": [ + "clusters/CRC/namespaces/payments-dev/namespace.yaml" + ], + "status": 409, + "title": "folder not yaml", + "type": "https://cmapi.ephico2real.com/problems/folder-not-yaml" + } + }, + "idempotency-replay": { + "value": { + "code": "idempotency-replay", + "detail": "Idempotency-Key was used for a different request", + "status": 409, + "title": "idempotency replay", + "type": "https://cmapi.ephico2real.com/problems/idempotency-replay" + } + }, + "namespace-not-adoptable": { + "value": { + "application": "legacy-tools", + "code": "namespace-not-adoptable", + "detail": "legacy-tools is not a candidate for adoption: The Argo CD Application legacy-tools tracks legacy-tools", + "rule": "tracked-elsewhere", + "state": "skipped", + "status": 409, + "title": "namespace not adoptable", + "type": "https://cmapi.ephico2real.com/problems/namespace-not-adoptable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `change-pending`, `idempotency-replay`, `folder-not-utf8`, `folder-not-yaml`, `namespace-not-adoptable`." + }, + "413": { + "content": { + "application/problem+json": { + "examples": { + "content-too-large": { + "value": { + "code": "content-too-large", + "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", + "maxBytes": 1048576, + "status": 413, + "title": "content too large", + "type": "https://cmapi.ephico2real.com/problems/content-too-large" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "adoption-key-held": { + "value": { + "code": "adoption-key-held", + "detail": "abc-rnd already has the label company.net/lob: an adoption keeps each key it finds as it is. Leave it out, and change it with a request after the adoption", + "keys": [ + { + "key": "company.net/lob", + "kind": "label" + } + ], + "status": 422, + "title": "adoption key held", + "type": "https://cmapi.ephico2real.com/problems/adoption-key-held" + } + }, + "cluster-not-writable": { + "value": { + "code": "cluster-not-writable", + "detail": "CRC is imported but has no clusters.yaml entry", + "status": 422, + "title": "cluster not writable", + "type": "https://cmapi.ephico2real.com/problems/cluster-not-writable" + } + }, + "environment-not-served": { + "value": { + "code": "environment-not-served", + "detail": "qa is not served by the nonprod instance", + "instanceUrl": "https://cmapi-staging.ephico2real.com", + "portalUrl": "https://portal-staging.ephico2real.com", + "status": 422, + "title": "environment not served", + "type": "https://cmapi.ephico2real.com/problems/environment-not-served" + } + }, + "identity-incomplete": { + "value": { + "code": "identity-incomplete", + "detail": "The token has no employee_id claim", + "status": 422, + "title": "identity incomplete", + "type": "https://cmapi.ephico2real.com/problems/identity-incomplete" + } + }, + "on-behalf-of-required": { + "value": { + "code": "on-behalf-of-required", + "detail": "A service client must name the person", + "status": 422, + "title": "on behalf of required", + "type": "https://cmapi.ephico2real.com/problems/on-behalf-of-required" + } + }, + "plugin-disabled": { + "value": { + "code": "plugin-disabled", + "detail": "The namespaces plugin takes no writes in dev on the nonprod instance: plugins.yaml disables it there", + "status": 422, + "title": "plugin disabled", + "type": "https://cmapi.ephico2real.com/problems/plugin-disabled" + } + }, + "policy-violation": { + "value": { + "code": "policy-violation", + "detail": "Metadata refused", + "status": 422, + "title": "policy violation", + "type": "https://cmapi.ephico2real.com/problems/policy-violation" + } + }, + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `cluster-not-writable`, `environment-not-served`, `plugin-disabled`, `validation-failed`, `identity-incomplete`, `on-behalf-of-required`, `adoption-key-held`, `policy-violation`." + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate-limited": { + "value": { + "code": "rate-limited", + "detail": "Too many write calls by this caller; try again in 2 s", + "retryAfter": 2, + "status": 429, + "title": "rate limited", + "type": "https://cmapi.ephico2real.com/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + }, + "502": { + "content": { + "application/problem+json": { + "examples": { + "git-unavailable": { + "value": { + "code": "git-unavailable", + "detail": "The Git host answered 500", + "status": 502, + "title": "git unavailable", + "type": "https://cmapi.ephico2real.com/problems/git-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The Git host failed.\n\nCodes: `git-unavailable`." + }, + "503": { + "content": { + "application/problem+json": { + "examples": { + "cluster-unreachable": { + "value": { + "code": "cluster-unreachable", + "detail": "CRC did not answer", + "retryAfter": 30, + "status": 503, + "title": "cluster unreachable", + "type": "https://cmapi.ephico2real.com/problems/cluster-unreachable" + } + }, + "idp-unavailable": { + "value": { + "code": "idp-unavailable", + "detail": "Keycloak signing keys are unreachable and this key is not cached", + "retryAfter": 30, + "status": 503, + "title": "idp unavailable", + "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" + } + }, + "validator-busy": { + "value": { + "code": "validator-busy", + "detail": "The policy check is temporarily busy. Try again after the delay in Retry-After.", + "retryAfter": 15, + "status": 503, + "title": "validator busy", + "type": "https://cmapi.ephico2real.com/problems/validator-busy" + } + }, + "validator-unavailable": { + "value": { + "code": "validator-unavailable", + "detail": "kubeconform did not start", + "retryAfter": 60, + "status": 503, + "title": "validator unavailable", + "type": "https://cmapi.ephico2real.com/problems/validator-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `cluster-unreachable`, `validator-unavailable`, `validator-busy`, `idp-unavailable`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + } + }, + "security": [ + { + "keycloak": [] + } + ], + "summary": "Adopt an existing namespace", + "tags": [ + "adoption" + ], + "x-cmapi-permission": "namespaces:write", + "x-cmapi-plugin": "adoption", + "x-cmapi-rate-limit": "write", + "x-codeSamples": [ + { + "label": "curl", + "lang": "Shell", + "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev:adopt -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'Content-Type: application/json' -d '{\"annotations\": {\"cmapi.net/team-dl\": \"abc-team@ephico2real.com\"}, \"justification\": \"Bring abc-rnd under cmapi\", \"labels\": {\"cmapi.net/team\": \"abc\"}}'" + } + ], + "x-plugin-version": "0.2.0" + } + }, + "/api/v1/clusters/{id}:probe": { + "post": { + "description": "Run the relist checks on this cluster's last discovered import and return its current diagnostics.\nNo Secret or cluster resource is changed. A known cluster without an import returns its not-imported view.\n\n**Requires** `operations:run`.", + "operationId": "core_probe", + "parameters": [ + { + "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", + "in": "path", + "name": "id", + "required": true, + "schema": { + "description": "The cluster's ID, as `GET /api/v1/clusters` returns it.", + "examples": [ + "CRC" + ], + "title": "Id", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "checkedAt": "2026-12-01T15:12:54.578527Z", + "clusterId": "CRC", + "environment": "dev", + "findingDetails": [], + "findings": [], + "gitopsPath": "clusters/CRC", + "labels": { + "region": "us-central" + }, + "lastProbeAt": "2026-12-01T15:12:54.578527Z", + "secretName": "cmapi-cluster-crc", + "serverVersion": "v1.35.6-fake", + "status": "connected", + "statusSince": "2026-12-01T15:12:54.018046Z", + "tokenExpiresAt": null, + "trust": { + "downgrade": false, + "serverName": null, + "source": "trusted" + }, + "writes": true + }, + "schema": { + "$ref": "#/components/schemas/ClusterView" + } + } + }, + "description": "The cluster's diagnostics after the checks ran again: status, findings, server version and token expiry." + }, + "400": { + "content": { + "application/problem+json": { + "examples": { + "dry-run-not-supported": { + "value": { + "code": "dry-run-not-supported", + "detail": "This call has no dry run, and nothing was done", + "status": 400, + "title": "dry run not supported", + "type": "https://cmapi.ephico2real.com/problems/dry-run-not-supported" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `dry-run-not-supported`." + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthenticated": { + "value": { + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "forbidden": { + "value": { + "code": "forbidden", + "detail": "Missing permission operations:run: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + }, + "404": { + "content": { + "application/problem+json": { + "examples": { + "cluster-not-found": { + "value": { + "code": "cluster-not-found", + "detail": "Unknown cluster OCP_X", + "status": 404, + "title": "cluster not found", + "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "What the path names is not known.\n\nCodes: `cluster-not-found`." + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate-limited": { + "value": { + "code": "rate-limited", + "detail": "Too many write calls by this caller; try again in 2 s", + "retryAfter": 2, + "status": 429, + "title": "rate limited", + "type": "https://cmapi.ephico2real.com/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + }, + "503": { + "content": { + "application/problem+json": { + "examples": { + "idp-unavailable": { + "value": { + "code": "idp-unavailable", + "detail": "Keycloak signing keys are unreachable and this key is not cached", + "retryAfter": 30, + "status": 503, + "title": "idp unavailable", + "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + } + }, + "security": [ + { + "keycloak": [] + } + ], + "summary": "Probe one cluster's held credential", + "tags": [ + "core" + ], + "x-cmapi-permission": "operations:run", + "x-cmapi-plugin": "core", + "x-cmapi-rate-limit": "write", + "x-codeSamples": [ + { + "label": "curl", + "lang": "Shell", + "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC:probe -H \"Authorization: Bearer $TOKEN\"" + } + ], + "x-plugin-version": "0.2.0" + } + }, + "/api/v1/directory/users": { + "get": { + "description": "Up to ten people matching the text, for the portal's people picker. The employee ID is returned to an\noperator (namespaces:protect) only.\n\n**Requires** `objects:read`.", + "operationId": "directory_search", + "parameters": [ + { + "description": "Two or more characters of a username, a name or an email address.", + "in": "query", + "name": "q", + "required": true, + "schema": { + "description": "Two or more characters of a username, a name or an email address.", + "examples": [ + "ada" + ], + "minLength": 2, + "title": "Q", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "items": [ + { + "email": "ola@ephico2real.com", + "employeeId": null, + "name": "Ola Adeyemi", + "username": "ola" + } + ] + }, + "schema": { + "$ref": "#/components/schemas/DirectoryUsers" + } + } + }, + "description": "The people whose username, name or email address matches." + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthenticated": { + "value": { + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "forbidden": { + "value": { + "code": "forbidden", + "detail": "Missing permission objects:read: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate-limited": { + "value": { + "code": "rate-limited", + "detail": "Too many write calls by this caller; try again in 2 s", + "retryAfter": 2, + "status": 429, + "title": "rate limited", + "type": "https://cmapi.ephico2real.com/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + }, + "503": { + "content": { + "application/problem+json": { + "examples": { + "idp-unavailable": { + "value": { + "code": "idp-unavailable", + "detail": "Keycloak signing keys are unreachable and this key is not cached", + "retryAfter": 30, + "status": 503, + "title": "idp unavailable", + "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + } + }, + "security": [ + { + "keycloak": [] + } + ], + "summary": "Search people", + "tags": [ + "directory" + ], + "x-cmapi-permission": "objects:read", + "x-cmapi-plugin": "directory", + "x-cmapi-rate-limit": "read", + "x-codeSamples": [ + { + "label": "curl", + "lang": "Shell", + "source": "curl -X GET 'https://cmapi-nonprod.ephico2real.com/api/v1/directory/users?q=ada' -H \"Authorization: Bearer $TOKEN\"" + } + ], + "x-plugin-version": "0.2.0" + } + }, + "/api/v1/directory/users/{username}": { + "get": { + "description": "A person by username (cached 15 minutes, served from the cache when Keycloak is unreachable).\n\n**Requires** `objects:read`.", + "operationId": "directory_get_user", + "parameters": [ + { + "description": "The person's username in Keycloak (`preferred_username`).", + "in": "path", + "name": "username", + "required": true, + "schema": { + "description": "The person's username in Keycloak (`preferred_username`).", + "examples": [ + "cmapi.requester" + ], + "title": "Username", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "email": "ola@ephico2real.com", + "employeeId": null, + "name": "Ola Adeyemi", + "username": "ola" + }, + "schema": { + "$ref": "#/components/schemas/DirectoryUser" + } + } + }, + "description": "The person's username, name and email address, and the employee ID for an operator only." + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthenticated": { + "value": { + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "forbidden": { + "value": { + "code": "forbidden", + "detail": "Missing permission objects:read: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + }, + "404": { + "content": { + "application/problem+json": { + "examples": { + "object-not-found": { + "value": { + "code": "object-not-found", + "detail": "No request req-20261105-0001", + "status": 404, + "title": "object not found", + "type": "https://cmapi.ephico2real.com/problems/object-not-found" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "What the path names is not known.\n\nCodes: `object-not-found`." + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate-limited": { + "value": { + "code": "rate-limited", + "detail": "Too many write calls by this caller; try again in 2 s", + "retryAfter": 2, + "status": 429, + "title": "rate limited", + "type": "https://cmapi.ephico2real.com/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + }, + "503": { + "content": { + "application/problem+json": { + "examples": { + "idp-unavailable": { + "value": { + "code": "idp-unavailable", + "detail": "Keycloak signing keys are unreachable and this key is not cached", + "retryAfter": 30, + "status": 503, + "title": "idp unavailable", + "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + } + }, + "security": [ + { + "keycloak": [] + } + ], + "summary": "Get a directory user", + "tags": [ + "directory" + ], + "x-cmapi-permission": "objects:read", + "x-cmapi-plugin": "directory", + "x-cmapi-rate-limit": "read", + "x-codeSamples": [ + { + "label": "curl", + "lang": "Shell", + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/directory/users/cmapi.requester -H \"Authorization: Bearer $TOKEN\"" + } + ], + "x-plugin-version": "0.2.0" + } + }, + "/api/v1/expirations": { + "get": { + "description": "One page of the managed namespaces that can expire, in the caller's environments: each one's expiry date from the\nwatch cache, the days left, its state and the notices sent, the count of each state over the other filters, and the\nrules of each environment. Where expiration is off (no entry in expiration.yaml, or enabled: false, such as prod), only a\nnamespace that kept a date from before is listed, with :makePermanent as its one action, and the environment has no\nrules. `today` is the day the API counts from.\n\n**Requires** `objects:read`.", + "operationId": "expiration_expirations", + "parameters": [ + { + "description": "Text that the name, the team label or the app label contains. Case does not matter.", + "in": "query", + "name": "q", + "required": false, + "schema": { + "default": "", + "description": "Text that the name, the team label or the app label contains. Case does not matter.", + "examples": [ + "payments" + ], + "title": "Q", + "type": "string" + } + }, + { + "description": "Only the namespaces of this environment (`cmapi.net/env`).", + "in": "query", + "name": "env", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only the namespaces of this environment (`cmapi.net/env`).", + "examples": [ + "dev" + ], + "title": "Env" + } + }, + { + "description": "Only the namespaces on this cluster.", + "in": "query", + "name": "clusterId", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only the namespaces on this cluster.", + "examples": [ + "CRC" + ], + "title": "Clusterid" + } + }, + { + "description": "Only the namespaces of this team (`cmapi.net/team`).", + "in": "query", + "name": "team", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only the namespaces of this team (`cmapi.net/team`).", + "examples": [ + "payments" + ], + "title": "Team" + } + }, + { + "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`.", + "in": "query", + "name": "state", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "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`.", + "examples": [ + "attention" + ], + "title": "State" + } + }, + { + "description": "`urgency` puts the most urgent first: grace, expiring, pending_delete, active, then permanent, and in each the fewest days left first. `name` sorts by name, A to Z.", + "in": "query", + "name": "sort", + "required": false, + "schema": { + "default": "urgency", + "description": "`urgency` puts the most urgent first: grace, expiring, pending_delete, active, then permanent, and in each the fewest days left first. `name` sorts by name, A to Z.", + "examples": [ + "urgency" + ], + "title": "Sort", + "type": "string" + } + }, + { + "description": "The number of rows in one page: 25, 50 or 100, and never more than 200. A larger result is not cut: `page.nextCursor` gives the next page.", + "in": "query", + "name": "limit", + "required": false, + "schema": { + "default": 50, + "description": "The number of rows in one page: 25, 50 or 100, and never more than 200. A larger result is not cut: `page.nextCursor` gives the next page.", + "examples": [ + 50 + ], + "title": "Limit", + "type": "integer" + } + }, + { + "description": "`page.nextCursor` or `page.prevCursor` of an earlier page of the same filters and sort. A cursor of other filters returns 400 `invalid-cursor`.", + "in": "query", + "name": "cursor", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "`page.nextCursor` or `page.prevCursor` of an earlier page of the same filters and sort. A cursor of other filters returns 400 `invalid-cursor`.", + "examples": [ + "eyJrIjpbInBheW1lbnRzLWRldiIsIkNSQyJdLCJkIjoibmV4dCJ9.2f1c" + ], + "title": "Cursor" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "facets": { + "active": 2, + "attention": 0, + "expiring": 0, + "grace": 0, + "pending_delete": 0, + "permanent": 1 + }, + "items": [ + { + "actions": [ + "extend", + "makePermanent" + ], + "app": null, + "clusterId": "CRC", + "created": "2026-12-01", + "daysLeft": 21, + "env": "dev", + "expiresAt": "2026-12-22", + "graceEnds": "2026-12-29", + "lifetimeDays": 21, + "name": "notes-dev", + "noticesSent": 0, + "openRequest": null, + "state": "active", + "team": "payments" + }, + { + "actions": [ + "extend", + "makePermanent" + ], + "app": null, + "clusterId": "CRC", + "created": "2026-12-01", + "daysLeft": 27, + "env": "dev", + "expiresAt": "2026-12-28", + "graceEnds": "2027-01-04", + "lifetimeDays": 27, + "name": "sprint-dev", + "noticesSent": 0, + "openRequest": "req-20261201-0013", + "state": "active", + "team": "payments" + }, + { + "actions": [ + "set" + ], + "app": null, + "clusterId": "CRC", + "created": "2026-12-01", + "daysLeft": null, + "env": "dev", + "expiresAt": null, + "graceEnds": null, + "lifetimeDays": null, + "name": "payments-dev", + "noticesSent": 0, + "openRequest": "req-20261201-0002", + "state": "permanent", + "team": "payments" + } + ], + "letters": { + "N": 1, + "P": 1, + "S": 1 + }, + "page": { + "from": 1, + "limit": 25, + "nextCursor": null, + "prevCursor": null, + "to": 3, + "total": 3 + }, + "rules": { + "dev": { + "graceDays": 7, + "maxExtensionDays": 30, + "maxLifetimeDays": 180, + "notifyDaysBefore": [ + 14, + 7, + 1 + ] + } + }, + "today": "2026-12-01" + }, + "schema": { + "$ref": "#/components/schemas/ExpirationPage" + } + } + }, + "description": "One page of the namespaces that can expire, with their dates, days left and notices, the count of each state, and each environment's rules." + }, + "400": { + "content": { + "application/problem+json": { + "examples": { + "invalid-cursor": { + "value": { + "code": "invalid-cursor", + "detail": "The cursor is not valid", + "status": 400, + "title": "invalid cursor", + "type": "https://cmapi.ephico2real.com/problems/invalid-cursor" + } + }, + "invalid-limit": { + "value": { + "code": "invalid-limit", + "detail": "limit is one of (25, 50, 100), at most 200", + "status": 400, + "title": "invalid limit", + "type": "https://cmapi.ephico2real.com/problems/invalid-limit" + } + }, + "invalid-sort": { + "value": { + "code": "invalid-sort", + "detail": "Unknown sort used2", + "status": 400, + "title": "invalid sort", + "type": "https://cmapi.ephico2real.com/problems/invalid-sort" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `invalid-cursor`, `invalid-sort`, `invalid-limit`." + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthenticated": { + "value": { + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "forbidden": { + "value": { + "code": "forbidden", + "detail": "Missing permission objects:read: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate-limited": { + "value": { + "code": "rate-limited", + "detail": "Too many write calls by this caller; try again in 2 s", + "retryAfter": 2, + "status": 429, + "title": "rate limited", + "type": "https://cmapi.ephico2real.com/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + }, + "503": { + "content": { + "application/problem+json": { + "examples": { + "idp-unavailable": { + "value": { + "code": "idp-unavailable", + "detail": "Keycloak signing keys are unreachable and this key is not cached", + "retryAfter": 30, + "status": 503, + "title": "idp unavailable", + "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + } + }, + "security": [ + { + "keycloak": [] + } + ], + "summary": "List namespaces by expiry", + "tags": [ + "expiration" + ], + "x-cmapi-permission": "objects:read", + "x-cmapi-plugin": "expiration", + "x-cmapi-rate-limit": "read", + "x-codeSamples": [ + { + "label": "curl", + "lang": "Shell", + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/expirations -H \"Authorization: Bearer $TOKEN\"" + } + ], + "x-plugin-version": "0.2.0" + } + }, + "/api/v1/me": { + "get": { + "description": "The caller's identity as cmapi records it, the roles and groups in the token, and the permissions\neach role grants with the environments it covers. The first thing to check when a call returns 403. `operator` says\nwhether the caller may set the operator-only keys (namespaces:protect), and `operatorEnvironments` where (#366).", + "operationId": "core_me", + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "access": { + "permissions": [ + "capacity:read", + "clusters:read", + "grants:write", + "namespaces:create", + "namespaces:write", + "objects:read", + "quotas:write", + "requests:cancel", + "requests:read", + "serviceaccounts:write" + ], + "roles": [ + { + "environments": "all", + "permissions": [ + "capacity:read", + "clusters:read", + "grants:write", + "namespaces:create", + "namespaces:write", + "objects:read", + "quotas:write", + "requests:cancel", + "requests:read", + "serviceaccounts:write" + ], + "role": "cmapi-requester" + } + ] + }, + "client": "cmapi-portal", + "groups": [ + "/cmapi/app-cmapi-rbac-requester" + ], + "identity": { + "clientId": "cmapi-portal", + "email": "ola@ephico2real.com", + "employeeId": "1001", + "familyName": "Doe", + "givenName": "Ola", + "kind": "user", + "middleName": null, + "sub": "sub-ola", + "username": "ola" + }, + "instance": "nonprod", + "kind": "user", + "operator": false, + "operatorEnvironments": [], + "roles": [ + "cmapi-requester" + ], + "username": "ola" + }, + "schema": { + "$ref": "#/components/schemas/Me" + } + } + }, + "description": "The caller's identity, roles, groups and permissions, with the environments each role covers." + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthenticated": { + "value": { + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate-limited": { + "value": { + "code": "rate-limited", + "detail": "Too many write calls by this caller; try again in 2 s", + "retryAfter": 2, + "status": 429, + "title": "rate limited", + "type": "https://cmapi.ephico2real.com/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + }, + "503": { + "content": { + "application/problem+json": { + "examples": { + "idp-unavailable": { + "value": { + "code": "idp-unavailable", + "detail": "Keycloak signing keys are unreachable and this key is not cached", + "retryAfter": 30, + "status": 503, + "title": "idp unavailable", + "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + } + }, + "security": [ + { + "keycloak": [] + } + ], + "summary": "Get the caller's identity and permissions", + "tags": [ + "core" + ], + "x-cmapi-plugin": "core", + "x-cmapi-rate-limit": "read", + "x-codeSamples": [ + { + "label": "curl", + "lang": "Shell", + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/me -H \"Authorization: Bearer $TOKEN\"" + } + ], + "x-plugin-version": "0.2.0" + } + }, + "/api/v1/metadata-keys": { + "get": { + "description": "This instance's metadata-keys.yaml as the JSON Schema 2020-12 of a new namespace's labels and annotations: each\ndeclared key with its rule, which keys are required, which cmapi fills in (x-cmapi-derived-from), and which only an\noperator (namespaces:protect) may set. The same schemas as NamespaceCreate in the API document, here also when\ndocs.enabled is false. Each property carries x-cmapi-rule, the rule in the words of a refusal, and title when the file\ngives one. x-cmapi-expiration is expiresAt's: each served environment's expiration rules (expiration.yaml).\n\nEach property also carries x-cmapi-edit, how the key may change on an existing namespace (#481): `mode` fixed (part of\nthe namespace's fixed name), automatic (filled in by cmapi), required or optional, the `reason` a person sees, and\n`sensitive` when a change of it adds one approval. One answer, the same for a create and a change.\n\ncmapi checks every request against the file itself: this answer describes the rules, it does not replace them. The\nanswer is the instance's, the same for every caller; it has a strong ETag. If-None-Match answers 304, and an If-Match\nthat does not list the ETag answers 412.\n\n**Requires** `objects:read`.", + "operationId": "core_metadata_keys", + "parameters": [ + { + "description": "The ETag of the answer the caller holds. If it is still the current one, the answer is 304 with no body.", + "in": "header", + "name": "If-None-Match", + "required": false, + "schema": { + "examples": [ + "\"1f774baf9bf093f8d4ebc497eb0d5b96\"" + ], + "type": "string" + } + }, + { + "description": "Optional on a read. The answer is sent only if one strong tag listed here is its current ETag, or if the value is `*`; otherwise it is 412 `precondition-failed`, with the current tag in `etag`. A weak tag (`W/\"...\"`) never matches. If-Match is read before If-None-Match (RFC 9110, section 13.2.2). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line.", + "in": "header", + "name": "If-Match", + "required": false, + "schema": { + "examples": [ + "\"1f774baf9bf093f8d4ebc497eb0d5b96\"" + ], + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "annotations": { + "additionalProperties": { + "maxLength": 4096, + "type": "string" + }, + "properties": { + "cmapi.net/protected": { + "description": "An operator only (namespaces:protect): another caller gets 403 forbidden.", + "type": "string", + "x-cmapi-edit": { + "mode": "optional", + "reason": "Needs namespaces:protect in the namespace's environment. Changing this key needs one more approval.", + "sensitive": true + }, + "x-cmapi-operator-only": true + }, + "cmapi.net/team-dl": { + "description": "Your team's distribution list, in one of the organisation's email domains (emailDomains); format only. An address in ['ephico2real.com'].", + "examples": [ + "payments-team@ephico2real.com" + ], + "minLength": 1, + "pattern": "^[A-Za-z0-9!#$%&'*+/=?^_`{|}~.-]+@(?:[eE][pP][hH][iI][cC][oO]2[rR][eE][aA][lL]\\.[cC][oO][mM])$", + "title": "Team DL", + "type": "string", + "x-cmapi-edit": { + "mode": "required", + "reason": "Required on every namespace.", + "sensitive": false + }, + "x-cmapi-format": "email-in-domains", + "x-cmapi-rule": "an address in ['ephico2real.com']" + }, + "do-not-delete": { + "description": "An operator only (namespaces:protect): another caller gets 403 forbidden.", + "type": "string", + "x-cmapi-edit": { + "mode": "optional", + "reason": "Needs namespaces:protect in the namespace's environment. Changing this key needs one more approval.", + "sensitive": true + }, + "x-cmapi-operator-only": true + } + }, + "propertyNames": { + "anyOf": [ + { + "enum": [ + "cmapi.net/team-dl", + "cmapi.net/protected", + "do-not-delete" + ] + }, + { + "pattern": "^(?:[^/]+|[^/]*\\.ephico2real\\.com/[^/]+)$" + } + ], + "maxLength": 317, + "not": { + "pattern": "^[^/]{254}" + }, + "pattern": "^(?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?(?:\\.[a-z0-9](?:[-a-z0-9]*[a-z0-9])?)*/)?[A-Za-z0-9](?:[-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$" + }, + "required": [ + "cmapi.net/team-dl" + ], + "type": "object", + "x-cmapi-other-keys": { + "max": 50, + "maxBytesTotal": 65536, + "maxValueBytes": 4096, + "prefixes": [ + "", + "*.ephico2real.com/" + ], + "sensitiveKeys": [ + "network.ephico2real.com/zone" + ] + } + }, + "labels": { + "additionalProperties": { + "maxLength": 63, + "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", + "type": "string" + }, + "properties": { + "cmapi.net/app": { + "allOf": [ + { + "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", + "type": "string" + } + ], + "description": "Links an app's environments. Must match ^[a-z0-9-]{2,40}$.", + "maxLength": 63, + "pattern": "^(?:^[a-z0-9-]{2,40}$)$", + "type": "string", + "x-cmapi-edit": { + "mode": "optional", + "reason": null, + "sensitive": false + }, + "x-cmapi-rule": "must match ^[a-z0-9-]{2,40}$" + }, + "cmapi.net/cost-center": { + "allOf": [ + { + "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", + "type": "string" + } + ], + "description": "Must match ^cc-[0-9]{4}$.", + "examples": [ + "cc-4410" + ], + "maxLength": 63, + "pattern": "^(?:^cc-[0-9]{4}$)$", + "type": "string", + "x-cmapi-edit": { + "mode": "optional", + "reason": null, + "sensitive": false + }, + "x-cmapi-rule": "must match ^cc-[0-9]{4}$" + }, + "cmapi.net/protected": { + "description": "An operator only (namespaces:protect): another caller gets 403 forbidden.", + "maxLength": 63, + "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", + "type": "string", + "x-cmapi-edit": { + "mode": "optional", + "reason": "Needs namespaces:protect in the namespace's environment. Changing this key needs one more approval.", + "sensitive": true + }, + "x-cmapi-operator-only": true + }, + "cmapi.net/rightsizing": { + "allOf": [ + { + "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", + "type": "string" + } + ], + "description": "Opt-in to automatic rnd and qa decreases. Must match ^(auto|manual)$.", + "maxLength": 63, + "pattern": "^(?:^(auto|manual)$)$", + "type": "string", + "x-cmapi-edit": { + "mode": "optional", + "reason": null, + "sensitive": false + }, + "x-cmapi-rule": "must match ^(auto|manual)$" + }, + "cmapi.net/team": { + "allOf": [ + { + "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", + "type": "string" + } + ], + "description": "Who owns it, for cost and notices: any team name. Not checked against who you are; your Keycloak roles decide what you may do. Must match ^[a-z0-9-]{2,40}$.", + "examples": [ + "payments" + ], + "maxLength": 63, + "minLength": 1, + "pattern": "^(?:^[a-z0-9-]{2,40}$)$", + "title": "Team", + "type": "string", + "x-cmapi-edit": { + "mode": "required", + "reason": "Required on every namespace. Changing this key needs one more approval.", + "sensitive": true + }, + "x-cmapi-rule": "must match ^[a-z0-9-]{2,40}$" + }, + "do-not-delete": { + "description": "An operator only (namespaces:protect): another caller gets 403 forbidden.", + "maxLength": 63, + "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", + "type": "string", + "x-cmapi-edit": { + "mode": "optional", + "reason": "Needs namespaces:protect in the namespace's environment. Changing this key needs one more approval.", + "sensitive": true + }, + "x-cmapi-operator-only": true + } + }, + "propertyNames": { + "anyOf": [ + { + "enum": [ + "cmapi.net/team", + "cmapi.net/cost-center", + "cmapi.net/app", + "cmapi.net/rightsizing", + "cmapi.net/protected", + "do-not-delete" + ] + }, + { + "pattern": "^(?:[^/]+|[^/]*\\.ephico2real\\.com/[^/]+)$" + } + ], + "maxLength": 317, + "not": { + "pattern": "^[^/]{254}" + }, + "pattern": "^(?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?(?:\\.[a-z0-9](?:[-a-z0-9]*[a-z0-9])?)*/)?[A-Za-z0-9](?:[-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$" + }, + "required": [ + "cmapi.net/team" + ], + "type": "object", + "x-cmapi-other-keys": { + "max": 50, + "prefixes": [ + "", + "*.ephico2real.com/" + ], + "sensitiveKeys": [ + "network.ephico2real.com/zone" + ] + } + }, + "x-cmapi-expiration": { + "environments": { + "dev": { + "allowedAtCreate": true, + "enabled": true, + "graceDays": 7, + "maxLifetimeDays": 180, + "notifyDaysBefore": [ + 14, + 7, + 1 + ] + }, + "rnd": { + "allowedAtCreate": true, + "enabled": true, + "graceDays": 7, + "maxLifetimeDays": 180, + "notifyDaysBefore": [ + 14, + 7, + 1 + ] + } + } + } + }, + "schema": { + "$ref": "#/components/schemas/MetadataKeysView" + } + } + }, + "description": "The JSON Schemas of a new namespace's labels and annotations, and the expiration rules of each environment, with an ETag.", + "headers": { + "ETag": { + "description": "The strong ETag of this answer, to send back in If-None-Match.", + "schema": { + "type": "string" + } + } + } + }, + "304": { + "description": "Not modified: the ETag in If-None-Match is still the current one. Use the answer you hold; this one has no body.", + "headers": { + "ETag": { + "description": "The strong ETag of this answer, to send back in If-None-Match.", + "schema": { + "type": "string" + } + } + } + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthenticated": { + "value": { + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "forbidden": { + "value": { + "code": "forbidden", + "detail": "Missing permission objects:read: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + }, + "412": { + "content": { + "application/problem+json": { + "examples": { + "precondition-failed": { + "value": { + "code": "precondition-failed", + "detail": "If-Match does not list the current ETag of this answer: read it again", + "etag": "1f774baf9bf093f8d4ebc497eb0d5b96", + "status": 412, + "title": "precondition failed", + "type": "https://cmapi.ephico2real.com/problems/precondition-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "No strong tag that If-Match lists is the object's ETag: it changed since it was read, or the value named none.\n\nCodes: `precondition-failed`." + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate-limited": { + "value": { + "code": "rate-limited", + "detail": "Too many write calls by this caller; try again in 2 s", + "retryAfter": 2, + "status": 429, + "title": "rate limited", + "type": "https://cmapi.ephico2real.com/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + }, + "503": { + "content": { + "application/problem+json": { + "examples": { + "idp-unavailable": { + "value": { + "code": "idp-unavailable", + "detail": "Keycloak signing keys are unreachable and this key is not cached", + "retryAfter": 30, + "status": 503, + "title": "idp unavailable", + "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + } + }, + "security": [ + { + "keycloak": [] + } + ], + "summary": "Get namespace label and annotation rules", + "tags": [ + "core" + ], + "x-cmapi-permission": "objects:read", + "x-cmapi-plugin": "core", + "x-cmapi-rate-limit": "read", + "x-codeSamples": [ + { + "label": "curl", + "lang": "Shell", + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/metadata-keys -H \"Authorization: Bearer $TOKEN\"" + } + ], + "x-plugin-version": "0.2.0" + } + }, + "/api/v1/operations": { + "get": { + "description": "The operations that the caller may run where they act, newest first, with each one's progress.\n\n**Requires** `operations:run`.", + "operationId": "operations_list_operations", + "parameters": [ + { + "description": "Only the runs of this template.", + "in": "query", + "name": "template", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only the runs of this template.", + "examples": [ + "tiers-rerender" + ], + "title": "Template" + } + }, + { + "description": "Only the runs in this phase.", + "in": "query", + "name": "phase", + "required": false, + "schema": { + "anyOf": [ + { + "enum": [ + "Pending", + "Running", + "Succeeded", + "Failed", + "Error", + "Stopped" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Only the runs in this phase.", + "examples": [ + "Running" + ], + "title": "Phase" + } + }, + { + "description": "The number of rows in one page: 25, 50 or 100, and never more than 200. A larger result is not cut: `page.nextCursor` gives the next page.", + "in": "query", + "name": "limit", + "required": false, + "schema": { + "default": 50, + "description": "The number of rows in one page: 25, 50 or 100, and never more than 200. A larger result is not cut: `page.nextCursor` gives the next page.", + "examples": [ + 50 + ], + "title": "Limit", + "type": "integer" + } + }, + { + "description": "`page.nextCursor` or `page.prevCursor` of an earlier page of the same filters and sort. A cursor of other filters returns 400 `invalid-cursor`.", + "in": "query", + "name": "cursor", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "`page.nextCursor` or `page.prevCursor` of an earlier page of the same filters and sort. A cursor of other filters returns 400 `invalid-cursor`.", + "examples": [ + "eyJrIjpbInBheW1lbnRzLWRldiIsIkNSQyJdLCJkIjoibmV4dCJ9.2f1c" + ], + "title": "Cursor" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "items": [ + { + "cancelRequestedAt": null, + "cancelRequestedBy": null, + "engine": "builtin", + "environments": [ + "dev" + ], + "finishedAt": null, + "links": { + "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + "self": "/api/v1/operations/op-20261201-7fead487" + }, + "operationId": "op-20261201-7fead487", + "parameters": { + "batchSize": 20, + "environments": [ + "dev" + ], + "maxOpenPerCluster": 5, + "tier": "small" + }, + "phase": "Running", + "progress": { + "finished": 0, + "phases": { + "Running": 1 + }, + "total": 1 + }, + "runName": "op-20261201-7fead487", + "startedAt": "2026-12-01T15:13:36.696696Z", + "startedBy": "opal", + "template": "tiers-rerender" + } + ], + "letters": { + "T": 1 + }, + "page": { + "from": 1, + "limit": 50, + "nextCursor": null, + "prevCursor": null, + "to": 1, + "total": 1 + } + }, + "schema": { + "$ref": "#/components/schemas/OperationPage" + } + } + }, + "description": "One page of operations, newest first, each with its progress." + }, + "400": { + "content": { + "application/problem+json": { + "examples": { + "invalid-cursor": { + "value": { + "code": "invalid-cursor", + "detail": "The cursor is not valid", + "status": 400, + "title": "invalid cursor", + "type": "https://cmapi.ephico2real.com/problems/invalid-cursor" + } + }, + "invalid-limit": { + "value": { + "code": "invalid-limit", + "detail": "limit is one of (25, 50, 100), at most 200", + "status": 400, + "title": "invalid limit", + "type": "https://cmapi.ephico2real.com/problems/invalid-limit" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `invalid-cursor`, `invalid-limit`." + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthenticated": { + "value": { + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "forbidden": { + "value": { + "code": "forbidden", + "detail": "Missing permission operations:run: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate-limited": { + "value": { + "code": "rate-limited", + "detail": "Too many write calls by this caller; try again in 2 s", + "retryAfter": 2, + "status": 429, + "title": "rate limited", + "type": "https://cmapi.ephico2real.com/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + }, + "503": { + "content": { + "application/problem+json": { + "examples": { + "idp-unavailable": { + "value": { + "code": "idp-unavailable", + "detail": "Keycloak signing keys are unreachable and this key is not cached", + "retryAfter": 30, + "status": 503, + "title": "idp unavailable", + "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", + "headers": { + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, + "schema": { + "minimum": 1, + "type": "integer" + } + } + } + } + }, + "security": [ + { + "keycloak": [] + } + ], + "summary": "List operations", + "tags": [ + "operations" + ], + "x-cmapi-permission": "operations:run", + "x-cmapi-plugin": "operations", + "x-cmapi-rate-limit": "read", + "x-codeSamples": [ + { + "label": "curl", + "lang": "Shell", + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/operations -H \"Authorization: Bearer $TOKEN\"" + } + ], + "x-plugin-version": "0.2.0" + }, + "post": { + "description": "Starts a run of a template on the engine that integrations.yaml names. The answer comes before any step runs; read\n`GET /api/v1/operations/{id}` for its progress. A step that changes a namespace opens an ordinary request, which the\napproval rules decide as any other: the run waits for each one, and the person who started the run cannot approve them.\nRuns start only through this call (docs/02, rule 2).\n\n**Requires** `operations:run`.", + "operationId": "operations_start", + "parameters": [ + { + "description": "A new random value for each new operation, such as a UUID, of at most 100 characters. Required. The same caller sending the same body with the same key gets the operation it started, in its current state, for as long as the operation is kept; the same key with another body is 409 `idempotency-replay`.", + "in": "header", + "name": "Idempotency-Key", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "A new random value for each new operation, such as a UUID, of at most 100 characters. Required. The same caller sending the same body with the same key gets the operation it started, in its current state, for as long as the operation is kept; the same key with another body is 409 `idempotency-replay`.", + "examples": [ + "0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10" + ], + "title": "Idempotency-Key" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "example": { + "parameters": { + "environments": [ + "dev" + ], + "tier": "small" + }, + "template": "tiers-rerender" + }, + "schema": { + "$ref": "#/components/schemas/OperationStart" + } + } + }, + "required": true + }, + "responses": { + "202": { + "content": { + "application/json": { + "example": { + "cancelRequestedAt": null, + "cancelRequestedBy": null, + "engine": "builtin", + "environments": [ + "dev" + ], + "finishedAt": null, + "links": { + "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + "self": "/api/v1/operations/op-20261201-7fead487" + }, + "operationId": "op-20261201-7fead487", + "parameters": { + "batchSize": 20, + "environments": [ + "dev" + ], + "maxOpenPerCluster": 5, + "tier": "small" + }, + "phase": "Running", + "progress": { + "finished": 0, + "phases": { + "Running": 1 + }, + "total": 1 + }, + "report": null, + "runName": "op-20261201-7fead487", + "startedAt": "2026-12-01T15:13:36.696696Z", + "startedBy": "opal", + "steps": [ + { + "attempts": 0, + "clusterId": "", + "finishedAt": null, + "item": "", + "lastError": null, + "outputs": null, + "phase": "Running", + "startedAt": "2026-12-01T15:13:36.480026Z", + "step": "select-outdated" + } + ], + "template": "tiers-rerender" + }, + "schema": { + "$ref": "#/components/schemas/Operation" + } + } + }, + "description": "The operation, started: its first steps are queued for the worker. `links.self` is its status." + }, + "400": { + "content": { + "application/problem+json": { + "examples": { + "dry-run-not-supported": { + "value": { + "code": "dry-run-not-supported", + "detail": "This call has no dry run, and nothing was done", + "status": 400, + "title": "dry run not supported", + "type": "https://cmapi.ephico2real.com/problems/dry-run-not-supported" + } + }, + "idempotency-key-required": { + "value": { + "code": "idempotency-key-required", + "detail": "Idempotency-Key header is required on writes", + "status": 400, + "title": "idempotency key required", + "type": "https://cmapi.ephico2real.com/problems/idempotency-key-required" + } + } }, "schema": { - "$ref": "#/components/schemas/Me" + "$ref": "#/components/schemas/ProblemDetail" } } }, - "description": "The caller's identity, roles, groups and permissions, with the environments each role covers." + "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `idempotency-key-required`, `dry-run-not-supported`." }, "401": { "content": { @@ -20740,6 +22444,156 @@ }, "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "environment-forbidden": { + "value": { + "code": "environment-forbidden", + "detail": "Your roles grant operations:run only in ['rnd'], not dev", + "status": 403, + "title": "environment forbidden", + "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" + } + }, + "forbidden": { + "value": { + "code": "forbidden", + "detail": "Missing permission operations:run: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`, `environment-forbidden`." + }, + "404": { + "content": { + "application/problem+json": { + "examples": { + "cluster-not-found": { + "value": { + "code": "cluster-not-found", + "detail": "Unknown cluster OCP_X", + "status": 404, + "title": "cluster not found", + "type": "https://cmapi.ephico2real.com/problems/cluster-not-found" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "What the path names is not known.\n\nCodes: `cluster-not-found`." + }, + "409": { + "content": { + "application/problem+json": { + "examples": { + "idempotency-replay": { + "value": { + "code": "idempotency-replay", + "detail": "Idempotency-Key was used for a different request", + "status": 409, + "title": "idempotency replay", + "type": "https://cmapi.ephico2real.com/problems/idempotency-replay" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `idempotency-replay`." + }, + "413": { + "content": { + "application/problem+json": { + "examples": { + "content-too-large": { + "value": { + "code": "content-too-large", + "detail": "The request content is larger than 1048576 bytes, the most that this instance reads", + "maxBytes": 1048576, + "status": 413, + "title": "content too large", + "type": "https://cmapi.ephico2real.com/problems/content-too-large" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request content is larger than this instance reads; `maxBytes` says how many bytes it reads. Nothing was done.\n\nCodes: `content-too-large`." + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "environment-not-served": { + "value": { + "code": "environment-not-served", + "detail": "qa is not served by the nonprod instance", + "instanceUrl": "https://cmapi-staging.ephico2real.com", + "portalUrl": "https://portal-staging.ephico2real.com", + "status": 422, + "title": "environment not served", + "type": "https://cmapi.ephico2real.com/problems/environment-not-served" + } + }, + "operation-template-unknown": { + "value": { + "code": "operation-template-unknown", + "detail": "No operation template 'tier-rerender'; this build has ['cluster-onboard', 'rebuild-verify', 'reconcile', 'tiers-rerender']", + "status": 422, + "templates": [ + "cluster-onboard", + "rebuild-verify", + "reconcile", + "tiers-rerender" + ], + "title": "operation template unknown", + "type": "https://cmapi.ephico2real.com/problems/operation-template-unknown" + } + }, + "policy-violation": { + "value": { + "code": "policy-violation", + "detail": "Metadata refused", + "status": 422, + "title": "policy violation", + "type": "https://cmapi.ephico2real.com/problems/policy-violation" + } + }, + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `operation-template-unknown`, `validation-failed`, `environment-not-served`, `policy-violation`." + }, "429": { "content": { "application/problem+json": { @@ -20785,6 +22639,15 @@ "title": "idp unavailable", "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" } + }, + "operations-engine-unavailable": { + "value": { + "code": "operations-engine-unavailable", + "detail": "The argo-workflows engine that integrations.yaml operations.engine names has no adapter in this build; set it to builtin, which runs the same templates in the cmapi worker", + "status": 503, + "title": "operations engine unavailable", + "type": "https://cmapi.ephico2real.com/problems/operations-engine-unavailable" + } } }, "schema": { @@ -20792,11 +22655,11 @@ } } }, - "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `operations-engine-unavailable`, `idp-unavailable`.", "headers": { "Retry-After": { - "description": "The seconds to wait before the next call: the same number as `retryAfter`.", - "required": true, + "description": "The seconds to wait before the next call: the same number as `retryAfter`. Sent with `idp-unavailable`.", + "required": false, "schema": { "minimum": 1, "type": "integer" @@ -20810,338 +22673,393 @@ "keycloak": [] } ], - "summary": "Get the caller's identity and permissions", + "summary": "Start an operation", "tags": [ - "core" + "operations" ], - "x-cmapi-plugin": "core", - "x-cmapi-rate-limit": "read", + "x-cmapi-permission": "operations:run", + "x-cmapi-plugin": "operations", + "x-cmapi-rate-limit": "write", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/me -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/operations -H \"Authorization: Bearer $TOKEN\" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'Content-Type: application/json' -d '{\"parameters\": {\"environments\": [\"dev\"], \"tier\": \"small\"}, \"template\": \"tiers-rerender\"}'" } ], "x-plugin-version": "0.2.0" } }, - "/api/v1/metadata-keys": { + "/api/v1/operations/{operation_id}": { "get": { - "description": "This instance's metadata-keys.yaml as the JSON Schema 2020-12 of a new namespace's labels and annotations: each\ndeclared key with its rule, which keys are required, which cmapi fills in (x-cmapi-derived-from), and which only an\noperator (namespaces:protect) may set. The same schemas as NamespaceCreate in the API document, here also when\ndocs.enabled is false. Each property carries x-cmapi-rule, the rule in the words of a refusal, and title when the file\ngives one. x-cmapi-expiration is expiresAt's: each served environment's expiration rules (expiration.yaml).\n\nEach property also carries x-cmapi-edit, how the key may change on an existing namespace (#481): `mode` fixed (part of\nthe namespace's fixed name), automatic (filled in by cmapi), required or optional, the `reason` a person sees, and\n`sensitive` when a change of it adds one approval. One answer, the same for a create and a change.\n\ncmapi checks every request against the file itself: this answer describes the rules, it does not replace them. The\nanswer is the instance's, the same for every caller; it has a strong ETag. If-None-Match answers 304, and an If-Match\nthat does not list the ETag answers 412.\n\n**Requires** `objects:read`.", - "operationId": "core_metadata_keys", + "description": "The status of record of one operation (docs/02): each step row with its phase, the requests it opened and why any\ndid not succeed.\n\n**Requires** `operations:run`.", + "operationId": "operations_get_operation", "parameters": [ { - "description": "The ETag of the answer the caller holds. If it is still the current one, the answer is 304 with no body.", - "in": "header", - "name": "If-None-Match", - "required": false, - "schema": { - "examples": [ - "\"1f774baf9bf093f8d4ebc497eb0d5b96\"" - ], - "type": "string" - } - }, - { - "description": "Optional on a read. The answer is sent only if one strong tag listed here is its current ETag, or if the value is `*`; otherwise it is 412 `precondition-failed`, with the current tag in `etag`. A weak tag (`W/\"...\"`) never matches. If-Match is read before If-None-Match (RFC 9110, section 13.2.2). Send the tags in one comma-separated If-Match field (`If-Match: \"a\", \"b\"`): the front door answers 400 to a second If-Match line.", - "in": "header", - "name": "If-Match", - "required": false, + "description": "The operation's ID, as the start returned it.", + "in": "path", + "name": "operation_id", + "required": true, "schema": { - "examples": [ - "\"1f774baf9bf093f8d4ebc497eb0d5b96\"" - ], - "type": "string" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "example": { - "annotations": { - "additionalProperties": { - "maxLength": 4096, - "type": "string" - }, - "properties": { - "cmapi.net/protected": { - "description": "An operator only (namespaces:protect): another caller gets 403 forbidden.", - "type": "string", - "x-cmapi-edit": { - "mode": "optional", - "reason": "Needs namespaces:protect in the namespace's environment. Changing this key needs one more approval.", - "sensitive": true - }, - "x-cmapi-operator-only": true - }, - "cmapi.net/team-dl": { - "description": "Your team's distribution list, in one of the organisation's email domains (emailDomains); format only. An address in ['ephico2real.com'].", - "examples": [ - "payments-team@ephico2real.com" - ], - "minLength": 1, - "pattern": "^[A-Za-z0-9!#$%&'*+/=?^_`{|}~.-]+@(?:[eE][pP][hH][iI][cC][oO]2[rR][eE][aA][lL]\\.[cC][oO][mM])$", - "title": "Team DL", - "type": "string", - "x-cmapi-edit": { - "mode": "required", - "reason": "Required on every namespace.", - "sensitive": false - }, - "x-cmapi-format": "email-in-domains", - "x-cmapi-rule": "an address in ['ephico2real.com']" - }, - "do-not-delete": { - "description": "An operator only (namespaces:protect): another caller gets 403 forbidden.", - "type": "string", - "x-cmapi-edit": { - "mode": "optional", - "reason": "Needs namespaces:protect in the namespace's environment. Changing this key needs one more approval.", - "sensitive": true - }, - "x-cmapi-operator-only": true - } - }, - "propertyNames": { - "anyOf": [ - { - "enum": [ - "cmapi.net/team-dl", - "cmapi.net/protected", - "do-not-delete" - ] - }, - { - "pattern": "^(?:[^/]+|[^/]*\\.ephico2real\\.com/[^/]+)$" - } - ], - "maxLength": 317, - "not": { - "pattern": "^[^/]{254}" - }, - "pattern": "^(?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?(?:\\.[a-z0-9](?:[-a-z0-9]*[a-z0-9])?)*/)?[A-Za-z0-9](?:[-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$" - }, - "required": [ - "cmapi.net/team-dl" + "description": "The operation's ID, as the start returned it.", + "examples": [ + "op-20261201-3f9a1c2e" + ], + "title": "Operation Id", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "cancelRequestedAt": "2026-12-01T15:13:36.705960Z", + "cancelRequestedBy": "opal", + "engine": "builtin", + "environments": [ + "dev" + ], + "finishedAt": "2026-12-01T15:13:36.995319Z", + "links": { + "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + "self": "/api/v1/operations/op-20261201-7fead487" + }, + "operationId": "op-20261201-7fead487", + "parameters": { + "batchSize": 20, + "environments": [ + "dev" ], - "type": "object", - "x-cmapi-other-keys": { - "max": 50, - "maxBytesTotal": 65536, - "maxValueBytes": 4096, - "prefixes": [ - "", - "*.ephico2real.com/" - ], - "sensitiveKeys": [ - "network.ephico2real.com/zone" - ] - } + "maxOpenPerCluster": 5, + "tier": "small" }, - "labels": { - "additionalProperties": { - "maxLength": 63, - "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", - "type": "string" + "phase": "Stopped", + "progress": { + "finished": 1, + "phases": { + "Stopped": 1 }, - "properties": { - "cmapi.net/app": { - "allOf": [ - { - "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", - "type": "string" - } - ], - "description": "Links an app's environments. Must match ^[a-z0-9-]{2,40}$.", - "maxLength": 63, - "pattern": "^(?:^[a-z0-9-]{2,40}$)$", - "type": "string", - "x-cmapi-edit": { - "mode": "optional", - "reason": null, - "sensitive": false - }, - "x-cmapi-rule": "must match ^[a-z0-9-]{2,40}$" - }, - "cmapi.net/cost-center": { - "allOf": [ - { - "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", - "type": "string" - } - ], - "description": "Must match ^cc-[0-9]{4}$.", - "examples": [ - "cc-4410" - ], - "maxLength": 63, - "pattern": "^(?:^cc-[0-9]{4}$)$", - "type": "string", - "x-cmapi-edit": { - "mode": "optional", - "reason": null, - "sensitive": false - }, - "x-cmapi-rule": "must match ^cc-[0-9]{4}$" - }, - "cmapi.net/protected": { - "description": "An operator only (namespaces:protect): another caller gets 403 forbidden.", - "maxLength": 63, - "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", - "type": "string", - "x-cmapi-edit": { - "mode": "optional", - "reason": "Needs namespaces:protect in the namespace's environment. Changing this key needs one more approval.", - "sensitive": true - }, - "x-cmapi-operator-only": true - }, - "cmapi.net/rightsizing": { - "allOf": [ - { - "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", - "type": "string" - } - ], - "description": "Opt-in to automatic rnd and qa decreases. Must match ^(auto|manual)$.", - "maxLength": 63, - "pattern": "^(?:^(auto|manual)$)$", - "type": "string", - "x-cmapi-edit": { - "mode": "optional", - "reason": null, - "sensitive": false - }, - "x-cmapi-rule": "must match ^(auto|manual)$" - }, - "cmapi.net/team": { - "allOf": [ - { - "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", - "type": "string" - } - ], - "description": "Who owns it, for cost and notices: any team name. Not checked against who you are; your Keycloak roles decide what you may do. Must match ^[a-z0-9-]{2,40}$.", - "examples": [ - "payments" - ], - "maxLength": 63, - "minLength": 1, - "pattern": "^(?:^[a-z0-9-]{2,40}$)$", - "title": "Team", - "type": "string", - "x-cmapi-edit": { - "mode": "required", - "reason": "Required on every namespace. Changing this key needs one more approval.", - "sensitive": true - }, - "x-cmapi-rule": "must match ^[a-z0-9-]{2,40}$" - }, - "do-not-delete": { - "description": "An operator only (namespaces:protect): another caller gets 403 forbidden.", - "maxLength": 63, - "pattern": "^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]*[A-Za-z0-9])?)?$", - "type": "string", - "x-cmapi-edit": { - "mode": "optional", - "reason": "Needs namespaces:protect in the namespace's environment. Changing this key needs one more approval.", - "sensitive": true + "total": 1 + }, + "report": { + "steps": [ + { + "items": [], + "phases": { + "Stopped": 1 }, - "x-cmapi-operator-only": true + "step": "select-outdated" } - }, - "propertyNames": { - "anyOf": [ - { - "enum": [ - "cmapi.net/team", - "cmapi.net/cost-center", - "cmapi.net/app", - "cmapi.net/rightsizing", - "cmapi.net/protected", - "do-not-delete" - ] - }, - { - "pattern": "^(?:[^/]+|[^/]*\\.ephico2real\\.com/[^/]+)$" - } - ], - "maxLength": 317, - "not": { - "pattern": "^[^/]{254}" + ] + }, + "runName": "op-20261201-7fead487", + "startedAt": "2026-12-01T15:13:36.696696Z", + "startedBy": "opal", + "steps": [ + { + "attempts": 0, + "clusterId": "", + "finishedAt": "2026-12-01T15:13:36.968745Z", + "item": "", + "lastError": null, + "outputs": { + "note": "stopped by opal" }, - "pattern": "^(?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?(?:\\.[a-z0-9](?:[-a-z0-9]*[a-z0-9])?)*/)?[A-Za-z0-9](?:[-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$" - }, - "required": [ - "cmapi.net/team" - ], - "type": "object", - "x-cmapi-other-keys": { - "max": 50, - "prefixes": [ - "", - "*.ephico2real.com/" - ], - "sensitiveKeys": [ - "network.ephico2real.com/zone" - ] + "phase": "Stopped", + "startedAt": "2026-12-01T15:13:36.480026Z", + "step": "select-outdated" + } + ], + "template": "tiers-rerender" + }, + "schema": { + "$ref": "#/components/schemas/Operation" + } + } + }, + "description": "The operation with every step row: its phase, attempts, outputs and last error; and its report once it ended." + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthenticated": { + "value": { + "code": "unauthenticated", + "detail": "Bearer token required", + "status": 401, + "title": "unauthenticated", + "type": "https://cmapi.ephico2real.com/problems/unauthenticated" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "No token, or the token is not valid.\n\nCodes: `unauthenticated`." + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "environment-forbidden": { + "value": { + "code": "environment-forbidden", + "detail": "Your roles grant operations:run only in ['rnd'], not dev", + "status": 403, + "title": "environment forbidden", + "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" + } + }, + "forbidden": { + "value": { + "code": "forbidden", + "detail": "Missing permission operations:run: no role in your token grants it (roles: ['cmapi-requester'])", + "status": 403, + "title": "forbidden", + "type": "https://cmapi.ephico2real.com/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`, `environment-forbidden`." + }, + "404": { + "content": { + "application/problem+json": { + "examples": { + "object-not-found": { + "value": { + "code": "object-not-found", + "detail": "No request req-20261105-0001", + "status": 404, + "title": "object not found", + "type": "https://cmapi.ephico2real.com/problems/object-not-found" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "What the path names is not known.\n\nCodes: `object-not-found`." + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" } - }, - "x-cmapi-expiration": { - "environments": { - "dev": { - "allowedAtCreate": true, - "enabled": true, - "graceDays": 7, - "maxLifetimeDays": 180, - "notifyDaysBefore": [ - 14, - 7, - 1 - ] - }, - "rnd": { - "allowedAtCreate": true, - "enabled": true, - "graceDays": 7, - "maxLifetimeDays": 180, - "notifyDaysBefore": [ - 14, - 7, - 1 - ] - } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate-limited": { + "value": { + "code": "rate-limited", + "detail": "Too many write calls by this caller; try again in 2 s", + "retryAfter": 2, + "status": 429, + "title": "rate limited", + "type": "https://cmapi.ephico2real.com/problems/rate-limited" } } }, "schema": { - "$ref": "#/components/schemas/MetadataKeysView" + "$ref": "#/components/schemas/ProblemDetail" } } }, - "description": "The JSON Schemas of a new namespace's labels and annotations, and the expiration rules of each environment, with an ETag.", + "description": "Too many calls by this caller in the bucket that `x-cmapi-rate-limit` names, or too many new requests for the team. Wait for the seconds in `Retry-After`, which `retryAfter` repeats. Nothing was done.\n\nCodes: `rate-limited`.", "headers": { - "ETag": { - "description": "The strong ETag of this answer, to send back in If-None-Match.", + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, "schema": { - "type": "string" + "minimum": 1, + "type": "integer" } } } }, - "304": { - "description": "Not modified: the ETag in If-None-Match is still the current one. Use the answer you hold; this one has no body.", + "503": { + "content": { + "application/problem+json": { + "examples": { + "idp-unavailable": { + "value": { + "code": "idp-unavailable", + "detail": "Keycloak signing keys are unreachable and this key is not cached", + "retryAfter": 30, + "status": 503, + "title": "idp unavailable", + "type": "https://cmapi.ephico2real.com/problems/idp-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A service that cmapi depends on is not answering. Try again later; `retryAfter`, when present, says when.\n\nCodes: `idp-unavailable`.", "headers": { - "ETag": { - "description": "The strong ETag of this answer, to send back in If-None-Match.", + "Retry-After": { + "description": "The seconds to wait before the next call: the same number as `retryAfter`.", + "required": true, "schema": { - "type": "string" + "minimum": 1, + "type": "integer" } } } + } + }, + "security": [ + { + "keycloak": [] + } + ], + "summary": "Get an operation", + "tags": [ + "operations" + ], + "x-cmapi-permission": "operations:run", + "x-cmapi-plugin": "operations", + "x-cmapi-rate-limit": "read", + "x-codeSamples": [ + { + "label": "curl", + "lang": "Shell", + "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/operations/op-20261201-3f9a1c2e -H \"Authorization: Bearer $TOKEN\"" + } + ], + "x-plugin-version": "0.2.0" + } + }, + "/api/v1/operations/{operation_id}:cancel": { + "post": { + "description": "Stops a run that has not ended. A request that a step opened is not cancelled with it: it is an ordinary request,\nwhich its requester or an operator cancels on its own (`POST /api/v1/requests/{id}:cancel`); the report lists it. A\nsecond cancel returns the operation as it is.\n\n**Requires** `operations:run`.", + "operationId": "operations_cancel", + "parameters": [ + { + "description": "The operation's ID, as the start returned it.", + "in": "path", + "name": "operation_id", + "required": true, + "schema": { + "description": "The operation's ID, as the start returned it.", + "examples": [ + "op-20261201-3f9a1c2e" + ], + "title": "Operation Id", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "example": { + "cancelRequestedAt": "2026-12-01T15:13:36.705960Z", + "cancelRequestedBy": "opal", + "engine": "builtin", + "environments": [ + "dev" + ], + "finishedAt": null, + "links": { + "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + "self": "/api/v1/operations/op-20261201-7fead487" + }, + "operationId": "op-20261201-7fead487", + "parameters": { + "batchSize": 20, + "environments": [ + "dev" + ], + "maxOpenPerCluster": 5, + "tier": "small" + }, + "phase": "Running", + "progress": { + "finished": 0, + "phases": { + "Running": 1 + }, + "total": 1 + }, + "report": null, + "runName": "op-20261201-7fead487", + "startedAt": "2026-12-01T15:13:36.696696Z", + "startedBy": "opal", + "steps": [ + { + "attempts": 0, + "clusterId": "", + "finishedAt": null, + "item": "", + "lastError": null, + "outputs": null, + "phase": "Running", + "startedAt": "2026-12-01T15:13:36.480026Z", + "step": "select-outdated" + } + ], + "template": "tiers-rerender" + }, + "schema": { + "$ref": "#/components/schemas/Operation" + } + } + }, + "description": "The operation: no new step starts, the steps not started and the steps waiting are Stopped, and it ends Stopped once the step that runs now ends." + }, + "400": { + "content": { + "application/problem+json": { + "examples": { + "dry-run-not-supported": { + "value": { + "code": "dry-run-not-supported", + "detail": "This call has no dry run, and nothing was done", + "status": 400, + "title": "dry run not supported", + "type": "https://cmapi.ephico2real.com/problems/dry-run-not-supported" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "A header or a parameter that cmapi reads first is missing or not valid.\n\nCodes: `dry-run-not-supported`." }, "401": { "content": { @@ -21168,10 +23086,19 @@ "content": { "application/problem+json": { "examples": { + "environment-forbidden": { + "value": { + "code": "environment-forbidden", + "detail": "Your roles grant operations:run only in ['rnd'], not dev", + "status": 403, + "title": "environment forbidden", + "type": "https://cmapi.ephico2real.com/problems/environment-forbidden" + } + }, "forbidden": { "value": { "code": "forbidden", - "detail": "Missing permission objects:read: no role in your token grants it (roles: ['cmapi-requester'])", + "detail": "Missing permission operations:run: no role in your token grants it (roles: ['cmapi-requester'])", "status": 403, "title": "forbidden", "type": "https://cmapi.ephico2real.com/problems/forbidden" @@ -21183,20 +23110,19 @@ } } }, - "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`." + "description": "The caller may not do this, or not in this environment.\n\nCodes: `forbidden`, `environment-forbidden`." }, - "412": { + "404": { "content": { "application/problem+json": { "examples": { - "precondition-failed": { + "object-not-found": { "value": { - "code": "precondition-failed", - "detail": "If-Match does not list the current ETag of this answer: read it again", - "etag": "1f774baf9bf093f8d4ebc497eb0d5b96", - "status": 412, - "title": "precondition failed", - "type": "https://cmapi.ephico2real.com/problems/precondition-failed" + "code": "object-not-found", + "detail": "No request req-20261105-0001", + "status": 404, + "title": "object not found", + "type": "https://cmapi.ephico2real.com/problems/object-not-found" } } }, @@ -21205,7 +23131,50 @@ } } }, - "description": "No strong tag that If-Match lists is the object's ETag: it changed since it was read, or the value named none.\n\nCodes: `precondition-failed`." + "description": "What the path names is not known.\n\nCodes: `object-not-found`." + }, + "409": { + "content": { + "application/problem+json": { + "examples": { + "invalid-transition": { + "value": { + "code": "invalid-transition", + "detail": "op-20261201-7fead487 ended Stopped", + "state": "Stopped", + "status": 409, + "title": "invalid transition", + "type": "https://cmapi.ephico2real.com/problems/invalid-transition" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "It conflicts with the current state of the object, of an open request or of the Idempotency-Key.\n\nCodes: `invalid-transition`." + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "validation-failed": { + "value": { + "code": "validation-failed", + "detail": "Request body is not valid", + "status": 422, + "title": "validation failed", + "type": "https://cmapi.ephico2real.com/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/ProblemDetail" + } + } + }, + "description": "The request breaks a rule. `code` says which; a policy refusal lists each item in `errors`.\n\nCodes: `validation-failed`." }, "429": { "content": { @@ -21277,18 +23246,18 @@ "keycloak": [] } ], - "summary": "Get namespace label and annotation rules", + "summary": "Cancel an operation", "tags": [ - "core" + "operations" ], - "x-cmapi-permission": "objects:read", - "x-cmapi-plugin": "core", - "x-cmapi-rate-limit": "read", + "x-cmapi-permission": "operations:run", + "x-cmapi-plugin": "operations", + "x-cmapi-rate-limit": "write", "x-codeSamples": [ { "label": "curl", "lang": "Shell", - "source": "curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/metadata-keys -H \"Authorization: Bearer $TOKEN\"" + "source": "curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/operations/op-20261201-3f9a1c2e:cancel -H \"Authorization: Bearer $TOKEN\"" } ], "x-plugin-version": "0.2.0" @@ -21497,7 +23466,7 @@ "content": { "application/json": { "example": { - "from": "2026-11-20T20:59:12.816211Z", + "from": "2026-11-24T15:13:31.152927Z", "items": [ { "action": "create", @@ -21516,9 +23485,9 @@ "source": "cmapi" } ], - "firstAt": "2026-11-27T20:59:09.886777Z", + "firstAt": "2026-12-01T15:13:26.735685Z", "id": "rej-2", - "lastAt": "2026-11-27T20:59:09.886777Z", + "lastAt": "2026-12-01T15:13:26.735685Z", "namespace": "kube-tools", "outcome": "refused", "plugin": "namespaces", @@ -21536,7 +23505,7 @@ "findings": [ { "kyvernoRule": null, - "message": "the head moved from 479aab8d to 9df23668 after the pull request was opened", + "message": "the head moved from 4afd09a1 to 00ee2444 after the pull request was opened", "path": null, "policy": "cmapi-check", "rule": null, @@ -21544,14 +23513,14 @@ "source": "cmapi" } ], - "firstAt": "2026-11-27T20:59:03.193672Z", + "firstAt": "2026-12-01T15:13:12.465909Z", "id": "rej-1", - "lastAt": "2026-11-27T20:59:03.193672Z", + "lastAt": "2026-12-01T15:13:12.465909Z", "namespace": "search-dev", "outcome": "refused", "plugin": "namespaces", "problem": null, - "requestId": "req-20261127-0007", + "requestId": "req-20261201-0007", "stage": "ci", "username": "ola" } @@ -21921,7 +23890,7 @@ "example": { "clusters": [ { - "asOf": "2026-11-27T20:59:12.694710Z", + "asOf": "2026-12-01T15:13:30.959859Z", "bundle": { "actionsDiffer": [], "actionsDifferTotal": 0, @@ -24047,14 +26016,14 @@ ], "timeoutHours": 8 }, - "baseSha": "80f4f1badad17a36a1e6c5d25834f76fef11435b", + "baseSha": "513f40b0ee251859ba80791976ccc3addcfdf1ba", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:55.923726Z", + "createdAt": "2026-12-01T15:12:57.455807Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:56.005112Z", + "at": "2026-12-01T15:12:57.536560Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", @@ -24071,16 +26040,16 @@ "instance": "nonprod", "justification": "Load test next sprint", "links": { - "events": "/api/v1/requests/req-20261127-0002/events", - "self": "/api/v1/requests/req-20261127-0002" + "events": "/api/v1/requests/req-20261201-0002/events", + "self": "/api/v1/requests/req-20261201-0002" }, "mergeSha": null, "namespace": "payments-dev", - "planHash": "df5602a2038007a6de28e19adf060fd6b5f8fb3d5b86637f790b31efdc510039", + "planHash": "7aebcbffedf4cef6b095bd7594ab08df7c4f3964ede6f8138b15048c990b9ed3", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0002", + "requestId": "req-20261201-0002", "requester": { "automated": false, "requester": { @@ -24098,7 +26067,7 @@ "submittedByClient": null }, "status": "pending_approval", - "updatedAt": "2026-11-27T20:58:55.904486Z" + "updatedAt": "2026-12-01T15:12:57.263260Z" } ], "letters": { @@ -24343,67 +26312,67 @@ "baseSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:54.441022Z", + "createdAt": "2026-12-01T15:12:55.670320Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:54.488801Z", + "at": "2026-12-01T15:12:55.724895Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", "status": "approved" }, { - "at": "2026-11-27T20:58:54.586895Z", + "at": "2026-12-01T15:12:55.840600Z", "by": "cmapi-bot", "event": "branch_pushed", - "note": "cmapi/CRC/req-20261127-0001 at 80f4f1ba on aaaaaaaa (created)", + "note": "cmapi/CRC/req-20261201-0001 at 513f40b0 on aaaaaaaa (created)", "status": "approved" }, { - "at": "2026-11-27T20:58:54.636706Z", + "at": "2026-12-01T15:12:55.901812Z", "by": "cmapi-bot", "event": "pr_opened", - "note": "cmapi/CRC/req-20261127-0001 #1", + "note": "cmapi/CRC/req-20261201-0001 #1", "status": "pr_open" }, { - "at": "2026-11-27T20:58:54.677782Z", + "at": "2026-12-01T15:12:55.945117Z", "by": "ci", "event": "ci", "note": "kubeconform: pass; kyverno: pass; cmapi check: pass", "status": "pr_open" }, { - "at": "2026-11-27T20:58:54.757184Z", + "at": "2026-12-01T15:12:56.052717Z", "by": "cmapi-deliverer", "event": "apply_started", - "note": "applying 80f4f1ba before the merge", + "note": "applying 513f40b0 before the merge", "status": "pr_open" }, { - "at": "2026-11-27T20:58:54.799387Z", + "at": "2026-12-01T15:12:56.124941Z", "by": "cmapi-deliverer", "event": "applied", - "note": "5 objects from cmapi/CRC/req-20261127-0001 at 80f4f1ba, before the merge, confirmed by a read: 1 Namespace, 1 ResourceQuota and 2 LimitRanges match the plan", + "note": "5 objects from cmapi/CRC/req-20261201-0001 at 513f40b0, before the merge, confirmed by a read: 1 Namespace, 1 ResourceQuota and 2 LimitRanges match the plan, as do 1 RoleBinding", "status": "applied" }, { - "at": "2026-11-27T20:58:54.850841Z", + "at": "2026-12-01T15:12:56.188647Z", "by": "worker", "event": "merge_verified", - "note": "merged 80f4f1ba; the folder at it is the plan's", + "note": "merged 513f40b0; the folder at it is the plan's", "status": "applied" }, { - "at": "2026-11-27T20:58:54.864833Z", + "at": "2026-12-01T15:12:56.204485Z", "by": "cmapi-bot", "event": "merged", - "note": "merged 80f4f1ba", + "note": "merged 513f40b0", "status": "merged" }, { - "at": "2026-11-27T20:58:54.881820Z", + "at": "2026-12-01T15:12:56.223876Z", "by": "cmapi-deliverer", "event": "synced", "note": "applied and confirmed by a read before the merge", @@ -24420,22 +26389,22 @@ "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0001/events", + "events": "/api/v1/requests/req-20261201-0001/events", "pr": "https://git.test/pulls/1", - "self": "/api/v1/requests/req-20261127-0001" + "self": "/api/v1/requests/req-20261201-0001" }, - "mergeSha": "80f4f1ba", + "mergeSha": "513f40b0", "namespace": "payments-dev", - "planHash": "9fed510537c2c36b3dc18a5b461ebfac4c2f1b7dfc2a61a394afd47b96624c09", + "planHash": "4e9af3fc1f212f0387b6958adccca82242cc53b7fd67192be64529da18a31563", "plugin": "namespaces", "pr": { - "branch": "cmapi/CRC/req-20261127-0001", - "head": "80f4f1ba", + "branch": "cmapi/CRC/req-20261201-0001", + "head": "513f40b0", "number": 1, "url": "https://git.test/pulls/1" }, "reason": null, - "requestId": "req-20261127-0001", + "requestId": "req-20261201-0001", "requester": { "automated": false, "requester": { @@ -24453,7 +26422,7 @@ "submittedByClient": null }, "status": "synced", - "updatedAt": "2026-11-27T20:58:54.780441Z" + "updatedAt": "2026-12-01T15:12:55.949790Z" }, "schema": { "$ref": "#/components/schemas/ChangeRequest" @@ -24668,8 +26637,8 @@ "application/json": { "example": { "approved": true, - "planHash": "9fed510537c2c36b3dc18a5b461ebfac4c2f1b7dfc2a61a394afd47b96624c09", - "requestId": "req-20261127-0001", + "planHash": "4e9af3fc1f212f0387b6958adccca82242cc53b7fd67192be64529da18a31563", + "requestId": "req-20261201-0001", "status": "synced" }, "schema": { @@ -24886,70 +26855,70 @@ "example": { "events": [ { - "at": "2026-11-27T20:58:54.488801Z", + "at": "2026-12-01T15:12:55.724895Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", "status": "approved" }, { - "at": "2026-11-27T20:58:54.586895Z", + "at": "2026-12-01T15:12:55.840600Z", "by": "cmapi-bot", "event": "branch_pushed", - "note": "cmapi/CRC/req-20261127-0001 at 80f4f1ba on aaaaaaaa (created)", + "note": "cmapi/CRC/req-20261201-0001 at 513f40b0 on aaaaaaaa (created)", "status": "approved" }, { - "at": "2026-11-27T20:58:54.636706Z", + "at": "2026-12-01T15:12:55.901812Z", "by": "cmapi-bot", "event": "pr_opened", - "note": "cmapi/CRC/req-20261127-0001 #1", + "note": "cmapi/CRC/req-20261201-0001 #1", "status": "pr_open" }, { - "at": "2026-11-27T20:58:54.677782Z", + "at": "2026-12-01T15:12:55.945117Z", "by": "ci", "event": "ci", "note": "kubeconform: pass; kyverno: pass; cmapi check: pass", "status": "pr_open" }, { - "at": "2026-11-27T20:58:54.757184Z", + "at": "2026-12-01T15:12:56.052717Z", "by": "cmapi-deliverer", "event": "apply_started", - "note": "applying 80f4f1ba before the merge", + "note": "applying 513f40b0 before the merge", "status": "pr_open" }, { - "at": "2026-11-27T20:58:54.799387Z", + "at": "2026-12-01T15:12:56.124941Z", "by": "cmapi-deliverer", "event": "applied", - "note": "5 objects from cmapi/CRC/req-20261127-0001 at 80f4f1ba, before the merge, confirmed by a read: 1 Namespace, 1 ResourceQuota and 2 LimitRanges match the plan", + "note": "5 objects from cmapi/CRC/req-20261201-0001 at 513f40b0, before the merge, confirmed by a read: 1 Namespace, 1 ResourceQuota and 2 LimitRanges match the plan, as do 1 RoleBinding", "status": "applied" }, { - "at": "2026-11-27T20:58:54.850841Z", + "at": "2026-12-01T15:12:56.188647Z", "by": "worker", "event": "merge_verified", - "note": "merged 80f4f1ba; the folder at it is the plan's", + "note": "merged 513f40b0; the folder at it is the plan's", "status": "applied" }, { - "at": "2026-11-27T20:58:54.864833Z", + "at": "2026-12-01T15:12:56.204485Z", "by": "cmapi-bot", "event": "merged", - "note": "merged 80f4f1ba", + "note": "merged 513f40b0", "status": "merged" }, { - "at": "2026-11-27T20:58:54.881820Z", + "at": "2026-12-01T15:12:56.223876Z", "by": "cmapi-deliverer", "event": "synced", "note": "applied and confirmed by a read before the merge", "status": "synced" } ], - "requestId": "req-20261127-0001", + "requestId": "req-20261201-0001", "status": "synced" }, "schema": { @@ -25188,7 +27157,7 @@ "approval": { "approvals": [ { - "at": "2026-11-27T20:58:56.181147Z", + "at": "2026-12-01T15:12:57.737114Z", "comment": "sizing reviewed", "relayedBy": null, "sub": "sub-amy", @@ -25213,28 +27182,28 @@ ], "timeoutHours": 8 }, - "baseSha": "80f4f1badad17a36a1e6c5d25834f76fef11435b", + "baseSha": "513f40b0ee251859ba80791976ccc3addcfdf1ba", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:55.923726Z", + "createdAt": "2026-12-01T15:12:57.455807Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:56.005112Z", + "at": "2026-12-01T15:12:57.536560Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", "status": "pending_approval" }, { - "at": "2026-11-27T20:58:56.208815Z", + "at": "2026-12-01T15:12:57.766421Z", "by": "amy", "event": "approval", "note": "sizing reviewed", "status": "pending_approval" }, { - "at": "2026-11-27T20:58:56.231666Z", + "at": "2026-12-01T15:12:57.795342Z", "by": "amy", "event": "approved", "note": "approval count met", @@ -25251,16 +27220,16 @@ "instance": "nonprod", "justification": "Load test next sprint", "links": { - "events": "/api/v1/requests/req-20261127-0002/events", - "self": "/api/v1/requests/req-20261127-0002" + "events": "/api/v1/requests/req-20261201-0002/events", + "self": "/api/v1/requests/req-20261201-0002" }, "mergeSha": null, "namespace": "payments-dev", - "planHash": "df5602a2038007a6de28e19adf060fd6b5f8fb3d5b86637f790b31efdc510039", + "planHash": "7aebcbffedf4cef6b095bd7594ab08df7c4f3964ede6f8138b15048c990b9ed3", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0002", + "requestId": "req-20261201-0002", "requester": { "automated": false, "requester": { @@ -25278,7 +27247,7 @@ "submittedByClient": null }, "status": "approved", - "updatedAt": "2026-11-27T20:58:56.128756Z" + "updatedAt": "2026-12-01T15:12:57.519349Z" }, "schema": { "$ref": "#/components/schemas/ChangeRequest" @@ -25617,21 +27586,21 @@ ], "timeoutHours": 8 }, - "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + "baseSha": "f33469a0b99e67100557d4172703299def66403b", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:00.839033Z", + "createdAt": "2026-12-01T15:13:07.269501Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:00.869605Z", + "at": "2026-12-01T15:13:07.303276Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", "status": "pending_approval" }, { - "at": "2026-11-27T20:59:01.284709Z", + "at": "2026-12-01T15:13:07.829553Z", "by": "ola", "event": "cancel", "note": "", @@ -25648,16 +27617,16 @@ "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0005/events", - "self": "/api/v1/requests/req-20261127-0005" + "events": "/api/v1/requests/req-20261201-0005/events", + "self": "/api/v1/requests/req-20261201-0005" }, "mergeSha": null, "namespace": "ledger-dev", - "planHash": "872bc285608555d97234f8f6f440473a920a3da01e2e5509a176628b51d35ac3", + "planHash": "ce7e669a03e55261cb76f1ec4054133e9985c1ab51a26c1edf7bfb18ea4bf918", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0005", + "requestId": "req-20261201-0005", "requester": { "automated": false, "requester": { @@ -25675,7 +27644,7 @@ "submittedByClient": null }, "status": "cancelled", - "updatedAt": "2026-11-27T20:59:01.183312Z" + "updatedAt": "2026-12-01T15:13:07.554237Z" }, "schema": { "$ref": "#/components/schemas/ChangeRequest" @@ -25969,21 +27938,21 @@ ], "timeoutHours": 8 }, - "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + "baseSha": "f33469a0b99e67100557d4172703299def66403b", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:01.025136Z", + "createdAt": "2026-12-01T15:13:07.467592Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:01.059924Z", + "at": "2026-12-01T15:13:07.523173Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", "status": "pending_approval" }, { - "at": "2026-11-27T20:59:01.177791Z", + "at": "2026-12-01T15:13:07.689889Z", "by": "amy", "event": "rejected", "note": "Use the medium tier", @@ -26000,16 +27969,16 @@ "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0006/events", - "self": "/api/v1/requests/req-20261127-0006" + "events": "/api/v1/requests/req-20261201-0006/events", + "self": "/api/v1/requests/req-20261201-0006" }, "mergeSha": null, "namespace": "billing-dev", - "planHash": "83fbdd10e46eb59ab7a8469389ca3be081d6248b68e498bd28f9b5553b7d319b", + "planHash": "2dc6e0f17a140f4c9b54f8ba3f3438767816ea38ea0e7288d30ad08d61977635", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0006", + "requestId": "req-20261201-0006", "requester": { "automated": false, "requester": { @@ -26027,7 +27996,7 @@ "submittedByClient": null }, "status": "rejected", - "updatedAt": "2026-11-27T20:59:01.074654Z" + "updatedAt": "2026-12-01T15:13:07.412997Z" }, "schema": { "$ref": "#/components/schemas/ChangeRequest" @@ -26320,70 +28289,70 @@ "slots": [], "timeoutHours": 8 }, - "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + "baseSha": "f33469a0b99e67100557d4172703299def66403b", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:02.774593Z", + "createdAt": "2026-12-01T15:13:11.695133Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:02.805919Z", + "at": "2026-12-01T15:13:11.739486Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", "status": "approved" }, { - "at": "2026-11-27T20:59:02.926517Z", + "at": "2026-12-01T15:13:12.002993Z", "by": "cmapi-bot", "event": "branch_pushed", - "note": "cmapi/CRC/req-20261127-0007 at 479aab8d on a539f2ec (created)", + "note": "cmapi/CRC/req-20261201-0007 at 4afd09a1 on f33469a0 (created)", "status": "approved" }, { - "at": "2026-11-27T20:59:03.034663Z", + "at": "2026-12-01T15:13:12.223049Z", "by": "cmapi-bot", "event": "pr_opened", - "note": "cmapi/CRC/req-20261127-0007 #5", + "note": "cmapi/CRC/req-20261201-0007 #5", "status": "pr_open" }, { - "at": "2026-11-27T20:59:03.202028Z", + "at": "2026-12-01T15:13:12.476559Z", "by": "ci", "event": "ci", "note": "kubeconform: pass; kyverno: pass; cmapi check: fail", "status": "pr_open" }, { - "at": "2026-11-27T20:59:03.221341Z", + "at": "2026-12-01T15:13:12.503772Z", "by": "ci", "event": "head_moved", - "note": "PR head moved from 479aab8d to 9df23668 after approval", + "note": "PR head moved from 4afd09a1 to 00ee2444 after approval", "status": "pr_open" }, { - "at": "2026-11-27T20:59:03.235587Z", + "at": "2026-12-01T15:13:12.524707Z", "by": "ci", "event": "pr_failed", "note": "checks failed", "status": "failed" }, { - "at": "2026-11-27T20:59:03.235646Z", + "at": "2026-12-01T15:13:12.524778Z", "by": "worker", "event": "pr_closed", "note": "#5: its checks failed; the request is failed and may be retried", "status": "failed" }, { - "at": "2026-11-27T20:59:03.337967Z", + "at": "2026-12-01T15:13:12.722929Z", "by": "worker", "event": "branch_deleted", - "note": "cmapi/CRC/req-20261127-0007 at 9df23668", + "note": "cmapi/CRC/req-20261201-0007 at 00ee2444", "status": "failed" }, { - "at": "2026-11-27T20:59:04.480562Z", + "at": "2026-12-01T15:13:15.355831Z", "by": "opal", "event": "retry", "note": "retry requested", @@ -26400,22 +28369,22 @@ "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0007/events", + "events": "/api/v1/requests/req-20261201-0007/events", "pr": "https://git.test/pulls/5", - "self": "/api/v1/requests/req-20261127-0007" + "self": "/api/v1/requests/req-20261201-0007" }, "mergeSha": null, "namespace": "search-dev", - "planHash": "2cbf58b2fd56a364d34143e4ad6349cd2aeda2faa6214d9720de95dce8966f81", + "planHash": "9e54f6892405d065608268e425a03e3a4ffcbf02c1d0465424fc7f3a06a65833", "plugin": "namespaces", "pr": { - "branch": "cmapi/CRC/req-20261127-0007", - "head": "479aab8d", + "branch": "cmapi/CRC/req-20261201-0007", + "head": "4afd09a1", "number": 5, "url": "https://git.test/pulls/5" }, "reason": null, - "requestId": "req-20261127-0007", + "requestId": "req-20261201-0007", "requester": { "automated": false, "requester": { @@ -26433,7 +28402,7 @@ "submittedByClient": null }, "status": "approved", - "updatedAt": "2026-11-27T20:59:04.382387Z" + "updatedAt": "2026-12-01T15:13:15.083613Z" }, "schema": { "$ref": "#/components/schemas/ChangeRequest" @@ -26722,63 +28691,63 @@ "slots": [], "timeoutHours": 8 }, - "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + "baseSha": "f33469a0b99e67100557d4172703299def66403b", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:08.498578Z", + "createdAt": "2026-12-01T15:13:24.659107Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:08.528720Z", + "at": "2026-12-01T15:13:24.709971Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", "status": "approved" }, { - "at": "2026-11-27T20:59:08.615802Z", + "at": "2026-12-01T15:13:24.888974Z", "by": "cmapi-bot", "event": "branch_pushed", - "note": "cmapi/CRC/req-20261127-0009 at f4851764 on a539f2ec (created)", + "note": "cmapi/CRC/req-20261201-0009 at 8dde0960 on f33469a0 (created)", "status": "approved" }, { - "at": "2026-11-27T20:59:08.662018Z", + "at": "2026-12-01T15:13:24.957534Z", "by": "cmapi-bot", "event": "pr_opened", - "note": "cmapi/CRC/req-20261127-0009 #8", + "note": "cmapi/CRC/req-20261201-0009 #8", "status": "pr_open" }, { - "at": "2026-11-27T20:59:08.703276Z", + "at": "2026-12-01T15:13:25.016675Z", "by": "ci", "event": "ci", "note": "kubeconform: pass; kyverno: pass; cmapi check: pass", "status": "pr_open" }, { - "at": "2026-11-27T20:59:08.743034Z", + "at": "2026-12-01T15:13:25.072457Z", "by": "worker", "event": "merge_verified", - "note": "merged f4851764; the folder at it is the plan's", + "note": "merged 8dde0960; the folder at it is the plan's", "status": "pr_open" }, { - "at": "2026-11-27T20:59:08.753863Z", + "at": "2026-12-01T15:13:25.089654Z", "by": "cmapi-bot", "event": "merged", - "note": "merged f4851764", + "note": "merged 8dde0960", "status": "merged" }, { - "at": "2026-11-27T20:59:08.804072Z", + "at": "2026-12-01T15:13:25.173437Z", "by": "worker", "event": "sync_timeout", "note": "orders-dev exists on the cluster and cmapi does not manage it; nothing applied", "status": "sync_failed" }, { - "at": "2026-11-27T20:59:08.972422Z", + "at": "2026-12-01T15:13:25.438291Z", "by": "opal", "event": "revert_requested", "note": "", @@ -26795,22 +28764,22 @@ "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0009/events", + "events": "/api/v1/requests/req-20261201-0009/events", "pr": "https://git.test/pulls/8", - "self": "/api/v1/requests/req-20261127-0009" + "self": "/api/v1/requests/req-20261201-0009" }, - "mergeSha": "f4851764", + "mergeSha": "8dde0960", "namespace": "orders-dev", - "planHash": "2b55cc5cb3a1687f1a10e7038a5ce91dfb672e864e45f9479f2a4ca2b85ddcdc", + "planHash": "4b5e5a0bd420f5925cbcfcc96fecca8e8fc2c4ccd0a7f579ffa057a49b37af02", "plugin": "namespaces", "pr": { - "branch": "cmapi/CRC/req-20261127-0009", - "head": "f4851764", + "branch": "cmapi/CRC/req-20261201-0009", + "head": "8dde0960", "number": 8, "url": "https://git.test/pulls/8" }, "reason": null, - "requestId": "req-20261127-0009", + "requestId": "req-20261201-0009", "requester": { "automated": false, "requester": { @@ -26828,7 +28797,7 @@ "submittedByClient": null }, "status": "sync_failed", - "updatedAt": "2026-11-27T20:59:08.871988Z" + "updatedAt": "2026-12-01T15:13:25.162107Z" }, "schema": { "$ref": "#/components/schemas/ChangeRequest" @@ -27521,6 +29490,11 @@ "name": "namespaces", "x-plugin-version": "0.2.0" }, + { + "description": "Operations: runs of a template of steps (tiers-rerender, rebuild-verify, reconcile, cluster-onboard) that report each step's progress, retry a step that fails, and open ordinary requests, approved as any request is, for every change they make.", + "name": "operations", + "x-plugin-version": "0.2.0" + }, { "description": "What the Kyverno bundle decided on each cluster, read from its policy reports, and the requests that cmapi refused before Git, with Kyverno's warnings on plans that went on.", "name": "policies", @@ -27575,7 +29549,8 @@ { "name": "Operations", "tags": [ - "core" + "core", + "operations" ] }, { diff --git a/docs/02-technical-design-v2.md b/docs/02-technical-design-v2.md index 58c69509..43de6f63 100644 --- a/docs/02-technical-design-v2.md +++ b/docs/02-technical-design-v2.md @@ -157,7 +157,7 @@ Reads return the live object now; writes return a ChangeRequest at once (202) an | environment-forbidden | 403 | A role grants the permission, but only in other environments (environments in authz-roles.yaml) | | forbidden | 403 | No Keycloak role the caller holds grants the route's permission | | idp-unavailable | 503 | Keycloak signing keys unreachable and no cached key matches; Retry-After set | -| operations-engine-unavailable | 503 | The configured operations engine (Argo Workflows or Tekton) is unreachable; the request path is unaffected | +| operations-engine-unavailable | 503 | The configured operations engine (Argo Workflows or Tekton) is unreachable; the request path is unaffected. Built (#26): this build has no Argo Workflows or Tekton adapter, so an instance whose integrations.yaml names one answers it to every `POST /api/v1/operations`, and the reads still answer | | cluster-not-writable | 422 | The cluster is imported but has no clusters.yaml policy entry yet; reads work | | plugin-disabled | 422 | plugins.yaml disables the plugin in the cluster's environment on this instance; the body carries plugin and environment, and reads work | | environment-not-served | 422 | The environment is not in this instance's allowedEnvironments; the body carries instanceUrl and portalUrl of the instance that serves it | @@ -736,7 +736,7 @@ Both hub identities retain the import-reader grant. Its `get` permits reading on Each instance imports only its own clusters. The baseline writes a cluster's Secret to the hub of the instance whose allowedEnvironments include that cluster's environment. Built: a clusters.yaml entry whose environment the instance does not serve stops the start (`load_policies`, `core/registry.py`). Import Secrets do not declare an environment; the environment comes from clusters.yaml. There is no cluster status `environment-not-served`: configuration outside the served environments is rejected before imports are checked. An imported cluster with no clusters.yaml entry can connect and is read-only. **Connection comes from the import; policy comes from the configuration.** The import Secret carries only connection fields: apiUrl, token, caData, tlsServerName and insecure. The cluster's entry in clusters.yaml carries only policy fields: clusterTokens, environment, gitopsPath, writes, delivery, labels, simulatedCapacity, and syncSignal, thanosUrl, metadata and placement, which no built code reads (docs/18, "`clusters.yaml` and `capacity.yaml`"). On CRC and kind, clusters.yaml is in the ConfigMap `cmapi-config` (`deploy/manifests/environments/crc/20-config.yaml`), not in the cluster-configs repository. Because the two sources hold different fields, neither can override the other. -An imported cluster with no clusters.yaml entry is read-only: reads work, and writes return 422 cluster-not-writable (`ClusterRegistry.writable`). The same refusal comes from `writes: false`. Not built: the cluster-onboard operation that adds the entry through a PR (no built code runs an operation engine, docs/18, `integrations.yaml`), and the read of the Thanos URL from the thanos-querier Route. Capacity comes from the watch of each cluster and from `simulatedCapacity` (docs/18, `capacity.yaml`). Today an operator adds the entry to clusters.yaml and the pods start again (docs/13, "A second cluster: kind"). +An imported cluster with no clusters.yaml entry is read-only: reads work, and writes return 422 cluster-not-writable (`ClusterRegistry.writable`). The same refusal comes from `writes: false`. Not built: the step of the cluster-onboard operation that adds the entry through a PR (propose-registry, #761; the operation itself is built, #26, and stops there for a cluster that clusters.yaml does not name), and the read of the Thanos URL from the thanos-querier Route. Capacity comes from the watch of each cluster and from `simulatedCapacity` (docs/18, `capacity.yaml`). Today an operator adds the entry to clusters.yaml and the pods start again (docs/13, "A second cluster: kind"). **Cluster metadata.** *Built on main: only `labels`. cmapi reads `labels` from the entry (`ClusterPolicy.labels`), shows them in `GET /api/v1/clusters`, and matches `match.clusterSelector.matchLabels` of an auto-approval policy against them (`core/approvals.py`). `metadata` and `placement` are read and not used. Not built: the validation below, the zone check against the nodes, `matchExpressions`, the `labelSelector` query of `GET /api/v1/clusters`, and the region and zone in metrics and in capacity snapshots.* Each clusters.yaml entry can classify its cluster with a region, its availability zones, a few standard fields and free-form labels. cmapi turns these into a label set per cluster. Selectors over that set let approval rules, auto-approval, placement, integrations and operations pick clusters by what they are instead of listing IDs. @@ -820,7 +820,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 (**not built**: `examples/config/operations/cluster-onboard.yaml` is an example and no code runs it; today steps 1 and 3 are 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'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.* 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. @@ -1389,7 +1389,7 @@ The Kyverno bundle is rendered from the same catalog (#212, "Policy in one place | GET /api/v1/tiers?environment= | Every offered tier per environment the instance serves (or one), resolved, with hash, plus the custom bounds and the sizable keys. ETag: the catalog hash | Any authenticated caller (namespaces:read) | | GET /api/v1/tiers/{tier}?environment= | One resolved tier | Same | | GET /api/v1/tiers/{tier}/namespaces?environment=&state=current\|outdated&limit=&cursor= | Namespaces on that tier with their rendered and current hash, on the shared paging contract | Scoped like GET /api/v1/quotas | -| POST /api/v1/operations with template tiers-rerender | An operation that re-renders outdated namespaces | operations:run (cmapi-operator) | +| POST /api/v1/operations with template tiers-rerender | An operation that re-renders outdated namespaces. Built (#26) | operations:run (cmapi-operator) | Writes keep their shape: POST .../namespaces takes tier and, for custom only, quota and limitRange; PATCH .../namespaces/{ns} with {"tier": "large"} changes tier, and on a custom namespace it merges quota and limitRange over the values in Git; PATCH or PUT .../quota takes the sizable keys only. Refusals are 422 policy-violation with errors\[\].code: tier-unknown, tier-not-offered, quota-with-named-tier (quota sent with small, medium or large), quota-key-not-sizable (a quota key that is not sizable and not overridable), custom-quota-required (a sizable key missing), custom-out-of-bounds (each offending key with its min, max and step), limits-with-named-tier, limit-key-not-overridable, limit-order-invalid and limit-exceeds-quota. @@ -1408,7 +1408,7 @@ Writes keep their shape: POST .../namespaces takes tier and, for custom only, qu "step": {"requests.cpu": "1", "requests.memory": "1Gi", "pods": "10"}}}}} ``` -**Changing a tier.** A PR to tiers.yaml (approver-platform in CODEOWNERS) changes no namespace by itself; after the rollout, namespaces whose cmapi.net/tier-hash differs show as tier-outdated. An operator then runs the tiers-rerender operation with tier, environments, an optional clusterSelector, batchSize (default 20) and maxOpenPerCluster (default 5). It opens one ordinary update request per outdated namespace: the plan diff shows old and new values, increases go through the capacity check and reserve the delta, a decrease below current use is skipped and listed in the operation report, and the approval rules apply as for any quota change. Namespaces on custom keep their sizable values and their approved beyond-tier values; only the rest of their catalog part re-renders. Any other change of a tier-outdated namespace, a change of a label for example, renders its tier again too, and is sized the same way: every plan takes the old values from the quota that Git holds, never from the catalog, so the capacity delta, quotaIncreasePct and networkExposure count what the catalog added since (#710; the record is docs/reviews/2026-11-26-issue-710/README.md). +**Changing a tier.** A PR to tiers.yaml (approver-platform in CODEOWNERS) changes no namespace by itself; after the rollout, namespaces whose cmapi.net/tier-hash differs show as tier-outdated. An operator then runs the tiers-rerender operation with tier, environments, an optional clusterSelector, batchSize (default 20) and maxOpenPerCluster (default 5). It opens one ordinary update request per outdated namespace: the plan diff shows old and new values, increases go through the capacity check and reserve the delta, a decrease below current use is skipped and listed in the operation report, and the approval rules apply as for any quota change. Namespaces on custom keep their sizable values and their approved beyond-tier values; only the rest of their catalog part re-renders. Any other change of a tier-outdated namespace, a change of a label for example, renders its tier again too, and is sized the same way: every plan takes the old values from the quota that Git holds, never from the catalog, so the capacity delta, quotaIncreasePct and networkExposure count what the catalog added since (#710; the record is docs/reviews/2026-11-26-issue-710/README.md). *Built (#26): the tiers-rerender template (`cmapi/src/cmapi/ops/templates/tiers-rerender.yaml`) selects the outdated namespaces from the watch cache that `GET /api/v1/quotas` reads, and opens each request as a PATCH that sends no change; batchSize caps the run's requests open at once and maxOpenPerCluster those on one cluster. A namespace already current in Git is skipped, and one whose new quota is below what its pods request now (the live quota's `status.used`) is skipped and listed. The record: docs/reviews/2026-12-01-issue-26-operations/design.md.* **Reference implementation.** cmapi/src/cmapi/core/tiers.py, with tests in cmapi/tests/core/test_tiers.py and cmapi/tests/core/test_limitrange_split.py that load every instance's file, cover refusals and catalog checks, and render the example namespace's resourcequota-payments-dev-quota.yaml, limitrange-payments-dev-limits-cpu.yaml and limitrange-payments-dev-limits-memory.yaml byte for byte. @@ -2162,7 +2162,7 @@ cmapi/ │ ├── capacity.yaml # snapshot interval, targets, overcommit │ ├── placement.yaml # score weights, freshness limits, reservation TTL │ ├── integrations.yaml # sync signal, operations engine, event publisher, approval channels, notifier -│ ├── operations/ # templates: cluster-onboard, rebuild-verify, adoption-sweep, tiers-rerender, ... +│ ├── operations/ # templates: cluster-onboard, rebuild-verify, adoption-sweep, tiers-rerender, ... (built, #26: they ship in src/cmapi/ops/templates/) │ ├── policy-bundle.yaml # tag of the Kyverno bundle in cluster-configs/policies │ └── adoption.yaml # mounted from the cmapi-adoption ConfigMap ├── src/cmapi/ @@ -2193,13 +2193,13 @@ cmapi/ │ │ ├── notify.py # Notifier: email, Teams, Slack │ │ ├── events.py # EventPublisher and the outbox │ │ ├── sync.py # SyncSignal: poll, Argo CD Notifications webhook -│ │ ├── operations.py # OperationsEngine: builtin, Argo Workflows, Tekton +│ │ ├── operations.py # OperationsEngine: builtin (built, #26), Argo Workflows, Tekton │ │ ├── kpi/ # system metrics: one definition for /metrics and /admin/kpi │ │ ├── db/ # SQLAlchemy models, repositories, Alembic migrations │ │ └── observability.py # metrics, structlog, OpenTelemetry │ ├── routers/ # core routes: requests, operations, admin, me │ ├── jobs/ # worker jobs, one module each -│ ├── ops/ # operation step library; runs in the worker or as the cmapi-ops image +│ ├── ops/ # operation step library and its templates; runs in the worker (#26) or as the cmapi-ops image │ ├── capacity/ # cmapi-capacity service (own entrypoint) │ └── plugins/ │ ├── namespaces/ metadata/ quotas/ tiers/ expiration/ @@ -2269,7 +2269,7 @@ Every module cmapi needs for the features agreed so far: approval-first lifecycl | core/notify.py | Email (default), Teams, Slack; notices go to the team DL | Notifier | SMTP or webhooks | 2 | Protocol | | core/events.py | Outbox and EventPublisher (none, signed webhook, Kafka) | EventPublisher | db | Backlog | Protocol | | core/sync.py | poll (default) or Argo CD Notifications webhook, always confirmed by a read | SyncSignal | argocd client | 2 | Protocol | -| core/operations.py | builtin engine, Argo Workflows, Tekton | OperationsEngine | ops/ | 5 | Protocol | +| core/operations.py | builtin engine, Argo Workflows, Tekton | OperationsEngine | ops/ | 5 | Built: the builtin engine (#26); Argo Workflows and Tekton not built | | core/kpi/ | One definition per system metric for /metrics and GET /api/v1/admin/kpi | KPI registry | cgroup, db | 1 | Specified | | core/db/ | SQLAlchemy models, repositories, Alembic migrations (expand and contract) | tables in Data model | PostgreSQL | 1 | Specified | @@ -2278,7 +2278,7 @@ Every module cmapi needs for the features agreed so far: approval-first lifecycl | Module | Endpoints | Uses | Phase | Status | | --- | --- | --- | --- | --- | | routers/requests.py | GET /requests (status=, approver=me, paged), GET /requests/{id}, /events; :approve, :reject, :cancel, :retry, :revert | lifecycle, approvals ledger, authz, listquery | 2 | Specified | -| routers/operations.py | POST, GET /operations, :cancel | OperationsEngine | 5 | Specified | +| routers/operations.py | POST, GET /operations, GET /operations/{id}, :cancel | OperationsEngine | 5 | Built (#26) | | routers/admin.py | GET /admin/kpi, POST /admin/reload, /admin/auto-approval:pause and :resume | kpi, config | 1, 2 | Specified | | routers/me.py | GET /me: identity, roles, permissions and their environments | authz, identity | 1 | Specified | | plugins/namespaces | POST, GET, PATCH, DELETE …/namespaces\[/{ns}\] | tiers, metadata, identity checks, expiration rules, render, approvals | 2 | Specified (its logic is reference code) | @@ -2390,10 +2390,10 @@ Built in PR #288 (#286 PR-A); not merged, not deployed | reservation\_expiry | Every minute | Ends placement reservations past their TTL | 3 | | policy\_report\_sweep | Every 5 minutes | cmapi\_policy\_results and the Policies tab cache | 5 | | token\_renew | Every minute | Renew bounded baseline imports at the configured point in the issued lifetime | 1 | -| reconcile | After a restore, or on demand | Rebuilds open requests from bot PRs; auto-approval starts paused | 5 | +| reconcile | After a restore, or on demand | Rebuilds open requests from bot PRs; auto-approval starts paused | 5. Built (#26) as the reconcile operation: it pauses auto-approval and lists the bot branches and PRs whose requests the database lacks; the rebuild is not built (#762) | | kpi\_export | Monthly | KPI rows for the 30-day KPIs | 5 | | outbox\_publish | Continuous, when an EventPublisher is on | Drains the outbox | Backlog | -| operations | POST /operations | tiers-rerender, adoption-sweep, cluster-onboard, rebuild-verify, bulk-migrate through OperationsEngine | 5 | +| operations | POST /operations | tiers-rerender, adoption-sweep, cluster-onboard, rebuild-verify, bulk-migrate through OperationsEngine | 5. Built (#26): the job `operation_step` runs one step of the built-in engine; tiers-rerender, rebuild-verify, reconcile and cluster-onboard. adoption-sweep and bulk-migrate are not built | ### cmapi-capacity (capacity/) @@ -2608,7 +2608,7 @@ events: syncSignal: notify # this cluster has Argo CD Notifications configured ``` -**One step library, any engine.** An operation template is data in config/operations/. Its steps are Python functions in cmapi.ops, shipped both in the worker image and as the cmapi-ops container. The built-in engine calls the functions in-process. The Argo adapter renders the same template into a Workflow with one cmapi-ops container per step, and the Tekton adapter renders a PipelineRun. A template changes in one place and behaves the same on every engine. +**One step library, any engine.** *Built (#26): the built-in engine, its step library and four templates (tiers-rerender, rebuild-verify, reconcile, cluster-onboard), and the Operations API; the Argo Workflows and Tekton adapters are not. The decisions the design left open, with their sources, are in docs/reviews/2026-12-01-issue-26-operations/design.md: the step's identity (delegation, D3), the retry semantics (Argo's retryStrategy, D4), surviving a dead worker (D5), cancel (D6), how a waiting step ends with its request (D7), and what is not built (D12).* An operation template is data in config/operations/. Its steps are Python functions in cmapi.ops, shipped both in the worker image and as the cmapi-ops container. The built-in engine calls the functions in-process. The Argo adapter renders the same template into a Workflow with one cmapi-ops container per step, and the Tekton adapter renders a PipelineRun. A template changes in one place and behaves the same on every engine. ```yaml # config/operations/cluster-onboard.yaml @@ -2653,7 +2653,7 @@ class OperationsEngine(Protocol): def watch(self) -> AsyncIterator[RunStatus]: ... # phase changes for cmapi's runs ``` -**Built-in engine.** Each step is a job of kind operation\_step in the existing jobs table, and its state lives in operation\_steps, so a worker restart resumes where it stopped. Retries follow the template's retry block. A fan-out step gets one row per item, capped per cluster. Without Argo you lose its UI, the workflow archive and pod-level isolation; reports go into the operations row as JSON instead of S3. Cluster bootstrap is the baseline's job, so no step needs cluster-admin. +**Built-in engine.** *Built (#26): `cmapi/src/cmapi/core/operations.py`, migration `0013`; operation_steps also has `cluster_id`, `inputs` and the row's times, and operations is docs/07's table with the changes 0013's docstring lists.* Each step is a job of kind operation\_step in the existing jobs table, and its state lives in operation\_steps, so a worker restart resumes where it stopped. Retries follow the template's retry block. A fan-out step gets one row per item, capped per cluster. Without Argo you lose its UI, the workflow archive and pod-level isolation; reports go into the operations row as JSON instead of S3. Cluster bootstrap is the baseline's job, so no step needs cluster-admin. ```sql CREATE TABLE operation_steps ( @@ -2668,7 +2668,7 @@ CREATE TABLE operation_steps ( ); ``` -**Operations API, the same on every engine.** POST /api/v1/operations starts a template; GET /api/v1/operations/{id} is the status of record; POST /api/v1/operations/{id}:cancel stops it. Starting one needs operations:run, held by cmapi-operator and cmapi-admin. Four rules apply whichever engine runs the steps: +**Operations API, the same on every engine.** POST /api/v1/operations starts a template; GET /api/v1/operations/{id} is the status of record; POST /api/v1/operations/{id}:cancel stops it. Starting one needs operations:run, held by cmapi-operator and cmapi-admin. *Built (#26): each of the four routes, and GET /api/v1/operations, needs operations:run where the run acts (design.md, D9); a start needs an Idempotency-Key.* Four rules apply whichever engine runs the steps: - Steps change managed objects only by calling cmapi. The only exception is read-only checks. - Runs start only through cmapi, which records an operations row and labels Argo or Tekton runs cmapi.net/operation-id. diff --git a/docs/04-api-examples.md b/docs/04-api-examples.md index ef002910..29c64dca 100644 --- a/docs/04-api-examples.md +++ b/docs/04-api-examples.md @@ -187,7 +187,7 @@ The answer was 202 (`application/json`): ], "timeoutHours": 8 }, - "baseSha": "ca16e8cc000b1d1f2305f2259948a58c6035e62a", + "baseSha": "e33ccf390a5fc196bb270e81c03752e59a2385f7", "beyondTier": { "approvals": [ { @@ -205,11 +205,11 @@ The answer was 202 (`application/json`): ] }, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:16.210356Z", + "createdAt": "2026-12-01T15:13:36.361990Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:16.232805Z", + "at": "2026-12-01T15:13:36.396117Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 3)]", @@ -225,16 +225,16 @@ The answer was 202 (`application/json`): "instance": "nonprod", "justification": "Bring abc-rnd under cmapi", "links": { - "events": "/api/v1/requests/req-20261127-0016/events", - "self": "/api/v1/requests/req-20261127-0016" + "events": "/api/v1/requests/req-20261201-0016/events", + "self": "/api/v1/requests/req-20261201-0016" }, "mergeSha": null, "namespace": "abc-rnd", - "planHash": "7630777637466bdb231a248db34b6e67aafe718082ab15403db130f4b28b73ee", + "planHash": "49c73db929d9a990a0acdf6bd9c262076939964693858d51f17c7de254db4939", "plugin": "adoption", "pr": null, "reason": null, - "requestId": "req-20261127-0016", + "requestId": "req-20261201-0016", "requester": { "automated": false, "requester": { @@ -252,7 +252,7 @@ The answer was 202 (`application/json`): "submittedByClient": null }, "status": "pending_approval", - "updatedAt": "2026-11-27T20:59:16.134586Z" + "updatedAt": "2026-12-01T15:13:36.123405Z" } ``` @@ -443,11 +443,11 @@ The answer was 200 (`application/json`): ], "app": null, "clusterId": "CRC", - "created": "2026-11-27", + "created": "2026-12-01", "daysLeft": 21, "env": "dev", - "expiresAt": "2026-12-18", - "graceEnds": "2026-12-25", + "expiresAt": "2026-12-22", + "graceEnds": "2026-12-29", "lifetimeDays": 21, "name": "notes-dev", "noticesSent": 0, @@ -479,7 +479,7 @@ The answer was 200 (`application/json`): ] } }, - "today": "2026-11-27" + "today": "2026-12-01" } ``` @@ -513,7 +513,7 @@ The answer was 200 (`application/json`): "annotations": { "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", "cmapi.net/instance": "nonprod", - "cmapi.net/request-id": "req-20261127-0001", + "cmapi.net/request-id": "req-20261201-0001", "cmapi.net/requested-by": "ola@ephico2real.com", "cmapi.net/team-dl": "payments-team@ephico2real.com" }, @@ -616,11 +616,11 @@ The answer was 202 (`application/json`): "baseSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:54.441022Z", + "createdAt": "2026-12-01T15:12:55.670320Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:54.488801Z", + "at": "2026-12-01T15:12:55.724895Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", @@ -637,16 +637,16 @@ The answer was 202 (`application/json`): "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0001/events", - "self": "/api/v1/requests/req-20261127-0001" + "events": "/api/v1/requests/req-20261201-0001/events", + "self": "/api/v1/requests/req-20261201-0001" }, "mergeSha": null, "namespace": "payments-dev", - "planHash": "9fed510537c2c36b3dc18a5b461ebfac4c2f1b7dfc2a61a394afd47b96624c09", + "planHash": "4e9af3fc1f212f0387b6958adccca82242cc53b7fd67192be64529da18a31563", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0001", + "requestId": "req-20261201-0001", "requester": { "automated": false, "requester": { @@ -664,7 +664,7 @@ The answer was 202 (`application/json`): "submittedByClient": null }, "status": "approved", - "updatedAt": "2026-11-27T20:58:54.385979Z" + "updatedAt": "2026-12-01T15:12:55.450056Z" } ``` @@ -864,14 +864,14 @@ The answer was 202 (`application/json`): ], "timeoutHours": 8 }, - "baseSha": "479aab8dca85cfbd40e9c4c4b791535b8a69d428", + "baseSha": "4afd09a1a70bbf2c03d8d2253e817b57a5812c0a", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:05.959028Z", + "createdAt": "2026-12-01T15:13:18.496644Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:05.969036Z", + "at": "2026-12-01T15:13:18.510655Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", @@ -888,8 +888,8 @@ The answer was 202 (`application/json`): "instance": "nonprod", "justification": null, "links": { - "events": "/api/v1/requests/req-20261127-0008/events", - "self": "/api/v1/requests/req-20261127-0008" + "events": "/api/v1/requests/req-20261201-0008/events", + "self": "/api/v1/requests/req-20261201-0008" }, "mergeSha": null, "namespace": "search-dev", @@ -897,7 +897,7 @@ The answer was 202 (`application/json`): "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0008", + "requestId": "req-20261201-0008", "requester": { "automated": false, "requester": { @@ -915,7 +915,7 @@ The answer was 202 (`application/json`): "submittedByClient": null }, "status": "pending_approval", - "updatedAt": "2026-11-27T20:59:05.871308Z" + "updatedAt": "2026-12-01T15:13:18.239084Z" } ``` @@ -964,7 +964,7 @@ The answer was 200 (`application/json`): "clusters/CRC/namespaces/search-dev/resourcequota-search-dev-quota.yaml": "removed", "clusters/CRC/namespaces/search-dev/token-issuer-rolebinding.yaml": "removed" }, - "etag": "2482d135c8aae7da", + "etag": "ca777167c63ddb5e", "files": {}, "findings": [], "metadata": null, @@ -1002,26 +1002,26 @@ curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces The run sent `GET /api/v1/clusters/CRC/namespaces/payments-dev`. -The answer was 200 (`application/json`, `etag: "d71165fa38f59dd4"`): +The answer was 200 (`application/json`, `etag: "1b59766bf9a3bbe7"`): ```json { "annotations": { "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", "cmapi.net/instance": "nonprod", - "cmapi.net/request-id": "req-20261127-0001", + "cmapi.net/request-id": "req-20261201-0001", "cmapi.net/requested-by": "ola@ephico2real.com", "cmapi.net/team-dl": "payments-team@ephico2real.com" }, "clusterId": "CRC", "env": "dev", - "etag": "d71165fa38f59dd4", + "etag": "1b59766bf9a3bbe7", "expiresAt": null, "git": { "annotations": { "argocd.argoproj.io/sync-options": "Prune=confirm,ServerSideApply=true", "cmapi.net/instance": "nonprod", - "cmapi.net/request-id": "req-20261127-0001", + "cmapi.net/request-id": "req-20261201-0001", "cmapi.net/requested-by": "ola@ephico2real.com", "cmapi.net/team-dl": "payments-team@ephico2real.com" }, @@ -1193,14 +1193,14 @@ The answer was 202 (`application/json`): ], "timeoutHours": 8 }, - "baseSha": "80f4f1badad17a36a1e6c5d25834f76fef11435b", + "baseSha": "513f40b0ee251859ba80791976ccc3addcfdf1ba", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:55.923726Z", + "createdAt": "2026-12-01T15:12:57.455807Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:56.005112Z", + "at": "2026-12-01T15:12:57.536560Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", @@ -1217,16 +1217,16 @@ The answer was 202 (`application/json`): "instance": "nonprod", "justification": "Load test next sprint", "links": { - "events": "/api/v1/requests/req-20261127-0002/events", - "self": "/api/v1/requests/req-20261127-0002" + "events": "/api/v1/requests/req-20261201-0002/events", + "self": "/api/v1/requests/req-20261201-0002" }, "mergeSha": null, "namespace": "payments-dev", - "planHash": "df5602a2038007a6de28e19adf060fd6b5f8fb3d5b86637f790b31efdc510039", + "planHash": "7aebcbffedf4cef6b095bd7594ab08df7c4f3964ede6f8138b15048c990b9ed3", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0002", + "requestId": "req-20261201-0002", "requester": { "automated": false, "requester": { @@ -1244,7 +1244,7 @@ The answer was 202 (`application/json`): "submittedByClient": null }, "status": "pending_approval", - "updatedAt": "2026-11-27T20:58:55.904486Z" + "updatedAt": "2026-12-01T15:12:57.263260Z" } ``` @@ -1303,7 +1303,7 @@ The answer was 200 (`application/json`): "clusters/CRC/namespaces/payments-dev/namespace.yaml": "changed", "clusters/CRC/namespaces/payments-dev/resourcequota-payments-dev-quota.yaml": "changed" }, - "etag": "d71165fa38f59dd4", + "etag": "1b59766bf9a3bbe7", "files": { "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-cpu.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-cpu\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: medium\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 44fd85f2d7cb\nspec:\n limits:\n - type: Container\n defaultRequest:\n cpu: 100m\n default:\n cpu: 500m\n max:\n cpu: '4'\n", "clusters/CRC/namespaces/payments-dev/limitrange-payments-dev-limits-memory.yaml": "apiVersion: v1\nkind: LimitRange\nmetadata:\n name: payments-dev-limits-memory\n namespace: payments-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/managed: 'true'\n cmapi.net/tier: medium\n annotations:\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/tier-hash: 44fd85f2d7cb\nspec:\n limits:\n - type: Container\n defaultRequest:\n memory: 256Mi\n default:\n memory: 512Mi\n max:\n memory: 8Gi\n", @@ -1328,7 +1328,7 @@ The answer was 200 (`application/json`): } } }, - "planHash": "13472056b96785ab1172af6108e4ab3bda9d07c0663fd117bcb98fe6d7c3c4d8", + "planHash": "3409c7cab6683ab5c6280d06452d63623f90b3231e915bb31b5b4efee19b9adc", "requester": { "automated": false, "requester": { @@ -1414,14 +1414,14 @@ The answer was 202 (`application/json`): "slots": [], "timeoutHours": 8 }, - "baseSha": "3e8ad5005d0b72c1869d34e49299f12f1b03b5b5", + "baseSha": "fff48c23f20c46278e17f5d0f1143fbe488baf9f", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:59.299718Z", + "createdAt": "2026-12-01T15:13:04.324648Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:59.374768Z", + "at": "2026-12-01T15:13:04.427407Z", "by": "ola", "event": "plan_auto_approved", "note": "none-required", @@ -1438,16 +1438,16 @@ The answer was 202 (`application/json`): "instance": "nonprod", "justification": "Another sprint", "links": { - "events": "/api/v1/requests/req-20261127-0004/events", - "self": "/api/v1/requests/req-20261127-0004" + "events": "/api/v1/requests/req-20261201-0004/events", + "self": "/api/v1/requests/req-20261201-0004" }, "mergeSha": null, "namespace": "sprint-dev", - "planHash": "fd55be2f5fa99dbc2d1abb18df09cb134f778a075ba88a80375fd4004efd3024", + "planHash": "94647a196d1eadd68a6e7f32e52ece621b84b432d66fe07079e993d28f81f1a4", "plugin": "namespaces", "pr": null, "reason": "expiration:extend", - "requestId": "req-20261127-0004", + "requestId": "req-20261201-0004", "requester": { "automated": false, "requester": { @@ -1465,7 +1465,7 @@ The answer was 202 (`application/json`): "submittedByClient": null }, "status": "approved", - "updatedAt": "2026-11-27T20:58:59.274371Z" + "updatedAt": "2026-12-01T15:13:04.155474Z" } ``` @@ -1512,9 +1512,9 @@ The answer was 200 (`application/json`): "changes": { "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed" }, - "etag": "073bd8faea2248ce", + "etag": "917c7a62361f9e08", "files": { - "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: sprint-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2026-12-31'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" + "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: sprint-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2027-01-04'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" }, "findings": [], "metadata": null, @@ -1522,7 +1522,7 @@ The answer was 200 (`application/json`): "annotations": {}, "labels": {} }, - "planHash": "45af0b7fd4a2f76619cf99f889c9d19edb65d059722e4e459866be1859ec697b", + "planHash": "1f9cb50d801c839f9d81f17c0bdfa248ec47c1aa58de25faff503e675da9a4f6", "requester": { "automated": false, "requester": { @@ -1590,14 +1590,14 @@ The answer was 202 (`application/json`): ], "timeoutHours": 8 }, - "baseSha": "ac1e81f58836d7f8a36ae1cdff67fe152c02fd02", + "baseSha": "feb3ec3f7d9810aff0adcce6cd4aa4a92b85fefd", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:12.604388Z", + "createdAt": "2026-12-01T15:13:30.640365Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:12.676330Z", + "at": "2026-12-01T15:13:30.783091Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", @@ -1614,16 +1614,16 @@ The answer was 202 (`application/json`): "instance": "nonprod", "justification": "In production use", "links": { - "events": "/api/v1/requests/req-20261127-0013/events", - "self": "/api/v1/requests/req-20261127-0013" + "events": "/api/v1/requests/req-20261201-0013/events", + "self": "/api/v1/requests/req-20261201-0013" }, "mergeSha": null, "namespace": "sprint-dev", - "planHash": "b2e28a66559008829930431df326dc1a91864514d67474024f7fae04298cdfd0", + "planHash": "7e351d77c635272d0628a10556f6e2a86b180aac067848e44417651013b36b00", "plugin": "namespaces", "pr": null, "reason": "expiration:makePermanent", - "requestId": "req-20261127-0013", + "requestId": "req-20261201-0013", "requester": { "automated": false, "requester": { @@ -1641,7 +1641,7 @@ The answer was 202 (`application/json`): "submittedByClient": null }, "status": "pending_approval", - "updatedAt": "2026-11-27T20:59:12.577772Z" + "updatedAt": "2026-12-01T15:13:30.497696Z" } ``` @@ -1701,7 +1701,7 @@ The answer was 200 (`application/json`): "changes": { "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "changed" }, - "etag": "073bd8faea2248ce", + "etag": "917c7a62361f9e08", "files": { "clusters/CRC/namespaces/sprint-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: sprint-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" }, @@ -1711,7 +1711,7 @@ The answer was 200 (`application/json`): "annotations": {}, "labels": {} }, - "planHash": "4e2f1ef26fab90b27dc41e0fd496b8e8006b2742bc192f09a8dea81ffefb031b", + "planHash": "70bbacf492d9d66211a7592e0a14a89dcac6317e2376b7674bc0ee2f01e6b85f", "requester": { "automated": false, "requester": { @@ -1741,7 +1741,7 @@ The answer was 200 (`application/json`): Permission: `namespaces:write`. ```bash -curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev/expiration:set -H "Authorization: Bearer $TOKEN" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'If-Match: "3f9a1c0b7e2d4a68"' -H 'Content-Type: application/json' -d '{"justification": "A load test this sprint", "until": "2026-12-18"}' +curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/clusters/CRC/namespaces/payments-dev/expiration:set -H "Authorization: Bearer $TOKEN" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'If-Match: "3f9a1c0b7e2d4a68"' -H 'Content-Type: application/json' -d '{"justification": "A load test this sprint", "until": "2026-12-22"}' ``` The run sent `POST /api/v1/clusters/CRC/namespaces/notes-dev/expiration:set` with this body: @@ -1749,7 +1749,7 @@ The run sent `POST /api/v1/clusters/CRC/namespaces/notes-dev/expiration:set` wit ```json { "justification": "A load test this sprint", - "until": "2026-12-18" + "until": "2026-12-22" } ``` @@ -1771,14 +1771,14 @@ The answer was 202 (`application/json`): "slots": [], "timeoutHours": 8 }, - "baseSha": "2b2f51e093acbd69fb6b2fb05c5acbef76ecb749", + "baseSha": "efebfc8bb689241a62f847984e2721f3262dc61f", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:11.598086Z", + "createdAt": "2026-12-01T15:13:28.971548Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:11.671849Z", + "at": "2026-12-01T15:13:29.129136Z", "by": "ola", "event": "plan_auto_approved", "note": "none-required", @@ -1795,16 +1795,16 @@ The answer was 202 (`application/json`): "instance": "nonprod", "justification": "A load test this sprint", "links": { - "events": "/api/v1/requests/req-20261127-0012/events", - "self": "/api/v1/requests/req-20261127-0012" + "events": "/api/v1/requests/req-20261201-0012/events", + "self": "/api/v1/requests/req-20261201-0012" }, "mergeSha": null, "namespace": "notes-dev", - "planHash": "9b232cebe5e7f6c7322d8707f3ec6242b41b2249fb7589b4e77ef7413540258c", + "planHash": "e03939885c418d98170f15ddf95c7ff62ccfa9557329000845f1b4171c55cc30", "plugin": "namespaces", "pr": null, "reason": "expiration:set", - "requestId": "req-20261127-0012", + "requestId": "req-20261201-0012", "requester": { "automated": false, "requester": { @@ -1822,7 +1822,7 @@ The answer was 202 (`application/json`): "submittedByClient": null }, "status": "approved", - "updatedAt": "2026-11-27T20:59:11.573014Z" + "updatedAt": "2026-12-01T15:13:28.855961Z" } ``` @@ -1831,7 +1831,7 @@ The run sent `POST /api/v1/clusters/CRC/namespaces/notes-dev/expiration:set?dryR ```json { "justification": "A load test this sprint", - "until": "2026-12-18" + "until": "2026-12-22" } ``` @@ -1870,9 +1870,9 @@ The answer was 200 (`application/json`): "changes": { "clusters/CRC/namespaces/notes-dev/namespace.yaml": "changed" }, - "etag": "2763b4eb2ce407b5", + "etag": "fc99df943d89d3a5", "files": { - "clusters/CRC/namespaces/notes-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: notes-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2026-12-18'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" + "clusters/CRC/namespaces/notes-dev/namespace.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: notes-dev\n labels:\n cmapi.net/cluster-id: CRC\n cmapi.net/env: dev\n cmapi.net/expiry: managed\n cmapi.net/managed: 'true'\n cmapi.net/requested-by-user: ola\n cmapi.net/tier: small\n cmapi.net/cost-center: cc-4410\n cmapi.net/team: payments\n annotations:\n argocd.argoproj.io/sync-options: Prune=confirm,ServerSideApply=true\n cmapi.net/expires-at: '2026-12-22'\n cmapi.net/instance: nonprod\n cmapi.net/request-id: (planned)\n cmapi.net/requested-by: ola@ephico2real.com\n cmapi.net/team-dl: payments-team@ephico2real.com\n" }, "findings": [], "metadata": null, @@ -1880,7 +1880,7 @@ The answer was 200 (`application/json`): "annotations": {}, "labels": {} }, - "planHash": "38d5d19ff384c206da94f3e9d1844ceeb7e15bedcd639467c71f7677117614a3", + "planHash": "9c1158dfa0d79c5c9f0c241dec6a32d5b2a292a37433713da86353035f89f39e", "requester": { "automated": false, "requester": { @@ -1919,7 +1919,7 @@ The answer was 200 (`application/json`): ```json { - "from": "2026-11-20T20:59:12.816211Z", + "from": "2026-11-24T15:13:31.152927Z", "items": [ { "action": "create", @@ -1938,9 +1938,9 @@ The answer was 200 (`application/json`): "source": "cmapi" } ], - "firstAt": "2026-11-27T20:59:09.886777Z", + "firstAt": "2026-12-01T15:13:26.735685Z", "id": "rej-2", - "lastAt": "2026-11-27T20:59:09.886777Z", + "lastAt": "2026-12-01T15:13:26.735685Z", "namespace": "kube-tools", "outcome": "refused", "plugin": "namespaces", @@ -1987,7 +1987,7 @@ The answer was 200 (`application/json`): { "clusters": [ { - "asOf": "2026-11-27T20:59:12.694710Z", + "asOf": "2026-12-01T15:13:30.959859Z", "bundle": { "actionsDiffer": [], "actionsDifferTotal": 0, @@ -2165,13 +2165,13 @@ curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/capacity -H "Authorizat The run sent `GET /api/v1/capacity`. -The answer was 200 (`application/json`, `etag: "1966474983b788a05effcc14deb90586"`): +The answer was 200 (`application/json`, `etag: "b71217a3b2368e40b964c0a3511fdad3"`): ```json { "clusters": [ { - "asOf": "2026-11-27T20:59:00Z", + "asOf": "2026-12-01T15:13:00Z", "basis": "simulated", "boundBy": "cpu", "clusterId": "CRC", @@ -2339,11 +2339,11 @@ The answer was 201 (`application/json`): ```json { - "asOf": "2026-11-27T20:59:13Z", + "asOf": "2026-12-01T15:13:31Z", "clusterId": "CRC", "excluded": [], - "expiresAt": "2026-11-27T21:14:13.469598Z", - "placementId": "pl-20261127-7658a163", + "expiresAt": "2026-12-01T15:28:31.965297Z", + "placementId": "pl-20261201-52bb3c04", "ranked": [ { "basis": "simulated", @@ -2372,7 +2372,7 @@ The answer was 201 (`application/json`): }, "reserved": true, "score": 29, - "snapshotAt": "2026-11-27T20:30:00Z" + "snapshotAt": "2026-12-01T15:00:00Z" } ], "request": { @@ -2408,7 +2408,7 @@ The answer was 200 (`application/json`): ```json { - "asOf": "2026-11-27T20:59:13Z", + "asOf": "2026-12-01T15:13:31Z", "clusterId": null, "excluded": [], "expiresAt": null, @@ -2441,7 +2441,7 @@ The answer was 200 (`application/json`): }, "reserved": false, "score": 39, - "snapshotAt": "2026-11-27T20:30:00Z" + "snapshotAt": "2026-12-01T15:00:00Z" } ], "request": { @@ -2519,7 +2519,7 @@ The answer was 200 (`application/json`): "detail": null, "source": "api", "state": "ok", - "takenAt": "2026-11-27T20:30:00Z" + "takenAt": "2026-12-01T15:00:00Z" }, "staleAfterSeconds": 3600 } @@ -2813,14 +2813,14 @@ The answer was 200 (`application/json`): ], "timeoutHours": 8 }, - "baseSha": "80f4f1badad17a36a1e6c5d25834f76fef11435b", + "baseSha": "513f40b0ee251859ba80791976ccc3addcfdf1ba", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:55.923726Z", + "createdAt": "2026-12-01T15:12:57.455807Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:56.005112Z", + "at": "2026-12-01T15:12:57.536560Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", @@ -2837,16 +2837,16 @@ The answer was 200 (`application/json`): "instance": "nonprod", "justification": "Load test next sprint", "links": { - "events": "/api/v1/requests/req-20261127-0002/events", - "self": "/api/v1/requests/req-20261127-0002" + "events": "/api/v1/requests/req-20261201-0002/events", + "self": "/api/v1/requests/req-20261201-0002" }, "mergeSha": null, "namespace": "payments-dev", - "planHash": "df5602a2038007a6de28e19adf060fd6b5f8fb3d5b86637f790b31efdc510039", + "planHash": "7aebcbffedf4cef6b095bd7594ab08df7c4f3964ede6f8138b15048c990b9ed3", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0002", + "requestId": "req-20261201-0002", "requester": { "automated": false, "requester": { @@ -2864,7 +2864,7 @@ The answer was 200 (`application/json`): "submittedByClient": null }, "status": "pending_approval", - "updatedAt": "2026-11-27T20:58:55.904486Z" + "updatedAt": "2026-12-01T15:12:57.263260Z" } ], "letters": { @@ -2893,7 +2893,7 @@ Permission: `requests:read`. curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/requests/req-20261105-0001 -H "Authorization: Bearer $TOKEN" ``` -The run sent `GET /api/v1/requests/req-20261127-0001`. +The run sent `GET /api/v1/requests/req-20261201-0001`. The answer was 200 (`application/json`): @@ -2916,11 +2916,11 @@ The answer was 200 (`application/json`): "baseSha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:54.441022Z", + "createdAt": "2026-12-01T15:12:55.670320Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:54.488801Z", + "at": "2026-12-01T15:12:55.724895Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", @@ -2937,22 +2937,22 @@ The answer was 200 (`application/json`): "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0001/events", + "events": "/api/v1/requests/req-20261201-0001/events", "pr": "https://git.test/pulls/1", - "self": "/api/v1/requests/req-20261127-0001" + "self": "/api/v1/requests/req-20261201-0001" }, - "mergeSha": "80f4f1ba", + "mergeSha": "513f40b0", "namespace": "payments-dev", - "planHash": "9fed510537c2c36b3dc18a5b461ebfac4c2f1b7dfc2a61a394afd47b96624c09", + "planHash": "4e9af3fc1f212f0387b6958adccca82242cc53b7fd67192be64529da18a31563", "plugin": "namespaces", "pr": { - "branch": "cmapi/CRC/req-20261127-0001", - "head": "80f4f1ba", + "branch": "cmapi/CRC/req-20261201-0001", + "head": "513f40b0", "number": 1, "url": "https://git.test/pulls/1" }, "reason": null, - "requestId": "req-20261127-0001", + "requestId": "req-20261201-0001", "requester": { "automated": false, "requester": { @@ -2970,7 +2970,7 @@ The answer was 200 (`application/json`): "submittedByClient": null }, "status": "synced", - "updatedAt": "2026-11-27T20:58:54.780441Z" + "updatedAt": "2026-12-01T15:12:55.949790Z" } ``` @@ -2987,15 +2987,15 @@ Permission: `requests:read`. curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/requests/req-20261105-0001/approval-status -H "Authorization: Bearer $TOKEN" ``` -The run sent `GET /api/v1/requests/req-20261127-0001/approval-status`. +The run sent `GET /api/v1/requests/req-20261201-0001/approval-status`. The answer was 200 (`application/json`): ```json { "approved": true, - "planHash": "9fed510537c2c36b3dc18a5b461ebfac4c2f1b7dfc2a61a394afd47b96624c09", - "requestId": "req-20261127-0001", + "planHash": "4e9af3fc1f212f0387b6958adccca82242cc53b7fd67192be64529da18a31563", + "requestId": "req-20261201-0001", "status": "synced" } ``` @@ -3010,7 +3010,7 @@ Permission: `requests:read`. curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/requests/req-20261105-0001/events -H "Authorization: Bearer $TOKEN" ``` -The run sent `GET /api/v1/requests/req-20261127-0001/events`. +The run sent `GET /api/v1/requests/req-20261201-0001/events`. The answer was 200 (`application/json`): @@ -3018,14 +3018,14 @@ The answer was 200 (`application/json`): { "events": [ { - "at": "2026-11-27T20:58:54.488801Z", + "at": "2026-12-01T15:12:55.724895Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", "status": "approved" } ], - "requestId": "req-20261127-0001", + "requestId": "req-20261201-0001", "status": "synced" } ``` @@ -3042,7 +3042,7 @@ Permission: `requests:approve`. curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/requests/req-20261105-0001:approve -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -d '{"comment": "sizing reviewed"}' ``` -The run sent `POST /api/v1/requests/req-20261127-0002:approve` with this body: +The run sent `POST /api/v1/requests/req-20261201-0002:approve` with this body: ```json { @@ -3058,7 +3058,7 @@ The answer was 200 (`application/json`): "approval": { "approvals": [ { - "at": "2026-11-27T20:58:56.181147Z", + "at": "2026-12-01T15:12:57.737114Z", "comment": "sizing reviewed", "relayedBy": null, "sub": "sub-amy", @@ -3082,14 +3082,14 @@ The answer was 200 (`application/json`): ], "timeoutHours": 8 }, - "baseSha": "80f4f1badad17a36a1e6c5d25834f76fef11435b", + "baseSha": "513f40b0ee251859ba80791976ccc3addcfdf1ba", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:58:55.923726Z", + "createdAt": "2026-12-01T15:12:57.455807Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:58:56.005112Z", + "at": "2026-12-01T15:12:57.536560Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", @@ -3106,16 +3106,16 @@ The answer was 200 (`application/json`): "instance": "nonprod", "justification": "Load test next sprint", "links": { - "events": "/api/v1/requests/req-20261127-0002/events", - "self": "/api/v1/requests/req-20261127-0002" + "events": "/api/v1/requests/req-20261201-0002/events", + "self": "/api/v1/requests/req-20261201-0002" }, "mergeSha": null, "namespace": "payments-dev", - "planHash": "df5602a2038007a6de28e19adf060fd6b5f8fb3d5b86637f790b31efdc510039", + "planHash": "7aebcbffedf4cef6b095bd7594ab08df7c4f3964ede6f8138b15048c990b9ed3", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0002", + "requestId": "req-20261201-0002", "requester": { "automated": false, "requester": { @@ -3133,7 +3133,7 @@ The answer was 200 (`application/json`): "submittedByClient": null }, "status": "approved", - "updatedAt": "2026-11-27T20:58:56.128756Z" + "updatedAt": "2026-12-01T15:12:57.519349Z" } ``` @@ -3150,7 +3150,7 @@ Permission: `requests:cancel`. curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/requests/req-20261105-0001:cancel -H "Authorization: Bearer $TOKEN" ``` -The run sent `POST /api/v1/requests/req-20261127-0005:cancel`. +The run sent `POST /api/v1/requests/req-20261201-0005:cancel`. The answer was 200 (`application/json`): @@ -3181,14 +3181,14 @@ The answer was 200 (`application/json`): ], "timeoutHours": 8 }, - "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + "baseSha": "f33469a0b99e67100557d4172703299def66403b", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:00.839033Z", + "createdAt": "2026-12-01T15:13:07.269501Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:00.869605Z", + "at": "2026-12-01T15:13:07.303276Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", @@ -3205,16 +3205,16 @@ The answer was 200 (`application/json`): "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0005/events", - "self": "/api/v1/requests/req-20261127-0005" + "events": "/api/v1/requests/req-20261201-0005/events", + "self": "/api/v1/requests/req-20261201-0005" }, "mergeSha": null, "namespace": "ledger-dev", - "planHash": "872bc285608555d97234f8f6f440473a920a3da01e2e5509a176628b51d35ac3", + "planHash": "ce7e669a03e55261cb76f1ec4054133e9985c1ab51a26c1edf7bfb18ea4bf918", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0005", + "requestId": "req-20261201-0005", "requester": { "automated": false, "requester": { @@ -3232,7 +3232,7 @@ The answer was 200 (`application/json`): "submittedByClient": null }, "status": "cancelled", - "updatedAt": "2026-11-27T20:59:01.183312Z" + "updatedAt": "2026-12-01T15:13:07.554237Z" } ``` @@ -3248,7 +3248,7 @@ Permission: `requests:reject`. curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/requests/req-20261105-0001:reject -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -d '{"comment": "Use the medium tier"}' ``` -The run sent `POST /api/v1/requests/req-20261127-0006:reject` with this body: +The run sent `POST /api/v1/requests/req-20261201-0006:reject` with this body: ```json { @@ -3285,14 +3285,14 @@ The answer was 200 (`application/json`): ], "timeoutHours": 8 }, - "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + "baseSha": "f33469a0b99e67100557d4172703299def66403b", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:01.025136Z", + "createdAt": "2026-12-01T15:13:07.467592Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:01.059924Z", + "at": "2026-12-01T15:13:07.523173Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", @@ -3309,16 +3309,16 @@ The answer was 200 (`application/json`): "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0006/events", - "self": "/api/v1/requests/req-20261127-0006" + "events": "/api/v1/requests/req-20261201-0006/events", + "self": "/api/v1/requests/req-20261201-0006" }, "mergeSha": null, "namespace": "billing-dev", - "planHash": "83fbdd10e46eb59ab7a8469389ca3be081d6248b68e498bd28f9b5553b7d319b", + "planHash": "2dc6e0f17a140f4c9b54f8ba3f3438767816ea38ea0e7288d30ad08d61977635", "plugin": "namespaces", "pr": null, "reason": null, - "requestId": "req-20261127-0006", + "requestId": "req-20261201-0006", "requester": { "automated": false, "requester": { @@ -3336,7 +3336,7 @@ The answer was 200 (`application/json`): "submittedByClient": null }, "status": "rejected", - "updatedAt": "2026-11-27T20:59:01.074654Z" + "updatedAt": "2026-12-01T15:13:07.412997Z" } ``` @@ -3352,7 +3352,7 @@ Permission: `requests:retry`. curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/requests/req-20261105-0001:retry -H "Authorization: Bearer $TOKEN" ``` -The run sent `POST /api/v1/requests/req-20261127-0007:retry`. +The run sent `POST /api/v1/requests/req-20261201-0007:retry`. The answer was 200 (`application/json`): @@ -3372,14 +3372,14 @@ The answer was 200 (`application/json`): "slots": [], "timeoutHours": 8 }, - "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + "baseSha": "f33469a0b99e67100557d4172703299def66403b", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:02.774593Z", + "createdAt": "2026-12-01T15:13:11.695133Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:02.805919Z", + "at": "2026-12-01T15:13:11.739486Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", @@ -3396,22 +3396,22 @@ The answer was 200 (`application/json`): "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0007/events", + "events": "/api/v1/requests/req-20261201-0007/events", "pr": "https://git.test/pulls/5", - "self": "/api/v1/requests/req-20261127-0007" + "self": "/api/v1/requests/req-20261201-0007" }, "mergeSha": null, "namespace": "search-dev", - "planHash": "2cbf58b2fd56a364d34143e4ad6349cd2aeda2faa6214d9720de95dce8966f81", + "planHash": "9e54f6892405d065608268e425a03e3a4ffcbf02c1d0465424fc7f3a06a65833", "plugin": "namespaces", "pr": { - "branch": "cmapi/CRC/req-20261127-0007", - "head": "479aab8d", + "branch": "cmapi/CRC/req-20261201-0007", + "head": "4afd09a1", "number": 5, "url": "https://git.test/pulls/5" }, "reason": null, - "requestId": "req-20261127-0007", + "requestId": "req-20261201-0007", "requester": { "automated": false, "requester": { @@ -3429,7 +3429,7 @@ The answer was 200 (`application/json`): "submittedByClient": null }, "status": "approved", - "updatedAt": "2026-11-27T20:59:04.382387Z" + "updatedAt": "2026-12-01T15:13:15.083613Z" } ``` @@ -3446,7 +3446,7 @@ Permission: `requests:retry`. curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/requests/req-20261105-0001:revert -H "Authorization: Bearer $TOKEN" ``` -The run sent `POST /api/v1/requests/req-20261127-0009:revert`. +The run sent `POST /api/v1/requests/req-20261201-0009:revert`. The answer was 200 (`application/json`): @@ -3466,14 +3466,14 @@ The answer was 200 (`application/json`): "slots": [], "timeoutHours": 8 }, - "baseSha": "a539f2ec28817c4438aff7fc406387f84840178e", + "baseSha": "f33469a0b99e67100557d4172703299def66403b", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:08.498578Z", + "createdAt": "2026-12-01T15:13:24.659107Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:08.528720Z", + "at": "2026-12-01T15:13:24.709971Z", "by": "ola", "event": "plan_auto_approved", "note": "auto:baseline-rnd-namespace", @@ -3490,22 +3490,22 @@ The answer was 200 (`application/json`): "instance": "nonprod", "justification": "Payments service dev namespace", "links": { - "events": "/api/v1/requests/req-20261127-0009/events", + "events": "/api/v1/requests/req-20261201-0009/events", "pr": "https://git.test/pulls/8", - "self": "/api/v1/requests/req-20261127-0009" + "self": "/api/v1/requests/req-20261201-0009" }, - "mergeSha": "f4851764", + "mergeSha": "8dde0960", "namespace": "orders-dev", - "planHash": "2b55cc5cb3a1687f1a10e7038a5ce91dfb672e864e45f9479f2a4ca2b85ddcdc", + "planHash": "4b5e5a0bd420f5925cbcfcc96fecca8e8fc2c4ccd0a7f579ffa057a49b37af02", "plugin": "namespaces", "pr": { - "branch": "cmapi/CRC/req-20261127-0009", - "head": "f4851764", + "branch": "cmapi/CRC/req-20261201-0009", + "head": "8dde0960", "number": 8, "url": "https://git.test/pulls/8" }, "reason": null, - "requestId": "req-20261127-0009", + "requestId": "req-20261201-0009", "requester": { "automated": false, "requester": { @@ -3523,7 +3523,7 @@ The answer was 200 (`application/json`): "submittedByClient": null }, "status": "sync_failed", - "updatedAt": "2026-11-27T20:59:08.871988Z" + "updatedAt": "2026-12-01T15:13:25.162107Z" } ``` @@ -3552,7 +3552,7 @@ The answer was 200 (`application/json`): { "items": [ { - "checkedAt": "2026-11-27T20:58:53.069187Z", + "checkedAt": "2026-12-01T15:12:54.018046Z", "clusterId": "CRC", "environment": "dev", "findingDetails": [], @@ -3561,11 +3561,11 @@ The answer was 200 (`application/json`): "labels": { "region": "us-central" }, - "lastProbeAt": "2026-11-27T20:58:53.069187Z", + "lastProbeAt": "2026-12-01T15:12:54.018046Z", "secretName": "cmapi-cluster-crc", "serverVersion": "v1.35.6-fake", "status": "connected", - "statusSince": "2026-11-27T20:58:53.069187Z", + "statusSince": "2026-12-01T15:12:54.018046Z", "tokenExpiresAt": null, "trust": { "downgrade": false, @@ -3594,7 +3594,7 @@ The answer was 200 (`application/json`): ```json { - "checkedAt": "2026-11-27T20:58:53.587291Z", + "checkedAt": "2026-12-01T15:12:54.578527Z", "clusterId": "CRC", "environment": "dev", "findingDetails": [], @@ -3603,11 +3603,11 @@ The answer was 200 (`application/json`): "labels": { "region": "us-central" }, - "lastProbeAt": "2026-11-27T20:58:53.587291Z", + "lastProbeAt": "2026-12-01T15:12:54.578527Z", "secretName": "cmapi-cluster-crc", "serverVersion": "v1.35.6-fake", "status": "connected", - "statusSince": "2026-11-27T20:58:53.069187Z", + "statusSince": "2026-12-01T15:12:54.018046Z", "tokenExpiresAt": null, "trust": { "downgrade": false, @@ -3963,6 +3963,293 @@ The answer was 200 (`application/json`): } ``` +Operations: runs of a template of steps (tiers-rerender, rebuild-verify, reconcile, cluster-onboard) that report each step's progress, retry a step that fails, and open ordinary requests, approved as any request is, for every change they make. + +### List operations + +`GET /api/v1/operations` + +Permission: `operations:run`. + +```bash +curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/operations -H "Authorization: Bearer $TOKEN" +``` + +The run sent `GET /api/v1/operations?template=tiers-rerender`. + +The answer was 200 (`application/json`): + +```json +{ + "items": [ + { + "cancelRequestedAt": null, + "cancelRequestedBy": null, + "engine": "builtin", + "environments": [ + "dev" + ], + "finishedAt": null, + "links": { + "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + "self": "/api/v1/operations/op-20261201-7fead487" + }, + "operationId": "op-20261201-7fead487", + "parameters": { + "batchSize": 20, + "environments": [ + "dev" + ], + "maxOpenPerCluster": 5, + "tier": "small" + }, + "phase": "Running", + "progress": { + "finished": 0, + "phases": { + "Running": 1 + }, + "total": 1 + }, + "runName": "op-20261201-7fead487", + "startedAt": "2026-12-01T15:13:36.696696Z", + "startedBy": "opal", + "template": "tiers-rerender" + } + ], + "letters": { + "T": 1 + }, + "page": { + "from": 1, + "limit": 50, + "nextCursor": null, + "prevCursor": null, + "to": 1, + "total": 1 + } +} +``` + +### Start an operation + +`POST /api/v1/operations` + +Permission: `operations:run`. + +```bash +curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/operations -H "Authorization: Bearer $TOKEN" -H 'Idempotency-Key: 0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10' -H 'Content-Type: application/json' -d '{"parameters": {"environments": ["dev"], "tier": "small"}, "template": "tiers-rerender"}' +``` + +The run sent `POST /api/v1/operations` with this body: + +```json +{ + "parameters": { + "environments": [ + "dev" + ], + "tier": "small" + }, + "template": "tiers-rerender" +} +``` + +The answer was 202 (`application/json`): + +```json +{ + "cancelRequestedAt": null, + "cancelRequestedBy": null, + "engine": "builtin", + "environments": [ + "dev" + ], + "finishedAt": null, + "links": { + "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + "self": "/api/v1/operations/op-20261201-7fead487" + }, + "operationId": "op-20261201-7fead487", + "parameters": { + "batchSize": 20, + "environments": [ + "dev" + ], + "maxOpenPerCluster": 5, + "tier": "small" + }, + "phase": "Running", + "progress": { + "finished": 0, + "phases": { + "Running": 1 + }, + "total": 1 + }, + "report": null, + "runName": "op-20261201-7fead487", + "startedAt": "2026-12-01T15:13:36.696696Z", + "startedBy": "opal", + "steps": [ + { + "attempts": 0, + "clusterId": "", + "finishedAt": null, + "item": "", + "lastError": null, + "outputs": null, + "phase": "Running", + "startedAt": "2026-12-01T15:13:36.480026Z", + "step": "select-outdated" + } + ], + "template": "tiers-rerender" +} +``` + +### Get an operation + +`GET /api/v1/operations/{operation_id}` + +Permission: `operations:run`. + +```bash +curl -X GET https://cmapi-nonprod.ephico2real.com/api/v1/operations/op-20261201-3f9a1c2e -H "Authorization: Bearer $TOKEN" +``` + +The run sent `GET /api/v1/operations/op-20261201-7fead487`. + +The answer was 200 (`application/json`): + +```json +{ + "cancelRequestedAt": "2026-12-01T15:13:36.705960Z", + "cancelRequestedBy": "opal", + "engine": "builtin", + "environments": [ + "dev" + ], + "finishedAt": "2026-12-01T15:13:36.995319Z", + "links": { + "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + "self": "/api/v1/operations/op-20261201-7fead487" + }, + "operationId": "op-20261201-7fead487", + "parameters": { + "batchSize": 20, + "environments": [ + "dev" + ], + "maxOpenPerCluster": 5, + "tier": "small" + }, + "phase": "Stopped", + "progress": { + "finished": 1, + "phases": { + "Stopped": 1 + }, + "total": 1 + }, + "report": { + "steps": [ + { + "items": [], + "phases": { + "Stopped": 1 + }, + "step": "select-outdated" + } + ] + }, + "runName": "op-20261201-7fead487", + "startedAt": "2026-12-01T15:13:36.696696Z", + "startedBy": "opal", + "steps": [ + { + "attempts": 0, + "clusterId": "", + "finishedAt": "2026-12-01T15:13:36.968745Z", + "item": "", + "lastError": null, + "outputs": { + "note": "stopped by opal" + }, + "phase": "Stopped", + "startedAt": "2026-12-01T15:13:36.480026Z", + "step": "select-outdated" + } + ], + "template": "tiers-rerender" +} +``` + +### Cancel an operation + +`POST /api/v1/operations/{operation_id}:cancel` + +Permission: `operations:run`. + +```bash +curl -X POST https://cmapi-nonprod.ephico2real.com/api/v1/operations/op-20261201-3f9a1c2e:cancel -H "Authorization: Bearer $TOKEN" +``` + +The run sent `POST /api/v1/operations/op-20261201-7fead487:cancel`. + +The answer was 200 (`application/json`): + +```json +{ + "cancelRequestedAt": "2026-12-01T15:13:36.705960Z", + "cancelRequestedBy": "opal", + "engine": "builtin", + "environments": [ + "dev" + ], + "finishedAt": null, + "links": { + "cancel": "/api/v1/operations/op-20261201-7fead487:cancel", + "self": "/api/v1/operations/op-20261201-7fead487" + }, + "operationId": "op-20261201-7fead487", + "parameters": { + "batchSize": 20, + "environments": [ + "dev" + ], + "maxOpenPerCluster": 5, + "tier": "small" + }, + "phase": "Running", + "progress": { + "finished": 0, + "phases": { + "Running": 1 + }, + "total": 1 + }, + "report": null, + "runName": "op-20261201-7fead487", + "startedAt": "2026-12-01T15:13:36.696696Z", + "startedBy": "opal", + "steps": [ + { + "attempts": 0, + "clusterId": "", + "finishedAt": null, + "item": "", + "lastError": null, + "outputs": null, + "phase": "Running", + "startedAt": "2026-12-01T15:13:36.480026Z", + "step": "select-outdated" + } + ], + "template": "tiers-rerender" +} +``` + ## Admin What an operator of the instance uses: the auto-approval switch, the prune confirmation, the integration modes, the plugins, the Git log and the system KPIs. @@ -4014,7 +4301,7 @@ The answer was 200 (`application/json`): { "paused": true, "reason": "incident 1234", - "setAt": "2026-11-27T20:59:01.388335+00:00", + "setAt": "2026-12-01T15:13:07.995528+00:00", "setBy": "ada" } ``` @@ -4043,7 +4330,7 @@ The answer was 200 (`application/json`): { "paused": false, "reason": "incident 1234 closed", - "setAt": "2026-11-27T20:59:01.394640+00:00", + "setAt": "2026-12-01T15:13:07.918684+00:00", "setBy": "ada" } ``` @@ -4065,7 +4352,7 @@ The answer was 200 (`application/json`): ```json { "log": [ - "80f4f1ba Merge cmapi/CRC/req-20261127-0001" + "513f40b0 Merge cmapi/CRC/req-20261201-0001" ] } ``` @@ -4141,18 +4428,18 @@ The answer was 200 (`application/json`): "cpuThrottledPeriods": null, "cpuThrottledSeconds": null, "cpuUsageSeconds": null, - "measuredAt": 1795813135.55039, + "measuredAt": 1796137976.883476, "memoryBytes": null, "memoryLimitBytes": null } ], "database": { - "connections": 9, + "connections": 13, "connectionsMax": 100, "oldestTransactionSeconds": 0.0, "poolInUse": 0, "poolSize": 5, - "sizeBytes": 10173463, + "sizeBytes": 9018391, "walBytes": 83886080 }, "instance": "nonprod", @@ -4164,7 +4451,7 @@ The answer was 200 (`application/json`): "target": "under 10 min", "targetStatus": "proposed", "unit": "seconds", - "value": 0.332343 + "value": 0.27096 } ], "thresholds": { @@ -4211,7 +4498,7 @@ The answer was 200 (`application/json`): } ``` -`body.items` has 11 items in the run. The first is shown. +`body.items` has 12 items in the run. The first is shown. ### Confirm the prune of a deleted namespace @@ -4240,7 +4527,7 @@ The answer was 200 (`application/json`): "approval": { "approvals": [ { - "at": "2026-11-27T20:59:06.043703Z", + "at": "2026-12-01T15:13:18.601698Z", "comment": "", "relayedBy": null, "sub": "sub-amy", @@ -4264,14 +4551,14 @@ The answer was 200 (`application/json`): ], "timeoutHours": 8 }, - "baseSha": "479aab8dca85cfbd40e9c4c4b791535b8a69d428", + "baseSha": "4afd09a1a70bbf2c03d8d2253e817b57a5812c0a", "beyondTier": null, "clusterId": "CRC", - "createdAt": "2026-11-27T20:59:05.959028Z", + "createdAt": "2026-12-01T15:13:18.496644Z", "env": "dev", "events": [ { - "at": "2026-11-27T20:59:05.969036Z", + "at": "2026-12-01T15:13:18.510655Z", "by": "ola", "event": "plan_needs_approval", "note": "waiting for [('approver-platform', 1)]", @@ -4288,22 +4575,22 @@ The answer was 200 (`application/json`): "instance": "nonprod", "justification": null, "links": { - "events": "/api/v1/requests/req-20261127-0008/events", + "events": "/api/v1/requests/req-20261201-0008/events", "pr": "https://git.test/pulls/7", - "self": "/api/v1/requests/req-20261127-0008" + "self": "/api/v1/requests/req-20261201-0008" }, - "mergeSha": "a539f2ec", + "mergeSha": "f33469a0", "namespace": "search-dev", "planHash": "c490196334dad591c3196aa59224d119861392145360aee1d428c93109235dbe", "plugin": "namespaces", "pr": { - "branch": "cmapi/CRC/req-20261127-0008", - "head": "a539f2ec", + "branch": "cmapi/CRC/req-20261201-0008", + "head": "f33469a0", "number": 7, "url": "https://git.test/pulls/7" }, "reason": null, - "requestId": "req-20261127-0008", + "requestId": "req-20261201-0008", "requester": { "automated": false, "requester": { @@ -4321,7 +4608,7 @@ The answer was 200 (`application/json`): "submittedByClient": null }, "status": "awaiting_prune", - "updatedAt": "2026-11-27T20:59:07.078985Z" + "updatedAt": "2026-12-01T15:13:20.605642Z" } ``` @@ -4358,8 +4645,8 @@ Each refusal is an RFC 9457 problem with the media type `application/problem+jso ```json { "code": "change-pending", - "detail": "req-20261127-0015 holds audit-dev", - "requestId": "req-20261127-0015", + "detail": "req-20261201-0015 holds audit-dev", + "requestId": "req-20261201-0015", "status": 409, "title": "change pending", "type": "https://cmapi.ephico2real.com/problems/change-pending" @@ -4444,7 +4731,7 @@ Each refusal is an RFC 9457 problem with the media type `application/problem+jso { "code": "idempotency-replay", "detail": "Idempotency-Key was used for a different request", - "requestId": "req-20261127-0015", + "requestId": "req-20261201-0015", "status": 409, "title": "idempotency replay", "type": "https://cmapi.ephico2real.com/problems/idempotency-replay" @@ -4467,7 +4754,7 @@ Each refusal is an RFC 9457 problem with the media type `application/problem+jso ### 409 `invalid-transition` -`POST /api/v1/requests/req-20261127-0007:revert`: +`POST /api/v1/requests/req-20261201-0007:revert`: ```json { @@ -4560,6 +4847,26 @@ Each refusal is an RFC 9457 problem with the media type `application/problem+jso } ``` +### 422 `operation-template-unknown` + +`POST /api/v1/operations`, with a body: + +```json +{ + "code": "operation-template-unknown", + "detail": "No operation template 'tier-rerender'; this build has ['cluster-onboard', 'rebuild-verify', 'reconcile', 'tiers-rerender']", + "status": 422, + "templates": [ + "cluster-onboard", + "rebuild-verify", + "reconcile", + "tiers-rerender" + ], + "title": "operation template unknown", + "type": "https://cmapi.ephico2real.com/problems/operation-template-unknown" +} +``` + ### 422 `placement-mismatch` `POST /api/v1/clusters/CRC/namespaces?dryRun=true`, with a body: @@ -4567,7 +4874,7 @@ Each refusal is an RFC 9457 problem with the media type `application/problem+jso ```json { "code": "placement-mismatch", - "detail": "Placement pl-20261127-7658a163 was made for another target: the placement's team is 'billing', the create's 'payments'", + "detail": "Placement pl-20261201-52bb3c04 was made for another target: the placement's team is 'billing', the create's 'payments'", "status": 422, "title": "placement mismatch", "type": "https://cmapi.ephico2real.com/problems/placement-mismatch" @@ -4625,7 +4932,7 @@ Each refusal is an RFC 9457 problem with the media type `application/problem+jso { "code": "precondition-failed", "detail": "The namespace changed in Git since you read it", - "etag": "d71165fa38f59dd4", + "etag": "1b59766bf9a3bbe7", "status": 412, "title": "precondition failed", "type": "https://cmapi.ephico2real.com/problems/precondition-failed" @@ -4704,7 +5011,7 @@ Each refusal is an RFC 9457 problem with the media type `application/problem+jso { "code": "precondition-failed", "detail": "If-Match does not list the current ETag of this answer: read it again", - "etag": "13b13a438dedd73906000f898819ba13", + "etag": "26d4367b57e62464bfa3089775962d25", "status": 412, "title": "precondition failed", "type": "https://cmapi.ephico2real.com/problems/precondition-failed" @@ -4897,6 +5204,21 @@ Each refusal is an RFC 9457 problem with the media type `application/problem+jso } ``` +### 409 `invalid-transition` (Cancel an operation) + +`POST /api/v1/operations/op-20261201-7fead487:cancel`: + +```json +{ + "code": "invalid-transition", + "detail": "op-20261201-7fead487 ended Stopped", + "state": "Stopped", + "status": 409, + "title": "invalid transition", + "type": "https://cmapi.ephico2real.com/problems/invalid-transition" +} +``` + ### 400 `invalid-sort` (Export the quota list as CSV) `GET /api/v1/quotas:export?sort=nope`: diff --git a/docs/14-authorization.md b/docs/14-authorization.md index bd860f80..d4e55259 100644 --- a/docs/14-authorization.md +++ b/docs/14-authorization.md @@ -53,7 +53,7 @@ A role is a client role on the client of the instance: `cmapi-nonprod`, `cmapi-s | `requests:retry` | | | | | yes | yes | | | 2 | | `adoption:write` | | | | | yes | yes | | | 0 | | `reports:read` | | | | | yes | yes | | | 2 | -| `operations:run` | | | | | yes | yes | | | 3 | +| `operations:run` | | | | | yes | yes | | | 7 | | `namespaces:protect` | | | | | yes | yes | | | 0 | | `config:write` | | | | | | yes | | | 0 | | `clusters:onboard` | | | | | | yes | | | 0 | @@ -63,7 +63,7 @@ A role is a client role on the client of the instance: `cmapi-nonprod`, `cmapi-s | `audit:export` | | | | | | | yes | | 0 | | `approvals:relay` | | | | | | | | yes | 0 | -`namespaces:protect` is what makes an operator (#366). No route declares it: the routes check it inside, in the environment of the object. It lets a caller set and remove the operator-only labels and annotations of `metadata-keys.yaml` (`cmapi.net/protected` and `do-not-delete`; a requester gets 403), cancel another person's request, and read employee IDs in the directory (`cmapi/src/cmapi/core/authz.py:160-166`, `cmapi/src/cmapi/core/pipeline.py:296`). It is a permission, not a role name: a role of `authz-roles.yaml` that inherits `cmapi-operator` is an operator, and a role that grants it in some environments makes an operator there only. A file that lists `permissions:` for `cmapi-operator` itself must name `namespaces:protect`, or that role is no longer an operator. +`namespaces:protect` is what makes an operator (#366). No route declares it: the routes check it inside, in the environment of the object. It lets a caller set and remove the operator-only labels and annotations of `metadata-keys.yaml` (`cmapi.net/protected` and `do-not-delete`; a requester gets 403), cancel another person's request, and read employee IDs in the directory (`cmapi/src/cmapi/core/authz.py:160-166`, `cmapi/src/cmapi/core/pipeline.py:304`). It is a permission, not a role name: a role of `authz-roles.yaml` that inherits `cmapi-operator` is an operator, and a role that grants it in some environments makes an operator there only. A file that lists `permissions:` for `cmapi-operator` itself must name `namespaces:protect`, or that role is no longer an operator. Each column name has the prefix `cmapi-` in Keycloak. An operator or an admin cannot approve with those roles alone: `requests:approve` is only in `cmapi-approver`. On CRC the group `app-cmapi-rbac-operator` also gives `cmapi-approver`. @@ -81,7 +81,7 @@ Each column name has the prefix `cmapi-` in Keycloak. An operator or an admin ca ### Which route needs which permission -Each route declares one permission. The OpenAPI document shows it as `x-cmapi-permission`, and the description of the route ends with a "Requires" line (`cmapi/src/cmapi/core/docs.py:349-354`). A `HEAD` is answered by the route of its `GET`, so it needs the same permission and gets the same 401 or 403 (#605). +Each route declares one permission. The OpenAPI document shows it as `x-cmapi-permission`, and the description of the route ends with a "Requires" line (`cmapi/src/cmapi/core/docs.py:355-360`). A `HEAD` is answered by the route of its `GET`, so it needs the same permission and gets the same 401 or 403 (#605). | Permission | Routes | |---|---| @@ -97,7 +97,7 @@ Each route declares one permission. The OpenAPI document shows it as `x-cmapi-pe | `requests:reject` | `POST /api/v1/requests/{request_id}:reject` | | `requests:cancel` | `POST /api/v1/requests/{request_id}:cancel` | | `requests:retry` | `POST /api/v1/requests/{request_id}:retry`
`POST /api/v1/requests/{request_id}:revert` | -| `operations:run` | `POST /api/v1/admin/prune:confirm`
`POST /api/v1/clusters/{id}:probe`
`POST /api/v1/clusters/{cluster_id}/capacity/snapshots:run` | +| `operations:run` | `POST /api/v1/admin/prune:confirm`
`POST /api/v1/clusters/{id}:probe`
`POST /api/v1/clusters/{cluster_id}/capacity/snapshots:run`
`POST /api/v1/operations`
`GET /api/v1/operations`
`GET /api/v1/operations/{operation_id}`
`POST /api/v1/operations/{operation_id}:cancel` (each where the run acts; `reconcile` also needs `approvals:pause`, #26) | | `reports:read` | `GET /api/v1/admin/git-log`
`GET /api/v1/admin/kpi` | | `approvals:pause` | `POST /api/v1/admin/auto-approval:pause`
`POST /api/v1/admin/auto-approval:resume` | @@ -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:290`, `:598` | | 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:715` | | 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` | @@ -313,15 +313,15 @@ The users filter of realm `cmapi` is `(uid=cmapi.*)` (`docs/15`, "The LDAP feder ### Tools that act for people -A tool signs in with the client credentials grant. It is a service client, or an account that holds a role in `identity.automationRoles`. The default role is `cmapi-onboarding`, and `cmapi-automation` holds it (`checks.py:1-15`; `docs/15`, "The clients"). The tool is the caller. Three cases follow (`checks.py:70-95`, called from `pipeline.py:288`): +A tool signs in with the client credentials grant. It is a service client, or an account that holds a role in `identity.automationRoles`. The default role is `cmapi-onboarding`, and `cmapi-automation` holds it (`checks.py:1-15`; `docs/15`, "The clients"). The tool is the caller. Three cases follow (`checks.py:70-95`, called from `pipeline.py:296`): | Case | What cmapi does | Source | |---|---|---| -| The tool sends no `onBehalfOf` | The tool is the requester. The request is recorded as automated. If `identity.requireOnBehalfOf` is `true`, the tool must name a person, and without one the answer is 422 `on-behalf-of-required` | `checks.py:83-88`; `problem_docs.py:105` | +| The tool sends no `onBehalfOf` | The tool is the requester. The request is recorded as automated. If `identity.requireOnBehalfOf` is `true`, the tool must name a person, and without one the answer is 422 `on-behalf-of-required` | `checks.py:83-88`; `problem_docs.py:106` | | 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` | +| A person sends `onBehalfOf` | 422 `on-behalf-of-not-allowed` | `checks.py:74-78`; `problem_docs.py:105` | -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:873`, `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. diff --git a/docs/16-data-model.md b/docs/16-data-model.md index e38f12d4..8175c7f1 100644 --- a/docs/16-data-model.md +++ b/docs/16-data-model.md @@ -19,6 +19,8 @@ The database is PostgreSQL through CloudNativePG, or an existing PostgreSQL serv | `expiration_notices` | One expiry notice for a namespace | No code writes it yet. The job `expire_check` is not built | No code reads it yet | | `policy_rejections` | One refusal of cmapi before Git on one UTC day, or Kyverno's warnings on a plan that became a request (#302) | `RejectionRepo.record` (`core/rejections.py`), from the namespace routes, `_submit` and the job `pr_checks`; pruned by the job `rejections_prune` | `GET /api/v1/policies/rejections` | | `capacity_reservations` | The CPU and memory that one open request holds on its cluster until its quota is live (#62; docs/02, Placement, "Reservations") | `POST /api/v1/capacity:place` for a placement's 15-minute hold (#21, `plugins/capacity/placement.py`); `Pipeline.submit` through `SimulatedCapacity.reserve` (`core/capacity_backend.py`), under the cluster's advisory lock; `RequestRepo.move` releases a hold as the request leaves a holding state, takes it again on a `:retry` into one, and moves its expiry on at each step between | The capacity check of every plan, dry run, submit, last approval and `:retry` (`SimulatedCapacity.check`), and placement | +| `operations` | One run of an operation template on the built-in engine: its parameters, its phase, who started it, and its report once it ends (#26, migration `0013`) | `POST /api/v1/operations` (`routers/operations.py`, `start`); the scheduler of the engine (`advance`, `core/operations.py`) moves its phase and writes its report; `:cancel` records who stopped it | `GET /api/v1/operations` and `GET /api/v1/operations/{operation_id}`; the scheduler | +| `operation_steps` | One step of a run, or one item of a fan-out step: its phase, its failed attempts, its outputs (a request it opened) and its last error (#26, `0013`) | The scheduler creates and starts each row (`advance`), and the job `operation_step` records what the step did (`run_step`, `core/operations.py`) | The same, and `GET /api/v1/operations/{operation_id}` | | `capacity_snapshots` | One scope (the cluster, a zone or a node role) of one cluster's capacity at the end of one snapshot interval (#21; docs/02, "Stored capacity") | The worker job `capacity_snapshot` (`jobs/capacity_snapshot.py`, `capacity/snapshots.py`), every capacity.yaml `snapshotInterval`, and on `POST /api/v1/clusters/{clusterId}/capacity/snapshots:run`; it deletes the rows past 13 months | Placement (freshness, zones, the 14-day p95 of use), `GET /api/v1/clusters/{clusterId}/capacity` and `GET /api/v1/capacity` | ## Relations @@ -34,9 +36,15 @@ change_requests (request_id) |-- policy_rejections.request_id many stored findings for one request; a refusal before a request has none |-- capacity_reservations.request_id the holds of one request, one active at a time; a placement's hold has none until a create claims it (#21) +operations (operation_id) + |-- operation_steps.operation_id the steps of one run, one row per step or per fan-out item + audit_events, jwks_keys, admin_switches, expiration_notices: no foreign key ``` +A request that a step opens is not linked by a key: its ID is in the step's `outputs.requestId`, and the request records the +step's client `svc-cmapi-workflows` and the person who started the run (#26, docs/reviews/2026-12-01-issue-26-operations/design.md, D8). + @@ -62,6 +70,11 @@ These indexes and constraints carry correctness. The code relies on each of them | A hold is released with its reason, or not at all | The check `ck_resv_released`: `released_at` and `released_why` are both set or both null. `released_why` is the state the request moved to (`synced`, `rejected`, `cancelled`, `timeout`, `failed`, `superseded`, `sync_failed`) or `expired`. No code writes `observed` (docs/02's list): each reader stops counting a hold from its own watch, and the row stays active until the lifecycle releases it | Migration `0011` | | Two requests cannot both take a cluster's last headroom | Not an index: the advisory lock of the cluster (`ReservationRepo.lock_cluster`, `repo.py`), taken in the transaction that checks a hold and writes it. The partial index `idx_resv_active` keeps the sum of a cluster's active holds cheap | Migration `0011`, #62 | +| One run per Idempotency-Key of a caller | The partial unique index `uq_op_idempotency` on `(started_by_sub, idempotency_key)`, and the check `ck_op_idempotency`: a key has its fingerprint | Migration `0013` | +| A run or a step is final exactly when it has its end time | The checks `ck_op_finished` (`finished_at` is set when the phase is not `Pending` or `Running`) and `ck_opstep_finished` (the same, for a phase not `Pending`, `Running` or `Waiting`), with `ck_op_phase` and `ck_opstep_phase` naming the phases | Migration `0013` | +| One row per step and fan-out item of a run | The primary key of `operation_steps`, `(operation_id, step, item)`; `item` is `''` for a step that is not fanned out. One pending job per row: its `operation_step` job's `payload.kind` is `//`, under `uq_jobs_pending` | Migration `0013`, `queue_step` (`core/operations.py`) | +| The engine's caps count what is in flight across every run | Not an index: the advisory lock of the engine (`lock_engine`, `core/operations.py`), taken by every scheduler pass; the partial index `idx_opstep_active` keeps the count of rows `Running` or `Waiting` cheap | Migration `0013` | + The states of a request are in `cmapi/src/cmapi/core/lifecycle.py`. The eight open states are `pending_approval`, `approved`, `pr_open`, `applied`, `merge_failed`, `merged`, `awaiting_prune` and `sync_failed` (`core/db/models.py:20`). `applied` and `merge_failed` came with #286: the cluster holds the change and `main` does not yet, so the lock must hold. ## The models and the migrations agree @@ -173,9 +186,9 @@ One row is one unit of work. The worker claims a due row with `FOR UPDATE SKIP L | Column | What it holds | |---|---| -| `kind` | One of `push_branch`, `open_pr`, `open_revert`, `pr_checks`, `apply`, `merge`, `git_cleanup`, `git_reconcile` (#286), `watch_sync`, `prune`, `approval_timeout`, `channel_notify`, `rejections_prune` (#302) (`HANDLERS`, `cmapi/src/cmapi/jobs/__init__.py`) | +| `kind` | One of `push_branch`, `open_pr`, `open_revert`, `pr_checks`, `apply`, `merge`, `git_cleanup`, `git_reconcile` (#286), `watch_sync`, `prune`, `approval_timeout`, `channel_notify`, `rejections_prune` (#302), `operation_step` (#26) (`HANDLERS`, `cmapi/src/cmapi/jobs/__init__.py`) | | `request_id`, `cluster_id` | The request, and its cluster. `approval_timeout`, `git_reconcile` and `rejections_prune` have no request and no cluster. Each queues itself again, every hour, every 15 minutes and every day (`RECURRING`, `APPROVAL_TIMEOUT_EVERY`, `GIT_RECONCILE_EVERY`, `REJECTIONS_PRUNE_EVERY`) | -| `payload` | Optional JSON. `channel_notify` has `kind`: `pending`, `approved`, `rejected` or `timeout`. `watch_sync` has `since` when `:retry` queued it. `open_revert` has `by`. `approval_timeout`, `git_reconcile` and `rejections_prune` have `every` | +| `payload` | Optional JSON. `operation_step` has `kind` (`//`, one pending job per step row), `operationId`, `step` and `item`. `channel_notify` has `kind`: `pending`, `approved`, `rejected` or `timeout`. `watch_sync` has `since` when `:retry` queued it. `open_revert` has `by`. `approval_timeout`, `git_reconcile` and `rejections_prune` have `every` | | `run_after` | The earliest time that a worker can claim the job. A retry moves it | | `attempts` | Added 1 at each claim. At 5 attempts (`MAX_ATTEMPTS`), a failed job closes. If its request is `approved` or `pr_open`, the request moves to `failed`. If its request is `merged` or `awaiting_prune`, the request moves to `sync_failed` (`Worker._record_failure`, `cmapi/src/cmapi/worker.py`) | | `last_error`, `locked_until`, `locked_by`, `lease_generation` | The last error (cut to 2000 characters), the end of the lease (300 seconds from the claim), the worker that holds it, and the fencing token | @@ -216,6 +229,28 @@ Migration 0012 (#21) adds what a placement's hold needs before any request exist Migration 0012 (#21). One row is one scope of one cluster at `taken_at`, the end of an interval floored to `interval_seconds` (capacity.yaml `snapshotInterval`, 30 minutes by default): `cluster`, `zone:` (the nodes' `topology.kubernetes.io/zone`) or `role:` (`node-role.kubernetes.io/`; a node with several role labels counts in each). `cpu` (cores) and `memory` (bytes) hold `capacity` and `allocatable` from the API's nodes, `requested`, `limits`, `usedAvg` and `usedPeak` from Thanos per node, `nodeUsedAvg` (not queried yet, null) and, on the cluster row, `quotaCommitted` from the watch's ledger. `pods` holds `allocatable` and `running`, `nodes` the counts of the nodes and their conditions, `storage` is null (not queried yet). `source` is `thanos` when capacity.yaml `usage.source` is thanos, else `api`, and then every figure only Thanos gives is null, never 0. `complete` is false, with `detail` saying why, when a query failed or warned, the nodes could not be listed, or Thanos's allocatable and the API's differ by more than 5%. The columns are docs/02's with `source` and `detail` added; like 0010's tables it is not partitioned by month (#705) and lives in the cmapi schema, since the worker runs the job in the embedded mode. The job deletes rows past 395 days. +### `operations` + +Migration 0013 (#26). One row is one run of a template of `cmapi/src/cmapi/ops/templates/`. `parameters` are the run's, with +the template's defaults. `engine` is the engine that runs it (`builtin`: the Argo Workflows and Tekton adapters are not built) +and `run_name` its name there, the operation's own ID on the built-in engine. `phase` is `Pending`, `Running`, or a final +`Succeeded`, `Failed` (a step failed, or a step after it never ran), `Error` (the engine failed) or `Stopped` (cancelled). +`environments` is where the run acts, null for the whole instance: each read and the cancel check `operations:run` there. +`started_by` is the starter's identity record with the roles and groups of the token that started it, the grant its steps act +under (design.md, D3). `idempotency_key` and `idempotency_fingerprint` are the start's Idempotency-Key and a hash of its +template and parameters, kept with the run. `cancel_requested_by` and `cancel_requested_at` say who stopped it. `report` is set +when the run ends: each step's rows by phase, and each item that did not succeed or found something, with why. + +### `operation_steps` + +Migration 0013 (#26). One row is one step of a run, or one item of a fan-out step (`item` is the item's key, such as +`CRC/payments-dev`; `''` for a step that is not fanned out). `cluster_id` is the item's cluster, for the per-cluster cap. +`phase` is `Pending` (not started), `Running` (its job queued or running), `Waiting` (for a request, an import or a retry's +backoff; its next job is queued for later), or a final `Succeeded`, `Skipped`, `Failed`, `Error` or `Stopped`. `attempts` +counts the failed attempts the template's retry block retried; `last_error` is the last one. `inputs` is the item's value from +the step that listed the items, and `outputs` what the step recorded: `requestId` of a request it opened, `outcome`, `note` and +the step's own results (`items` of a step that fans another out). + ## Planned adoption quota view (#26, #251; not built) This section describes the proposed model in docs/reviews/2026-11-14-issue-26-adoption/README.md, D8 and D17–D19. @@ -274,7 +309,7 @@ The figure is `docs/diagrams/data-model/source.html`, drawn to diagram-kit's `/v Written by `scripts/db-schema-doc.py` from the test database of the service suite (PostgreSQL 16 on `127.0.0.1:55432`, macOS, 2026-11-13; written again on 2026-11-23 for migrations `0008` (#592) and `0009` (#603), and on 2026-11-26 for `0011` (#62) and `0012` (#21)). The test `tests/service/test_data_model_doc.py` fails when this part differs from the database. To write it again: `CMAPI_DATABASE_URL=... python scripts/db-schema-doc.py`, and replace the text between the two marker lines. -Migration head: `0012`. Tables: 14. +Migration head: `0013`. Tables: 16. ### `admin_switches` @@ -545,6 +580,65 @@ Migration head: `0012`. Tables: 14. | `idx_verdicts_cluster_day` | Index | `btree (cluster_id, day)` | | `idx_verdicts_day` | Index | `btree (day)` | +### `operation_steps` + +| Column | Type | Null | Default | +|---|---|---|---| +| `operation_id` | varchar(40) | no | | +| `step` | varchar(80) | no | | +| `item` | varchar(253) | no | `''::character varying` | +| `cluster_id` | varchar(63) | no | `''::character varying` | +| `phase` | varchar(20) | no | `'Pending'::character varying` | +| `attempts` | integer | no | `0` | +| `inputs` | jsonb | yes | | +| `outputs` | jsonb | yes | | +| `last_error` | text | yes | | +| `started_at` | timestamptz | yes | | +| `finished_at` | timestamptz | yes | | +| `updated_at` | timestamptz | no | `now()` | + +| Constraint or index | Kind | Definition | +|---|---|---| +| `ck_opstep_attempts` | Check | `CHECK ((attempts >= 0))` | +| `ck_opstep_finished` | Check | `CHECK (((finished_at IS NULL) = ((phase)::text = ANY ((ARRAY['Pending'::character varying, 'Running'::character varying, 'Waiting'::character varying])::text[]))))` | +| `ck_opstep_phase` | Check | `CHECK (((phase)::text = ANY ((ARRAY['Pending'::character varying, 'Running'::character varying, 'Waiting'::character varying, 'Succeeded'::character varying, 'Skipped'::character varying, 'Failed'::character varying, 'Error'::character varying, 'Stopped'::character varying])::text[])))` | +| `operation_steps_operation_id_fkey` | Foreign key | `FOREIGN KEY (operation_id) REFERENCES operations(operation_id)` | +| `operation_steps_pkey` | Primary key | `PRIMARY KEY (operation_id, step, item)` | +| `idx_opstep_active` | Index | `btree (phase, cluster_id) WHERE ((phase)::text = ANY ((ARRAY['Running'::character varying, 'Waiting'::character varying])::text[]))` | + +### `operations` + +| Column | Type | Null | Default | +|---|---|---|---| +| `operation_id` | varchar(40) | no | | +| `template` | varchar(80) | no | | +| `parameters` | jsonb | no | | +| `engine` | varchar(20) | no | | +| `run_name` | varchar(253) | no | | +| `phase` | varchar(20) | no | `'Pending'::character varying` | +| `environments` | jsonb | yes | | +| `started_by_sub` | varchar(100) | no | | +| `started_by` | jsonb | no | | +| `idempotency_key` | varchar(100) | yes | | +| `idempotency_fingerprint` | varchar(64) | yes | | +| `cancel_requested_by` | varchar(100) | yes | | +| `cancel_requested_at` | timestamptz | yes | | +| `report` | jsonb | yes | | +| `started_at` | timestamptz | no | `now()` | +| `updated_at` | timestamptz | no | `now()` | +| `finished_at` | timestamptz | yes | | + +| Constraint or index | Kind | Definition | +|---|---|---| +| `ck_op_cancel` | Check | `CHECK (((cancel_requested_at IS NULL) = (cancel_requested_by IS NULL)))` | +| `ck_op_finished` | Check | `CHECK (((finished_at IS NULL) = ((phase)::text = ANY ((ARRAY['Pending'::character varying, 'Running'::character varying])::text[]))))` | +| `ck_op_idempotency` | Check | `CHECK (((idempotency_key IS NULL) = (idempotency_fingerprint IS NULL)))` | +| `ck_op_phase` | Check | `CHECK (((phase)::text = ANY ((ARRAY['Pending'::character varying, 'Running'::character varying, 'Succeeded'::character varying, 'Failed'::character varying, 'Error'::character varying, 'Stopped'::character varying])::text[])))` | +| `operations_pkey` | Primary key | `PRIMARY KEY (operation_id)` | +| `idx_op_active` | Index | `btree (phase) WHERE (finished_at IS NULL)` | +| `idx_op_started` | Index | `btree (started_at)` | +| `uq_op_idempotency` | Unique index | `btree (started_by_sub, idempotency_key) WHERE (idempotency_key IS NOT NULL)` | + ### `policy_rejections` | Column | Type | Null | Default | diff --git a/docs/18-configuration.md b/docs/18-configuration.md index 9edcd4e7..fb8b1393 100644 --- a/docs/18-configuration.md +++ b/docs/18-configuration.md @@ -950,7 +950,7 @@ Three plugins have writes (`WRITERS`): `namespaces`, `adoption` (#26), and `capa ## `integrations.yaml` -Optional. The code that reads it is `cmapi/src/cmapi/core/sync.py` (`DeliveryConfig.from_integrations`), `cmapi/src/cmapi/core/channels.py` and `cmapi/src/cmapi/routers/admin.py`. The chart writes it from the values `delivery.*`, `argocd.*` and `notifier.*` (`deploy/helm/cmapi/templates/config.yaml`). +Optional. The code that reads it is `cmapi/src/cmapi/core/sync.py` (`DeliveryConfig.from_integrations`), `cmapi/src/cmapi/core/channels.py`, `cmapi/src/cmapi/core/operations.py` (`OperationsSettings.from_integrations`, #26) and `cmapi/src/cmapi/routers/admin.py`. The chart writes it from the values `delivery.*`, `argocd.*` and `notifier.*` (`deploy/helm/cmapi/templates/config.yaml`). | Key | Type | Default | Meaning | |---|---|---|---| @@ -962,7 +962,9 @@ Optional. The code that reads it is `cmapi/src/cmapi/core/sync.py` (`DeliveryCon | `delivery.argocd.rootApplication` | text | `cluster-configs-{clusterId}` | The name of the root Application. `{clusterId}` becomes the cluster ID in lower case with `_` as `-`, and `{namespace}` the request's namespace. Any other placeholder in this template or in `delivery.flux.kustomization` stops the start (`core/sync.py`) | | `syncSignal.pollInterval` | duration | `30s` | How often the worker reads a merged request's objects (and the Application in `argocd` mode, or the signal) | | `syncSignal.default`, `syncSignal.reconcileInterval` | text | None. With no `syncSignal` key the route reports `{default: poll}` | Reported by `GET /api/v1/admin/integrations`. No other code reads them. The value `notify` is not built | -| `operations.*` | mapping | `engine: builtin` | Reported by `GET /api/v1/admin/integrations`. No built code runs an operation engine | +| `operations.engine` | `builtin`, `argo-workflows` or `tekton` | `builtin` | The engine that runs operations (#26). `builtin` runs the steps in the cmapi worker, with their state in PostgreSQL. This build has no adapter for `argo-workflows` or `tekton`: an instance that names one starts and stays ready, and every `POST /api/v1/operations` answers 503 `operations-engine-unavailable`; the reads still answer, and a run the built-in engine started goes on. Another value stops the start (`OperationsSettings`, `core/operations.py`). Also reported by `GET /api/v1/admin/integrations` | +| `operations.builtin.maxConcurrentSteps` | integer, 1 to 64 | `4` | The steps of every run that may be `Running` at once (queued or running now). A step that waits for a request, an import or a retry's backoff is `Waiting` and does not count. docs/02: "separate from request jobs, so operations never starve them". Another value stops the start | +| `operations.argoWorkflows`, `operations.tekton` | mapping | None | Not read: the adapters are not built | | `events.*` | mapping | `publisher: none` | Reported by the same route. No built code publishes events | | `notifier.smtp.host` | text | None | The SMTP host. Without it, only the portal channel is active, and expiry notices are recorded for the Expiration tab without an email | | `notifier.smtp.port` | integer | `25`, or `465` with `tls: implicit` | The SMTP port | diff --git a/docs/21-usage-from-thanos.md b/docs/21-usage-from-thanos.md index 0de76529..6588cd3e 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`) | -| 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 | +| 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:678-688`), 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:261-267`) | +| 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:678-688`). 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 | @@ -215,7 +215,7 @@ they are kept. While any finding stands, `ThanosQuerier.query` refuses before it - **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`). - **A namespace create never queries Thanos.** Only a quota change on an existing namespace reads usage - (`cmapi/src/cmapi/core/pipeline.py:454-461`). A test creates a namespace on PostgreSQL with `usage.source: thanos` and both + (`cmapi/src/cmapi/core/pipeline.py:462-469`). 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 usage `unavailable` (`cmapi/tests/service/test_reader_thanos_grants_724.py:428-470`). diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index af031f8d..7c3a235b 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -121,6 +121,14 @@ Status: read from `main` at `afd1206` on 2026-11-23. Each row was read from the | `instance.git.hostChecks` | `true`: the worker waits for `ci/kubeconform` and `ci/kyverno` as commit statuses of the host, and posts its own. | [18-configuration.md](18-configuration.md) | | `kubeconform` | The validator of the rendered manifests. It is baked into the api image with the Kyverno CLI. | [Containerfile](../cmapi/Containerfile), [18-configuration.md](18-configuration.md) | | Jobs and leases | The `jobs` table holds one unit of work for the worker, with a lease. A fencing token (migration 0003) refuses the commit of a worker whose lease expired. | [16-data-model.md](16-data-model.md), [0003](../cmapi/src/cmapi/core/db/migrations/versions/0003_job_lease_generation.py) | +| Operation | A run of an operation template: a set of steps that the built-in engine runs in the worker, with their state in `operations` and `operation_steps` (migration 0013). Started by `POST /api/v1/operations`, read as `GET /api/v1/operations/{id}`, stopped by `:cancel`; each needs `operations:run` (#26). | [core/operations.py](../cmapi/src/cmapi/core/operations.py), [design.md](reviews/2026-12-01-issue-26-operations/design.md) | +| Operation template | The data of an operation: its parameters, its retry block and its steps, each step a function of the step library. The built ones are `tiers-rerender`, `rebuild-verify`, `reconcile` and `cluster-onboard`. | [ops/templates/](../cmapi/src/cmapi/ops/templates/) | +| Step library | The Python functions of `cmapi.ops`, one per step of each template, keyed by template and step. docs/02: "One step library, any engine". | [ops/\_\_init\_\_.py](../cmapi/src/cmapi/ops/__init__.py) | +| Built-in engine | The operations engine that runs in the cmapi worker: one `operation_step` job per step that is due, under one scheduler (`advance`). integrations.yaml `operations.engine: builtin`, the default. Argo Workflows and Tekton are the optional engines, not built: naming one answers 503 `operations-engine-unavailable`. | [core/operations.py](../cmapi/src/cmapi/core/operations.py), [18-configuration.md](18-configuration.md) | +| Step phases | `Pending`, `Running` (queued or running now), `Waiting` (for a request, an import or a retry's backoff), and the final `Succeeded`, `Skipped`, `Failed`, `Error`, `Stopped`. A run is `Pending`, `Running`, `Succeeded`, `Failed`, `Error` or `Stopped`. | [core/operations.py](../cmapi/src/cmapi/core/operations.py) | +| Fan-out step | A step with `withParam`: one `operation_steps` row per item that an earlier step listed (for example one per outdated namespace), capped by `parallelism` and `perCluster`. | [design.md](reviews/2026-12-01-issue-26-operations/design.md), D10 | +| `svc-cmapi-workflows` | The client that an operation's steps act as. On the built-in engine it holds the roles of the person who started the run, and each request it opens has that person as its requester (delegation, design.md D3). | [core/operations.py](../cmapi/src/cmapi/core/operations.py) (`StepContext.actor`) | +| `maxConcurrentSteps` | integrations.yaml `operations.builtin.maxConcurrentSteps`, default 4: the steps of every run that may be `Running` at once, so operations never fill the queue ahead of the request jobs. | [18-configuration.md](18-configuration.md) | | `policy_rejections` | The table of cmapi's refusals before Git, and Kyverno's warnings on a plan that went on (migration 0006, #302). Pruned by the daily job `rejections_prune`. | [16-data-model.md](16-data-model.md), [18-configuration.md](18-configuration.md) | ## Policies @@ -195,7 +203,7 @@ Status: read from `main` at `afd1206` on 2026-11-23. Each row was read from the | `crc-image.sh`, `render.sh`, `release-crc.sh` | The scripts that import an image by digest, render the manifests for an environment, and run `helm upgrade` with the environment file and the image lock. | [13-crc-deployment.md](13-crc-deployment.md), [crc.yaml](../deploy/environments/crc.yaml) | | Plain manifests, chart | Two ways to deploy: plain YAML under `deploy/manifests/` first, and a Helm chart under `deploy/helm/cmapi` for each component later. None for Keycloak or LDAP. | [deploy/manifests/README.md](../deploy/manifests/README.md), [crc.yaml](../deploy/environments/crc.yaml) | | CloudNativePG | The operator that runs the default database: one `Cluster` (operator 1.30.1 on CRC). A site with its own PostgreSQL provides Secret `cmapi-db-app` instead. | [12-existing-postgresql.md](12-existing-postgresql.md), [CLAUDE.md](../CLAUDE.md) | -| Migrations 0001 to 0010 | Alembic revisions. 0001 schema; 0002 one approval per person; 0003 fencing token on job leases; 0004 `counted_for` on approvals; 0005 `applied` and `merge_failed` hold the lock; 0006 `policy_rejections`; 0007 request events record the insertion time; 0008 an Idempotency-Key belongs to its caller (`idempotency_sub` and `uq_cr_idempotency_caller`, beside the requester's index, #592); 0009 the caller's index is the only one, with the check `ck_cr_idempotency_caller` (#603); 0010 `analysis_sweeps` and `namespace_verdicts`, the daily usage sweep and its verdicts (#310). | [versions/](../cmapi/src/cmapi/core/db/migrations/versions/) | +| Migrations 0001 to 0013 | Alembic revisions. 0001 schema; 0002 one approval per person; 0003 fencing token on job leases; 0004 `counted_for` on approvals; 0005 `applied` and `merge_failed` hold the lock; 0006 `policy_rejections`; 0007 request events record the insertion time; 0008 an Idempotency-Key belongs to its caller (`idempotency_sub` and `uq_cr_idempotency_caller`, beside the requester's index, #592); 0009 the caller's index is the only one, with the check `ck_cr_idempotency_caller` (#603); 0010 `analysis_sweeps` and `namespace_verdicts`, the daily usage sweep and its verdicts (#310); 0011 `capacity_reservations` (#62); 0012 `capacity_snapshots` and placement holds (#21); 0013 `operations` and `operation_steps`, the built-in operations engine (#26). | [versions/](../cmapi/src/cmapi/core/db/migrations/versions/) | | Argo CD | The GitOps controller on each cluster. In `argocd` mode it applies the namespace folder. cmapi reads the Application's status to confirm `synced`. | [06-reference-architecture.md](06-reference-architecture.md), [18-configuration.md](18-configuration.md) | | Backup (CRC) | `crc-backup.sh`: the backup that step 13 takes immediately before the import and step 25 deletes. | [13-crc-deployment.md](13-crc-deployment.md) | diff --git a/docs/citations.lock.json b/docs/citations.lock.json index b8b237b0..1a1ac2b2 100644 --- a/docs/citations.lock.json +++ b/docs/citations.lock.json @@ -338,7 +338,7 @@ " return None", " return Requirement(rule=d[\"rule\"], slots=tuple(Slot(**s) for s in d[\"slots\"]), self_approval=d[\"selfApproval\"]," ], - "docs/14-authorization.md|cmapi/src/cmapi/core/docs.py|349-354": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/docs.py|355-360": [ " if permission:", " desc += f\"\\n\\n**Requires** `{permission}`.\"", " op_id = f\"{self.plugin}_{fn.__name__}\"", @@ -504,28 +504,28 @@ " self.identity.get(\"requireOnBehalfOf\", False),", " self.identity.get(\"automationRoles\", [\"cmapi-onboarding\"]))" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|282-282": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|290-290": [ " self.cfg.roles.require(who, \"namespaces:create\" if action == \"create\" else \"namespaces:write\", env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|288-288": [ - " requester = self.requester_for(who, body.get(\"onBehalfOf\"))" - ], "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|296-296": [ + " requester = requester or self.requester_for(who, body.get(\"onBehalfOf\"))" + ], + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|304-304": [ " 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|598-598": [ " 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|715-715": [ " 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|873-873": [ " 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": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/problem_docs.py|105-105": [ " \"on-behalf-of-not-allowed\": \"Remove `onBehalfOf`. A person calls as themselves.\"," ], - "docs/14-authorization.md|cmapi/src/cmapi/core/problem_docs.py|105-105": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/problem_docs.py|106-106": [ " \"on-behalf-of-required\": \"Name the person in `onBehalfOf`. A service client must say for whom it calls.\"," ], "docs/14-authorization.md|cmapi/src/cmapi/core/views.py|25-27": [ @@ -538,7 +538,7 @@ " app.include_router(health.version_router)" ], "docs/14-authorization.md|cmapi/src/cmapi/main.py|204-208": [ - " authed_routers = (me.router, requests.router, admin.router, *cfg.plugins.routers())", + " authed_routers = (me.router, requests.router, operations.router, admin.router, *cfg.plugins.routers())", " # Each route that takes a token takes one from its caller's bucket, after the sign-in (routers/__init__.py, rate_limit;", " # #689). The routes with no token (the version, health, the problem pages, the docs) have no caller to count.", " for r in authed_routers:", @@ -1550,7 +1550,7 @@ "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/clients/policyreports.py|38-38": [ "POLICY_KINDS = (\"ValidatingPolicy\",)" ], - "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|256-262": [ + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|261-267": [ " def workload_counts(self, cluster_id: str, ns: str) -> tuple[int, int]:", " \"\"\"Pods and PVCs in a namespace, for the delete thresholds. A live read: unknown is 503, never 0.\"\"\"", " client = self.registry.cache(cluster_id).client", @@ -1559,7 +1559,7 @@ " return (len(client.list(\"Pod\", namespace=ns)[\"items\"]),", " len(client.list(\"PersistentVolumeClaim\", namespace=ns)[\"items\"]))" ], - "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|454-461": [ + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|462-469": [ " # A quota change on an existing namespace reads its live 14-day usage (docs/01, \"Quota changes on existing namespaces\");", " # nothing else does: \"Never queried while creating a namespace or setting its first quota\" (docs/01, Thanos on onboarding).", " usage_view, usage_facts = None, {}", @@ -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|678-688": [ " 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/docs/reviews/2026-12-01-issue-26-operations/design.md b/docs/reviews/2026-12-01-issue-26-operations/design.md new file mode 100644 index 00000000..bb94ce2e --- /dev/null +++ b/docs/reviews/2026-12-01-issue-26-operations/design.md @@ -0,0 +1,210 @@ +# Story #26, criterion 3: the built-in operations engine + +The criterion: "Built-in cluster-onboard, rebuild-verify, reconcile and tier re-render operations report progress, survive +retries and honor approvals; optional workflow engines are not required." This record holds the decisions the design left +open, each with the source it rests on. The design itself is docs/02, "Optional integrations: sync signal, operations, events" +("One step library, any engine", the OperationsEngine Protocol, "Built-in engine", the four rules), "Changing a tier", and +"Onboarding becomes shorter"; docs/07 gives the template catalogue and the operations table. It is built as written; nothing +here reopens it. + +Written by the implementer (Opus 5.5, high) on 2026-12-01. Every source below was fetched that day. + +## What is built in this first slice + +- The built-in engine (`cmapi/src/cmapi/core/operations.py`): steps run in the cmapi worker as jobs of kind `operation_step`, + with their state in PostgreSQL (`operations`, `operation_steps`, migration `0013`). +- The step library and four templates (`cmapi/src/cmapi/ops/`): tiers-rerender and rebuild-verify end to end; reconcile and + cluster-onboard as far as what they need is built (D12). +- The Operations API (`cmapi/src/cmapi/routers/operations.py`): `POST /api/v1/operations`, `GET /api/v1/operations`, + `GET /api/v1/operations/{id}`, `POST /api/v1/operations/{id}:cancel`, each needing `operations:run`. +- Not built: the Argo Workflows and Tekton adapters, which the criterion does not need; a screen (the mockup has none). + +## D1. An engine with no adapter answers 503; reads go on + +docs/02, "Failure isolation": "If the configured engine is unreachable at startup, cmapi starts anyway and stays ready. POST +/api/v1/operations returns 503 operations-engine-unavailable until the engine comes back." This build has no adapter for +`argo-workflows` or `tekton`, so an instance whose integrations.yaml names one starts and is ready, and every start is 503 +`operations-engine-unavailable` (`UnavailableEngine`). A value that integrations.yaml cannot hold (`airflow`, or +`maxConcurrentSteps: 0`) stops the start, as a bad `delivery.mode` does (`OperationsSettings.from_integrations`). A run the +built-in engine started keeps running if integrations.yaml later names another engine (`Operations.builtin`). + +## D2. One job per step row, one scheduler + +docs/02, "Built-in engine": "Each step is a job of kind operation_step in the existing jobs table, and its state lives in +operation_steps, so a worker restart resumes where it stopped. Retries follow the template's retry block. A fan-out step gets +one row per item, capped per cluster." So: + +- Each row that is due has one pending `operation_step` job. Its `payload.kind` is `//`, so the existing + `uq_jobs_pending` index keeps it to one. +- One function moves every run (`advance`), under one advisory lock for the engine. It creates the rows of the steps whose + `after` steps all ended Succeeded or Skipped, starts Pending rows within the caps, and ends a run with nothing in flight. +- A row that waits on something outside the engine (a request, an import, a retry's backoff) is `Waiting`, with its next job + queued for later. `maxConcurrentSteps` (integrations.yaml, default 4) counts only the rows `Running` across every run: the + jobs that are due or running now. docs/02: "separate from request jobs, so operations never starve them". A run of 500 + namespaces therefore never puts 500 due jobs ahead of the request jobs. + +## D3. The step's identity: delegation, not impersonation + +docs/02, rule 4: "Steps call cmapi as svc-cmapi-workflows, and every request they open records both that client and the person +who started the operation." On the built-in engine a step runs in the worker, with no token. RFC 8693, section 1.1 +(): "With delegation semantics, principal A still has its own identity separate +from B", where impersonation makes A "indistinguishable from B in that context". cmapi takes the delegation side: + +- The step acts as `svc-cmapi-workflows` (`StepContext.actor`), a service identity of its own, holding the roles of the token + that started the run (stored in `operations.started_by`). A step can do no more than its starter could, in the environments + where the starter could (a confused deputy is not possible), and a plan checks `namespaces:write` against those roles. +- Each request it opens has the starter as its requester and the step's client as the sender (`StepContext.requester`): + `requester_username` and `requester_sub` are the starter's, `requester_kind` is `service`, `requester_client` and + `requester.submittedByClient` are `svc-cmapi-workflows`, and `automated` is true. +- The approval ledger refuses the requester's subject as an approver, so the starter cannot approve the requests of the run + where the environment forbids self-approval. docs/01, "Approval of record": the approver is "not the person who started the + operation". Where an environment allows self-approval (rnd and dev in the examples), the same rule as for a person's own + request applies. +- Limitation, recorded: roles are those of the token at the start. A role removed from the starter later does not stop a run + already started; an operator cancels it. + +## D4. Retries: Argo's retryStrategy, and what is retried + +The template's `retry: {limit: 3, backoff: 30s, factor: 2}` (docs/02) follows Argo Workflows' RetryStrategy, read from the +source (): `Limit` "is the +maximum number of retry attempts [...] It does not include the original [...]; the maximum number of total attempts will be +limit + 1"; `Backoff.Duration` "is the amount to back off"; `Backoff.Factor` "is a factor to multiply the base duration after +each failed retry". So a step is tried at most 4 times, waiting 30, 60 and 120 seconds (`Retry.delay`). + +What is retried, and what is not: + +| The step | The row | +|---|---| +| raises `StepRefused` (a step that is not built, a refusal the same call would give again) | Failed, no retry | +| raises a problem with a 4xx status other than 409 and 412 (policy-violation, capacity-exceeded, not found) | Failed, no retry: the same plan gives the same answer | +| raises a 5xx problem (git-unavailable, cluster-unreachable, validator-busy), a 409, a 412, or any other exception | Waiting, `attempts` + 1, `last_error`, the next job after the backoff; Failed past the limit | +| rolls back the whole transaction (RequestRepo.insert does on a lost race for the namespace lock) | the exception goes to the worker, which retries the job as it does every job (`worker.py`, BACKOFF): nothing of the step was kept | + +A worker that fails a job's own bookkeeping five times (`MAX_ATTEMPTS`) ends the row `Error` (`job_gave_up`), so the run ends +instead of showing Running for ever. + +## D5. Surviving a worker that dies mid-step + +Three things hold together: + +1. A step runs in its job's transaction. What it writes (a request, its outputs) and its row's new phase commit together, or not + at all. A worker that dies before the commit leaves nothing. +2. The job's lease (`jobs.locked_until`) runs out, and another worker claims the same job. The fencing token + (`lease_generation`, `JobRepo.assert_lease`) refuses the commit of a worker that lost its lease. +3. A step that opens a request finds the one it opened before: each row has its own Idempotency-Key (`//`, + under the subject `svc-cmapi-workflows`), and the step looks it up first (`RequestRepo.by_idempotency`). A step that waits + reads the request ID from its own outputs. + +`test_a_worker_that_dies_mid_step_leaves_the_step_to_the_next_worker_and_one_request_is_opened` proves it: the first worker +opens the request and dies before its commit; the next worker claims the job when the lease runs out; one request is opened. + +## D6. Cancel + +The long-running operations contract (, +CancelOperation): "The server makes a best effort to cancel the operation, but success is not guaranteed", and "On successful +cancellation, the operation is not deleted". Argo Workflows' `argo stop` (): +"Stop a workflow but still run exit handlers". So `:cancel` records who asked and when, and the run is kept: + +- No new step starts. A Pending row is Stopped at once, and so is a Waiting row that no job holds. A row whose job runs at that + moment is Stopped by its job, before it calls the step again. +- The run ends `Stopped` once no row is in flight; in the common case that is in the cancel's own answer. +- A request that a step opened is not cancelled: it is an ordinary request, which its requester or an operator cancels on its + own (`POST /api/v1/requests/{id}:cancel`). The report lists it. Cancelling an approval in flight behind people's backs would + be a decision the person who cancels the run did not make. +- A cancel of a run that ended is 409 `invalid-transition`. No template has an exit handler in this slice (D12). + +## D7. How a waiting step ends with its request + +docs/02, rule 3: "a step that needs approval opens a cmapi request and polls it, and people approve in the PR". docs/07: it +"polls GET /api/v1/requests/{id} with backoff until it is synced or terminal". The step reads the request's state every 30 +seconds (`wait_for_request`): + +| The request | The row | Why | +|---|---|---| +| `synced` | Succeeded | the change is on the cluster | +| `rejected`, `cancelled`, `timeout` | Skipped, `outcome` names it | the approval path ended it: a decision, or none in time. A rejected re-render is a person's call, not the engine's failure | +| `failed`, `superseded`, `reverted` | Failed | the delivery failed | +| any open state, `sync_failed` and `merge_failed` among them | Waiting | a person can still `:retry` it | + +A tiers-rerender whose namespace another request holds waits for it (docs/07: "the step treats 409 as wait and retry"), and +one whose Git folder is already current (422 `no-change`) is Skipped with `outcome: current`. + +## D8. No `operation_id` column on `change_requests` + +docs/07 adds `change_requests.operation_id`; docs/02's built-in engine does not. The request a step opens is in the step's +`outputs.requestId`, and the request records the step's client and the starter (D3), so the table of every write is not touched. +A later screen that lists a request's operation can add the column then, as an expand-only migration. + +## D9. Who may read and cancel a run + +docs/02 names `operations:run` for the start. The reads and the cancel need it too, where the run acts: every environment a +tiers-rerender names, the environment of the cluster of rebuild-verify and cluster-onboard, and every environment (an +unrestricted grant) for reconcile, which acts on the whole instance, and for a cluster that clusters.yaml does not name yet. +This is how `POST /api/v1/clusters/{id}:probe` treats an import with no environment (`routers/me.py`). The list shows only the +runs the caller may read. reconcile pauses auto-approval, an admin's switch (`approvals:pause`), so its start also needs that +permission (the template's `permissions`). + +## D10. Fan-out, batches and the per-cluster cap + +A fan-out step names the step that lists its items with `withParam: "{{steps..outputs.items}}"`, Argo's own key: "WithParam +expands a step into multiple parallel steps from the value in the parameter, which is expected to be a JSON list" +(workflow_types.go). `parallelism` caps the items in flight at once (Argo's WorkflowSpec `parallelism`: "limits the max total +parallel pods that can execute at the same time"; ), and `perCluster` +caps them per cluster. tiers-rerender maps docs/02's `batchSize` (default 20) to `parallelism` and `maxOpenPerCluster` (default +5) to `perCluster`: at most 20 of the run's requests open at once, at most 5 on one cluster. An item is in flight from its +start until its request ends. + +## D11. Templates ship with the build + +docs/02: "An operation template is data in config/operations/. Its steps are Python functions in cmapi.ops". A template names +steps by their functions, so a template and the functions it names must change together. The templates are data in the package +(`cmapi/src/cmapi/ops/templates/*.yaml`, in `pyproject.toml`'s package data), parsed and checked when the process starts: an +unknown key, a step after a step that does not come before it, a reference to no step or parameter, or a step with no function +stops the start (`parse_template`). An instance does not override them in this slice. + +## D12. What is not built, and where it stops + +| Template | Step | Today | Issue | +|---|---|---|---| +| cluster-onboard | propose-registry | Skipped when clusters.yaml names the cluster; refuses otherwise. `POST /api/v1/admin/clusters:propose` is not built, and which repository holds clusters.yaml is an owner decision | #761 | +| cluster-onboard | smoke-test | refuses (`notBuilt`), after the steps before it ran | #765 | +| cluster-onboard | preflight | checks the import: connected, no finding (with the Thanos grants, #724). Thanos retention and the root Application's sync are listed as not checked | #763 | +| reconcile | rebuild-requests | succeeds when every bot branch and pull request has its request; refuses when find-unrecorded lists any (a security design: a rebuilt row is an approved request made from Git text) | #762 | +| every template | `onExit` | not supported: docs/02's cluster-onboard has `onExit: cleanup` for the bootstrap Secret, and the bootstrap left cluster-onboard for the baseline | | + +A step that is not built refuses with its issue's number in `last_error`, so a run stops there and says why; it never reports +a pass for what it did not do. + +## D13. The start's Idempotency-Key + +draft-ietf-httpapi-idempotency-key-header-07, section 2.3 (): +"The resource SHOULD define such expiration policy and publish it in the documentation"; section 2.4: "An idempotency fingerprint +MAY be used in conjunction with an idempotency key". The start requires the header. The key is kept with its run, with a +fingerprint of the template and the parameters: the same caller, key and body get the run it started for as long as the run is +kept; the same key with another body is 409 `idempotency-replay`. The header's description in the API says so. + +## D14. Smaller choices + +- Operation IDs are `op-YYYYMMDD-<8 hex>`, random like a placement's ID, so a start takes no day lock. +- The OperationsEngine Protocol (`core/ports.py`) is synchronous, as the rest of cmapi is, with docs/02's `available`, `submit` + and `cancel`; the built-in engine writes its own state, so it has no `watch`. +- tiers-rerender selects the outdated namespaces from the same watch cache that `GET /api/v1/quotas` reads for `tierOutdated`; + each plan then reads Git, as every plan does. A cluster that cannot be read is retried, never taken as having none. A + namespace with no ResourceQuota that cmapi rendered (an adopted one) is not selected. +- "a decrease below current use is skipped": the live quota's `status.used` against the plan's new hard values, through + `TierCatalog.compare`'s `below_used`. +- The requests a run opens do not take tokens from the team's rate-limit bucket (`team_request`, #689), which counts the writes + of callers of the API. A run is bounded by its own caps instead: `batchSize` and `maxOpenPerCluster` (D10). +- The locks, in one order everywhere: a step's job locks its own row, then the engine's advisory lock, then the runs' rows; a + cancel takes the engine's lock before its run's row. A scheduler pass touches only Pending rows and the Waiting rows it can + lock without waiting (`SKIP LOCKED`), never a row whose job runs (`lock_engine`). +- rebuild-verify reads each folder against the cluster with the read that ends a request (`read_plan`, #751), not Argo CD's + sync status: "a deliverer's report is never the proof" (docs/02, "Delivery modes and the read that ends a request"). + +## Tests + +`cmapi/tests/service/test_operations_26.py`, on the service suite's fakes (no cluster): start and progress; the approval-gated +step waiting until a platform approver approves; a decrease below use skipped; a rejection reported; a retry with backoff, and a +step out of retries; a worker that dies mid-step; batchSize and cancel; 403 without `operations:run` and outside the +environment; the refusals at the start; the Idempotency-Key; 503 `operations-engine-unavailable`; a bad integrations.yaml; +`maxConcurrentSteps`; rebuild-verify's drift report; reconcile; cluster-onboard; migration `0013`'s constraints, up and down. From 13c6a05a7506f8f4efef8d0edf9415f5ab124a51 Mon Sep 17 00:00:00 2001 From: ephico2real2 Date: Tue, 1 Dec 2026 11:25:24 -0600 Subject: [PATCH 3/4] #26 operations review fixes: delegated changes satisfy the starter's own approvals; starter identity checked; stored scope on replay and dispatch; cancel seen under the lock; start lock before the key; bounded step keys; Gitea paging; report order Reviewer 1 (Codex gpt-6.2-astra) 12 of 13 accepted, #6 rejected; reviewer 2 (Fable) R2-1..R2-3. Applied by the coordinator after a line-by-line read. Record: docs/reviews/2026-12-01-issue-26-operations/. --- cmapi/src/cmapi/core/approvals.py | 23 +- cmapi/src/cmapi/core/git/gitea.py | 18 +- cmapi/src/cmapi/core/operations.py | 41 +- cmapi/src/cmapi/core/pipeline.py | 28 +- cmapi/src/cmapi/ops/__init__.py | 4 +- cmapi/src/cmapi/routers/operations.py | 24 +- cmapi/tests/service/test_api_standard.py | 2 +- cmapi/tests/service/test_operations_26.py | 31 + .../service/test_operations_review_774.py | 357 +++++++ .../tests/service/test_usage_verdicts_310.py | 5 +- docs/14-authorization.md | 20 +- docs/21-usage-from-thanos.md | 6 +- docs/citations.lock.json | 28 +- .../2026-12-01-issue-26-operations/README.md | 30 + .../2026-12-01-issue-26-operations/design.md | 35 +- .../2026-12-01-issue-26-operations/final.diff | 997 ++++++++++++++++++ .../reviewer-1-codex.md | 721 +++++++++++++ .../reviewer-2-fable.md | 291 +++++ 18 files changed, 2589 insertions(+), 72 deletions(-) create mode 100644 cmapi/tests/service/test_operations_review_774.py create mode 100644 docs/reviews/2026-12-01-issue-26-operations/README.md create mode 100644 docs/reviews/2026-12-01-issue-26-operations/final.diff create mode 100644 docs/reviews/2026-12-01-issue-26-operations/reviewer-1-codex.md create mode 100644 docs/reviews/2026-12-01-issue-26-operations/reviewer-2-fable.md diff --git a/cmapi/src/cmapi/core/approvals.py b/cmapi/src/cmapi/core/approvals.py index bbaf57ae..8a2ec60b 100644 --- a/cmapi/src/cmapi/core/approvals.py +++ b/cmapi/src/cmapi/core/approvals.py @@ -17,7 +17,7 @@ """ from __future__ import annotations -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from fnmatch import fnmatchcase from pathlib import Path from typing import Any, Mapping @@ -168,6 +168,27 @@ def added_for(self, facts: Mapping[str, Any], names: frozenset[str]) -> list[Slo # ---- decide def decide(self, facts: Mapping[str, Any], *, paused: bool = False, team_auto_today: int = 0) -> Requirement: + """The approvals a request needs. A delegated request (an operation's step: sent by svc-cmapi-workflows for the + person who started the run) is decided twice: as sent, and as the starter's own request (`starterApprovalFacts` + replace the facts about the sender). It must satisfy both, so delegation never lowers what the starter's own request + needs (RFC 8693, section 1.1: the delegate acts with rights the starter delegated, no more), and a rule about the + workflow client or about automated requests still adds its approvers.""" + req = self._requirement(facts, paused, team_auto_today) + if "starterApprovalFacts" not in facts: + return req + direct = self._requirement({**facts, **facts["starterApprovalFacts"]}, paused, team_auto_today) + if direct.approved_at_plan: + return req # the starter's own request needs nobody: what the sender's needs is the answer + if req.approved_at_plan: + return replace(direct, reasons=(*direct.reasons, "delegated change requires the starter's approvals")) + # Both need approvers: every slot of each. In a group that both name, the larger count covers both. + slots = {slot.group: slot for slot in req.slots} + for slot in direct.slots: + if slot.group not in slots or slot.count > slots[slot.group].count: + slots[slot.group] = slot + return replace(direct, slots=tuple(slots.values()), reasons=tuple(dict.fromkeys((*direct.reasons, *req.reasons)))) + + def _requirement(self, facts: Mapping[str, Any], paused: bool, team_auto_today: int) -> Requirement: env = facts["environment"] if env not in self.environments: # Pipeline._decide refuses first, with the serving instance's URLs (#671) raise Problem.unprocessable("environment-not-served", f"No approval rules for {env}") diff --git a/cmapi/src/cmapi/core/git/gitea.py b/cmapi/src/cmapi/core/git/gitea.py index 639d57e0..0bfa9e3f 100644 --- a/cmapi/src/cmapi/core/git/gitea.py +++ b/cmapi/src/cmapi/core/git/gitea.py @@ -204,13 +204,23 @@ def delete_branch(self, branch: str, expected: str) -> bool: r = self._call("delete_branch", "DELETE", f"{self._repo()}/branches/{quote(branch)}", ok=(204, 404)) return r.status_code in (204, 404) + def _list_pages(self, operation: str, resource: str, **filters: str) -> Iterator[dict[str, Any]]: + path = f"{self._repo()}/{resource}" + for page in count(1): + response = self._call(operation, "GET", path, params={**filters, "limit": 50, "page": page}) + if response.status_code != 200: + raise GitUnavailable(f"{operation}: GET {path} page {page}: HTTP {response.status_code}") + yield from response.json() + if "next" not in response.links: + return + def list_open(self, prefix: str) -> list[PrRef]: - r = self._call("find_pr", "GET", f"{self._repo()}/pulls", params={"state": "open", "limit": 50}) - return [self._pr_ref(p) for p in r.json() if p["head"]["ref"].startswith(prefix)] + return [self._pr_ref(p) for p in self._list_pages("find_pr", "pulls", state="open") + if p["head"]["ref"].startswith(prefix)] def list_branches(self, prefix: str) -> dict[str, str]: - r = self._call("branches", "GET", f"{self._repo()}/branches", params={"limit": 50}) - return {b["name"]: b["commit"]["id"] for b in r.json() if b["name"].startswith(prefix)} + return {b["name"]: b["commit"]["id"] for b in self._list_pages("branches", "branches") + if b["name"].startswith(prefix)} def branch_time(self, sha: str) -> int: from datetime import datetime diff --git a/cmapi/src/cmapi/core/operations.py b/cmapi/src/cmapi/core/operations.py index fd30aa24..381c54ea 100644 --- a/cmapi/src/cmapi/core/operations.py +++ b/cmapi/src/cmapi/core/operations.py @@ -24,7 +24,7 @@ - Runs start only through cmapi, which records an operations row: `Operations.start`, from POST /api/v1/operations. - No pause nodes: a step that needs approval opens a request and polls it (StepResult.wait). - Steps act as svc-cmapi-workflows, and every request they open records that client and the person who started the run - (`StepContext.actor`, `StepContext.requester`). + (`StepContext.actor`, `StepContext.starter`; `Pipeline.plan_namespace(starter, ..., submitted_by=actor)`). The design decisions, with their sources: docs/reviews/2026-12-01-issue-26-operations/design.md. """ @@ -45,7 +45,6 @@ from cmapi.core.db.models import JobRow, OperationRow, OperationStepRow from cmapi.core.db.repo import JobRepo, utcnow from cmapi.core.errors import Problem -from cmapi.core.identity.checks import Requester from cmapi.core.identity.claims import Identity from cmapi.core.observability import OPERATION_RUNS, log @@ -365,8 +364,11 @@ def advance(s: Session, engine: BuiltinEngine) -> None: rows within the caps, and end a run that has nothing left in flight.""" lock_engine(s) s.flush() + # populate_existing: a step's job loaded its run before the step ran, and a cancel may have committed since. Without it + # the ORM keeps the row it holds, and this pass would start the next step, or end the run Succeeded, of a cancelled run. runs = list(s.scalars(select(OperationRow).where(OperationRow.finished_at.is_(None)) - .order_by(OperationRow.started_at, OperationRow.operation_id).with_for_update())) + .order_by(OperationRow.started_at, OperationRow.operation_id).with_for_update() + .execution_options(populate_existing=True))) for op in runs: template = engine.templates.get(op.template) if template is None: @@ -482,13 +484,14 @@ def _end_if_done(s: Session, op: OperationRow, template: OperationTemplate) -> N phase = "Failed" # a step failed, so the steps after it never ran else: phase = "Succeeded" - _finish(s, op, phase, None) + _finish(s, op, phase, None, template) -def _finish(s: Session, op: OperationRow, phase: str, error: str | None) -> None: +def _finish(s: Session, op: OperationRow, phase: str, error: str | None, + template: OperationTemplate | None = None) -> None: now = utcnow() op.phase, op.finished_at, op.updated_at = phase, now, now - op.report = build_report(op, _rows(s, op.operation_id), error) + op.report = build_report(_rows(s, op.operation_id), error, template) log.info("operation_finished", operation_id=op.operation_id, template=op.template, phase=phase) OPERATION_RUNS.labels(op.template, op.engine, phase).inc() @@ -505,10 +508,11 @@ def _final(row: OperationStepRow, phase: str, *, note: str | None = None, error: row.last_error = error[:2000] -def build_report(op: OperationRow, rows: list[OperationStepRow], error: str | None) -> dict[str, Any]: +def build_report(rows: list[OperationStepRow], error: str | None, template: OperationTemplate | None) -> dict[str, Any]: """What the run did, by step: how many rows ended in each phase, and each item that did not succeed with why.""" steps: dict[str, dict[str, Any]] = {} - for r in sorted(rows, key=lambda r: (r.started_at or op.started_at, r.step, r.item)): + order = {step.name: i for i, step in enumerate(template.steps)} if template else {} + for r in sorted(rows, key=lambda r: (order.get(r.step, len(order)), r.step, r.item)): st = steps.setdefault(r.step, {"step": r.step, "phases": {}, "items": []}) st["phases"][r.phase] = st["phases"].get(r.phase, 0) + 1 # An item that did not succeed, and one that succeeded with something to read (rebuild-verify's drift). @@ -603,16 +607,15 @@ def actor(self) -> Identity: return Identity(sub=WORKFLOWS_CLIENT, username=WORKFLOWS_CLIENT, kind="service", client_id=WORKFLOWS_CLIENT, roles=st.roles) - @property - def requester(self) -> Requester: - """The person who started the run, sent by svc-cmapi-workflows: both are recorded (docs/02, rule 4), and the ledger - refuses the starter as an approver (docs/01, "Approval of record").""" - return Requester(person=self.starter, caller=self.actor, automated=True) - @property def key(self) -> str: """The Idempotency-Key of the request this row opens: one per row, so a step that runs again finds its request.""" - return f"{self.operation.operation_id}/{self.row.step}/{self.row.item}" + raw = f"{self.operation.operation_id}/{self.row.step}/{self.row.item}" + # change_requests.idempotency_key holds 100 characters, and a cluster ID and a namespace are up to 63 each. A key that + # fits stays readable; a longer one is its hash, which is as stable and as distinct. + if len(raw) <= 100: + return raw + return "op-step:" + hashlib.sha256(raw.encode()).hexdigest() def starter_identity(record: Mapping[str, Any]) -> Identity: @@ -657,6 +660,14 @@ def run_step(ctx: Any, s: Session, job: JobRow) -> None: job_transaction = s.get_transaction() try: with s.begin_nested(): # a step that raises leaves nothing it wrote + # The run acts, and is read, where its start was authorized (operations.environments; design.md, D9). A cluster + # that clusters.yaml moved to another environment since is refused: its report would be read under the old one. + cluster = row.cluster_id or op.parameters.get("cluster-id") + if cluster and op.environments is not None: + current = ctx.registry.clusters.get(cluster) + if current is None or current.environment not in op.environments: + raise StepRefused(f"{cluster} is not in the environments this run was started for " + f"({', '.join(op.environments)}): start it again") if step.not_built: raise StepRefused(f"{row.step} is not built yet ({step.not_built}); the steps before it ran") result = STEPS[(template.name, row.step)](sc) diff --git a/cmapi/src/cmapi/core/pipeline.py b/cmapi/src/cmapi/core/pipeline.py index c348f0bb..e6c3c27c 100644 --- a/cmapi/src/cmapi/core/pipeline.py +++ b/cmapi/src/cmapi/core/pipeline.py @@ -271,18 +271,20 @@ def workload_counts(self, cluster_id: str, ns: str) -> tuple[int, int]: # ---- plan a create or update def plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any], *, action: str, - if_match: str | None = None, reason: str | None = None, requester: Requester | None = None) -> Plan: - """`requester`: who the request is for, when the caller already knows it (an operation's step: the person who started - the run, sent by svc-cmapi-workflows, docs/02 rule 4). Otherwise it is resolved from `who` and `onBehalfOf`.""" + if_match: str | None = None, reason: str | None = None, submitted_by: Identity | None = None) -> Plan: + """`submitted_by`: the client that sends the request for `who`, when it is not `who` (an operation's step: `who` is + the person who started the run and `submitted_by` is svc-cmapi-workflows, docs/02 rule 4). `who` is checked as on + their own request: the permission, the identity rules (requester_for) and the approval rules. The approval rules + are also decided for the sender, and the request must satisfy both (ApprovalRules.decide; design.md, D3).""" try: return self._plan_namespace(who, cluster_id, body, action=action, if_match=if_match, reason=reason, - requester=requester) + submitted_by=submitted_by) except Problem as exc: count_refusal(exc) raise def _plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any], *, action: str, - if_match: str | None = None, reason: str | None = None, requester: Requester | None = None) -> Plan: + if_match: str | None = None, reason: str | None = None, submitted_by: Identity | None = None) -> Plan: st = self.registry.writable(cluster_id) env = st.policy.environment self.check_env_served(env) @@ -293,7 +295,8 @@ def _plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any if action == "create": check_name(ns, self.reserved) check_not_unmanaged(ns, cache.namespace(ns)) - requester = requester or self.requester_for(who, body.get("onBehalfOf")) + direct = self.requester_for(who, body.get("onBehalfOf")) + requester = Requester(direct.person, submitted_by, automated=True) if submitted_by else direct if action == "create": # The label is only written at create; refuse here, not as a 422 from the API server at apply. The refusal is # explicit: a ValueError that escapes a route is the service's fault, 500 internal-error (#648). @@ -436,8 +439,10 @@ def _plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any if action != "create": metadata_diff = self.cfg.metadata.metadata_diff(metadata_of(prev_ns), metadata_of(namespace_doc(files)), sent) findings = [*findings, *self._environment_moved(cluster_id, ns, prev_ns, env)] - if action == "update" and reason is None: - # A PATCH, whose body can add a key: the expiry calls (reason expiration:...) cannot, so they get no finding. + if action == "update" and (reason is None or submitted_by is not None): + # A PATCH, whose body can add a key: the expiry calls (reason expiration:...) cannot, so they get no finding. An + # operation's request is decided as its starter's own PATCH would be, so it carries the finding, and the warning + # keeps auto-approval from applying to it as it does to the PATCH. findings = [*findings, *self._held_key_findings(cluster_id, sources, labels, anns)] # Every change is sized from the quota that Git holds and the cluster enforces, never from the catalog (#710). A # namespace rendered from an older catalog is tier-outdated, and the change that renders it again is "an ordinary @@ -488,6 +493,13 @@ def _plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any # tier gives). It does not depend on the beyond-tier keys: a change to a tier with a higher value raises it too. exposure_base = hard if quotas_held else resolved.quota if action == "create" else old_hard raised = exposure_raised(exposure_base, hard) + if submitted_by: + # What the rules read about the sender, as the starter's own request would say it: decided beside the facts of + # the request as sent, which name the workflow client (ApprovalRules.decide). Stored with the plan, so the + # decision that submit takes again is the same one. + facts["starterApprovalFacts"] = {"automated": direct.automated, "requesterClient": facts["requesterClient"], + "reason": None} + facts["requesterClient"] = submitted_by.client_id facts.update({"beyondTier": bool(beyond), "beyondTierKeys": sorted(beyond), "networkExposure": bool(raised)}) requirement = self._decide(facts) beyond_view = self.beyond_view(facts, beyond) diff --git a/cmapi/src/cmapi/ops/__init__.py b/cmapi/src/cmapi/ops/__init__.py index 3fbbe9dd..87e08fa4 100644 --- a/cmapi/src/cmapi/ops/__init__.py +++ b/cmapi/src/cmapi/ops/__init__.py @@ -127,9 +127,9 @@ def rerender_namespace(sc: StepContext) -> StepResult: files, _ = ctx.pipeline.read_folder(cid, ns) from cmapi.core.pipeline import folder_etag try: - plan = ctx.pipeline.plan_namespace(sc.actor, cid, {"namespace": ns}, action="update", + plan = ctx.pipeline.plan_namespace(sc.starter, cid, {"namespace": ns}, action="update", if_match=f'"{folder_etag(files)}"', reason=RERENDER_REASON, - requester=sc.requester) + submitted_by=sc.actor) except Problem as exc: if exc.code == "no-change": return StepResult.skipped("Git already holds it rendered from the current catalog", outcome="current") diff --git a/cmapi/src/cmapi/routers/operations.py b/cmapi/src/cmapi/routers/operations.py index d8a7c04b..b8171b62 100644 --- a/cmapi/src/cmapi/routers/operations.py +++ b/cmapi/src/cmapi/routers/operations.py @@ -211,7 +211,7 @@ def _get(s: Any, operation_id: str, *, lock: bool = False) -> OperationRow: problems=["operation-template-unknown", "validation-failed", "environment-forbidden", "environment-not-served", "cluster-not-found", "policy-violation", "idempotency-key-required", "idempotency-replay", "operations-engine-unavailable"]) -def start(body: OperationStart, key: str = Depends(start_key), who: Identity = Depends(require(PERMISSION)), +def start(body: OperationStart, who: Identity = Depends(require(PERMISSION)), key: str = Depends(start_key), c: AppContext = Depends(ctx)) -> dict: """Starts a run of a template on the engine that integrations.yaml names. The answer comes before any step runs; read `GET /api/v1/operations/{id}` for its progress. A step that changes a namespace opens an ordinary request, which the @@ -220,22 +220,30 @@ def start(body: OperationStart, key: str = Depends(start_key), who: Identity = D from cmapi.ops import START_CHECKS c.operations.check_available() - template = c.operations.template(body.template) - params = template.validate(body.parameters) - environments = _environments(c, template, params) - for permission in (PERMISSION, *template.permissions): - _require(c, who, permission, environments) - if template.name in START_CHECKS: - START_CHECKS[template.name](c, params) sent = fingerprint({"template": body.template, "parameters": body.parameters}) with c.db.session() as s: + # The engine's lock before the key is read: of two starts with one key at the same moment, the second waits here and + # then finds the first one's run. Without it both miss the key, and the second insert breaks uq_op_idempotency (500). + lock_engine(s) held = s.scalars(select(OperationRow).where(OperationRow.started_by_sub == who.sub, OperationRow.idempotency_key == key)).first() if held is not None: + # A replay is a read of the run it started: checked where that run acts, as GET is, before the run or its ID + # is returned. The caller's grant may be narrower now than when it started the run (design.md, D13). + _require(c, who, PERMISSION, held.environments) if held.idempotency_fingerprint != sent: raise Problem.conflict("idempotency-replay", "Idempotency-Key was used for a different operation", operationId=held.operation_id) + for permission in c.operations.template(held.template).permissions: + _require(c, who, permission, held.environments) return _full(c, s, held) + template = c.operations.template(body.template) + params = template.validate(body.parameters) + environments = _environments(c, template, params) + for permission in (PERMISSION, *template.permissions): + _require(c, who, permission, environments) + if template.name in START_CHECKS: + START_CHECKS[template.name](c, params) op_id = new_operation_id() row = OperationRow(operation_id=op_id, template=template.name, parameters=params, engine=c.operations.engine.name, run_name=op_id, phase="Pending", environments=environments, started_by_sub=who.sub, diff --git a/cmapi/tests/service/test_api_standard.py b/cmapi/tests/service/test_api_standard.py index d9c143b5..0987efe2 100644 --- a/cmapi/tests/service/test_api_standard.py +++ b/cmapi/tests/service/test_api_standard.py @@ -44,7 +44,7 @@ SCALARS = ("string", "integer", "number", "boolean") # S1: a summary starts with what the caller does. A new kind of operation adds its verb here. VERBS = {"Adopt", "Approve", "Cancel", "Change", "Confirm", "Create", "Delete", "Export", "Extend", "Get", "Give", "List", "Pause", - "Place", "Probe", "Reject", "Remove", "Resume", "Retry", "Revert", "Run", "Search"} # Place, Run: #21 + "Place", "Probe", "Reject", "Remove", "Resume", "Retry", "Revert", "Run", "Search", "Start"} # Place, Run: #21 # S3: the operations that need a token and no permission (GET /me is how a caller finds out what it may do). TOKEN_ONLY = {("get", "/api/v1/me")} # S7: the reads that answer 304 to a matching If-None-Match (routers/me.py, plugins/capacity/router.py). diff --git a/cmapi/tests/service/test_operations_26.py b/cmapi/tests/service/test_operations_26.py index f5613f8e..91bee74b 100644 --- a/cmapi/tests/service/test_operations_26.py +++ b/cmapi/tests/service/test_operations_26.py @@ -490,3 +490,34 @@ def run(*args): assert conn.execute("SELECT to_regclass('capacity_snapshots')").fetchone() != (None,) run("head") assert conn.execute("SELECT count(*) FROM operations").fetchone() == (0,) + + +def test_cancel_during_step_suppresses_its_successor(world, monkeypatch): + """Two DB sessions. Cancel commits while the worker holds the step row and has already read the run.""" + from concurrent.futures import ThreadPoolExecutor + from threading import Event + + from cmapi.core.operations import StepResult + from cmapi.ops import STEPS + + client, ctx, _, _, _, keys = world + op_id = start(world, "rebuild-verify", {"cluster-id": "CRC"}).json()["operationId"] + entered, resume = Event(), Event() + + def hold_first_step(sc): + entered.set() + assert resume.wait(10) + return StepResult.done(items=[]) + + monkeypatch.setitem(STEPS, ("rebuild-verify", "list-folders"), hold_first_step) + with ThreadPoolExecutor(max_workers=1) as pool: + worker = pool.submit(run_jobs, ctx, 1) + try: + assert entered.wait(10) + cancelled = client.post(f"{URL}/{op_id}:cancel", headers=auth(keys, "opal", **OPAL)) + assert cancelled.status_code == 200, cancelled.text + finally: + resume.set() + assert worker.result(timeout=10) == ["operation_step"] + view = get(world, op_id) + assert view["phase"] == "Stopped" and [row["step"] for row in view["steps"]] == ["list-folders"] diff --git a/cmapi/tests/service/test_operations_review_774.py b/cmapi/tests/service/test_operations_review_774.py new file mode 100644 index 00000000..7f613d9e --- /dev/null +++ b/cmapi/tests/service/test_operations_review_774.py @@ -0,0 +1,357 @@ +"""Focused operation regressions of the review of PR #774 (reviewer 1, then reviewer 2). The engine tests exercise the ORM +identity map on SQLite and stub only scheduler I/O; the tests that take `world` or build_world run on PostgreSQL.""" +from contextlib import nullcontext +from datetime import timedelta +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest +from sqlalchemy import JSON, MetaData, create_engine, select, update +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.orm import Session + +from cmapi import ops +from cmapi.core import operations as engine +from cmapi.core.approvals import ApprovalRules +from cmapi.core.authz import RolePolicy +from cmapi.core.db.models import ChangeRequestRow, JobRow, OperationRow, OperationStepRow +from cmapi.core.db.repo import fingerprint, utcnow +from cmapi.core.errors import Problem +from cmapi.core.identity.claims import Identity +from cmapi.core.pipeline import folder_etag +from cmapi.core.ports import CapacityResult +from cmapi.routers import operations as api +from conftest import build_world +from test_flow import NS, OPAL, auth + +STARTER = Identity("sub-opal", "opal", "user", "portal", employee_id="123", roles=frozenset(OPAL["roles"])) + + +@pytest.fixture +def runtime(monkeypatch): + db = create_engine("sqlite://") + schema = MetaData() + for model in (OperationRow, OperationStepRow): + table = model.__table__.to_metadata(schema) + for col in table.columns: + if isinstance(col.type, JSONB): + col.type = JSON() + schema.create_all(db) + monkeypatch.setattr(engine, "lock_engine", lambda session: None) + ctx = SimpleNamespace(operations=engine.Operations.from_integrations({"operations": {"builtin": {"maxConcurrentSteps": 1}}}), + registry=SimpleNamespace(clusters={"CRC": SimpleNamespace(environment="dev")})) + with Session(db) as session: + yield session, ctx + db.dispose() + + +def run_row(op_id="op-one", template="rebuild-verify"): + return OperationRow(operation_id=op_id, run_name=op_id, template=template, engine="builtin", phase="Running", + environments=["dev"], parameters={"cluster-id": "CRC", "parallelism": 2}, + started_by_sub=STARTER.sub, started_by=STARTER.record()) + + +def step_row(op_id, step, phase, item=""): + return OperationStepRow(operation_id=op_id, step=step, phase=phase, item=item, cluster_id="", attempts=0, + finished_at=utcnow() if phase == "Succeeded" else None) + + +def job_for(row): + return JobRow(kind=engine.STEP_JOB, payload={"operationId": row.operation_id, "step": row.step, "item": row.item}) + + +def test_advance_observes_a_cancel_recorded_after_worker_loaded_run(runtime): + session, ctx = runtime + run = run_row() + session.add_all([run, step_row(run.operation_id, "list-folders", "Succeeded")]) + session.commit() + session.refresh(run) # the worker loaded every column before entering its step function + # Database state of the cancel transaction at the instant the worker acquires the lock. + session.execute(update(OperationRow).values(cancel_requested_at=utcnow(), cancel_requested_by="opal") + .execution_options(synchronize_session=False)) + assert run.cancel_requested_at is None + engine.advance(session, ctx.operations.builtin) + assert run.phase == "Stopped" + assert list(session.scalars(select(OperationStepRow.step))) == ["list-folders"] + + +def test_worker_holds_cluster_steps_to_recorded_scope(runtime, monkeypatch): + session, ctx = runtime + run = run_row() + row = step_row(run.operation_id, "list-folders", "Running") + session.add_all([run, row]) + session.flush() + ctx.registry.clusters["CRC"].environment = "rnd" + handler = Mock(return_value=engine.StepResult.done(items=[])) + monkeypatch.setitem(ops.STEPS, (run.template, row.step), handler) + engine.run_step(ctx, session, job_for(row)) + handler.assert_not_called() + assert row.phase == "Failed" and run.phase == "Failed" + + +def test_cancel_report_preserves_template_order_for_unstarted_items(runtime): + session, ctx = runtime + run = run_row() + first = step_row(run.operation_id, "list-folders", "Succeeded") + pending = step_row(run.operation_id, "verify-namespace", "Pending", "example") + run.started_at = utcnow() - timedelta(minutes=2) + first.started_at = run.started_at + timedelta(seconds=1) + run.cancel_requested_at, run.cancel_requested_by = utcnow(), "opal" + session.add_all([run, first, pending]) + engine.advance(session, ctx.operations.builtin) + assert [entry["step"] for entry in run.report["steps"]] == ["list-folders", "verify-namespace"] + + +def test_step_keys_fit_the_request_column_and_preserve_existing_short_keys(): + op = run_row("op-20261201-01234567") + row = step_row(op.operation_id, "rerender-namespace", "Pending", "CRC/example") + sc = engine.StepContext(None, None, op, None, row) + assert sc.key == f"{op.operation_id}/{row.step}/{row.item}" + row.item = "c" * 63 + "/" + "n" * 63 + original = sc.key + assert len(original) <= ChangeRequestRow.idempotency_key.type.length + assert original == sc.key + row.item = row.item[:-1] + "x" + assert sc.key != original + + +def replay_context(held, monkeypatch): + session = Mock() + ctx = SimpleNamespace(db=SimpleNamespace(session=lambda: nullcontext(session)), + operations=engine.Operations.from_integrations({}), cfg=SimpleNamespace(roles=RolePolicy()), + registry=SimpleNamespace(clusters={"CRC": SimpleNamespace(environment="dev")}, get=Mock())) + monkeypatch.setattr(api, "_full", lambda c, s, row: row) + session.scalars.return_value.first.return_value = held + return session, ctx + + +def replay_input(): + body = api.OperationStart(template="rebuild-verify", parameters={"cluster-id": "CRC"}) + held = run_row() + held.idempotency_fingerprint = fingerprint(body.model_dump()) + return body, held + + +def test_start_reads_the_key_after_acquiring_the_scheduler_lock(monkeypatch): + body, held = replay_input() + session, ctx = replay_context(held, monkeypatch) + locked = Mock() + monkeypatch.setattr(api, "lock_engine", locked) + + def lookup(query): + locked.assert_called_once_with(session) + return SimpleNamespace(first=lambda: held) + session.scalars.side_effect = lookup + assert api.start(body, key="key", who=STARTER, c=ctx) is held + + +def test_replay_uses_the_stored_visibility_scope(monkeypatch): + body, held = replay_input() + held.environments = None + _, ctx = replay_context(held, monkeypatch) + monkeypatch.setattr(api, "lock_engine", lambda session: None) + ctx.cfg.roles = RolePolicy({"roles": {"cmapi-operator": {"environments": ["dev"]}}}) + with pytest.raises(Problem) as denied: + api.start(body, key="key", who=STARTER, c=ctx) + assert denied.value.status == 403 + + +def test_start_checks_permission_before_the_key(test_config, keys, monkeypatch): + with build_world(test_config, keys, monkeypatch) as (client, *_): + response = client.post("/api/v1/operations", json={"template": "reconcile"}, + headers={"Authorization": "Bearer " + keys.token("viewer", roles=["cmapi-viewer"])}) + assert response.status_code == 403 + + +@pytest.mark.parametrize("employee, expected", [(None, "identity-incomplete"), ("123", "approval")]) +def test_delegated_plan_preserves_starter_checks(employee, expected, test_config, keys, monkeypatch): + from dataclasses import replace + import yaml + + with build_world(test_config, keys, monkeypatch) as (_, ctx, git, *_): + monkeypatch.setattr(ctx.pipeline, "auto_paused", lambda session: False) + monkeypatch.setattr(ctx.pipeline.capacity, "check", lambda *args, **kwargs: CapacityResult("fits", True, None, {})) + files = ctx.pipeline.plan_namespace(STARTER, "CRC", NS, action="create").files + path = next(p for p in files if yaml.safe_load(files[p])["kind"] == "ResourceQuota") + quota = yaml.safe_load(files[path]) + quota["spec"]["hard"]["requests.cpu"] = "6" + files[path] = yaml.safe_dump(quota) + git.branches["main"].update(files) + raw = {"environments": {"dev": {"required": 1}}, "autoApproval": {"enabled": True, "policies": [ + {"name": "client-policy", "requester": {"clients": [engine.WORKFLOWS_CLIENT]}}]}} + monkeypatch.setattr(ctx.cfg, "approvals", ApprovalRules(raw)) + run = run_row(template="tiers-rerender") + run.started_by = {**replace(STARTER, employee_id=employee).record(), "roles": list(STARTER.roles)} + run.parameters = {"tier": "small", "environments": ["dev"]} + row = step_row(run.operation_id, "rerender-namespace", "Running", "CRC/payments-dev") + row.inputs = {"clusterId": "CRC", "namespace": NS["namespace"]} + sc = engine.StepContext(ctx, Mock(), run, None, row) + repo = Mock() + repo.open_for.return_value = repo.by_idempotency.return_value = None + monkeypatch.setattr(ops, "RequestRepo", lambda session: repo) + submit = Mock(return_value=SimpleNamespace(request_id="req-example", status="pending_approval")) + monkeypatch.setattr(ctx.pipeline, "submit", submit) + if expected == "identity-incomplete": + with pytest.raises(Problem) as refused: + ops.rerender_namespace(sc) + assert refused.value.code == expected + submit.assert_not_called() + else: + ops.rerender_namespace(sc) + actor, plan = submit.call_args.args[:2] + assert actor.client_id == engine.WORKFLOWS_CLIENT and plan.requester.sub == STARTER.sub + assert plan.requester.record()["submittedByClient"] == actor.client_id + for decision in (plan.requirement, ctx.pipeline._decide(plan.facts, team_auto_today=1)): + assert decision.auto is None and decision.total == 1 + + +def test_cancel_takes_the_engine_lock_before_locking_the_run(runtime, monkeypatch): + session, ctx = runtime + ctx.db = SimpleNamespace(session=lambda: nullcontext(session)) + ctx.cfg = SimpleNamespace(roles=RolePolicy()) + run = run_row() + session.add_all([run, step_row(run.operation_id, "list-folders", "Running")]) + session.flush() + locks = [] + monkeypatch.setattr(api, "lock_engine", lambda s: locks.append("engine")) + get_row = api._get + + def observe_get(s, operation_id, *, lock=False): + if lock: + locks.append("row") + return get_row(s, operation_id, lock=lock) + monkeypatch.setattr(api, "_get", observe_get) + monkeypatch.setattr(api, "AuditRepo", Mock()) + view = api.cancel(run.operation_id, who=STARTER, c=ctx) + assert view["cancelRequestedBy"] == STARTER.username + assert locks == ["engine", "row"] + + +def test_unavailable_engine_and_unknown_template_remain_distinct(monkeypatch): + _, ctx = replay_context(None, monkeypatch) + monkeypatch.setattr(api, "lock_engine", lambda s: None) + body = api.OperationStart(template="missing") + for backend, status, code in (("builtin", 422, "operation-template-unknown"), + ("tekton", 503, "operations-engine-unavailable")): + ctx.operations = engine.Operations.from_integrations({"operations": {"engine": backend}}) + with pytest.raises(Problem) as refused: + api.start(body, key="unused", who=STARTER, c=ctx) + assert (refused.value.status, refused.value.code) == (status, code) + + +def test_reconcile_reads_later_gitea_result_pages(monkeypatch): + import httpx + from cmapi.core.git.gitea import GiteaProvider + + git = GiteaProvider("https://example.test", "org/repo", "") + name = "cmapi/CRC/req-later" + + def page(operation, method, path, *, params): + number = params.get("page", 1) + branch = "main" if number == 1 else name + row = ({"name": branch, "commit": {"id": "sha"}} if path.endswith("/branches") else + {"number": 5, "head": {"ref": branch, "sha": "sha"}}) + return httpx.Response(200, headers={"Link": '; rel="next"'} if number == 1 else {}, json=[row]) + + monkeypatch.setattr(git, "_call", page) + try: + assert git.list_branches("cmapi/CRC/") == {name: "sha"} + assert [pr.branch for pr in git.list_open("cmapi/CRC/")] == [name] + finally: + git._client.close() + + +# --------------------------------------------------------------------------- reviewer 2 + + +def test_two_starts_with_one_key_at_once_start_one_run(world): + """Finding 7 on PostgreSQL. This connection holds the engine's lock while both POSTs arrive, so neither has read the key + when the other writes it. Released, one starts the run and the other answers with it; before, the second insert broke + uq_op_idempotency and the caller got a 500.""" + import time + from concurrent.futures import ThreadPoolExecutor + from sqlalchemy import text + + client, ctx, *_, keys = world + headers = {**auth(keys, "opal", **OPAL), "Idempotency-Key": "one-key-twice"} + body = {"template": "rebuild-verify", "parameters": {"cluster-id": "CRC"}} + with ctx.db.engine.connect() as holder, ThreadPoolExecutor(max_workers=2) as pool: + holder.execute(text("SELECT pg_advisory_lock(:k)"), {"k": engine._ENGINE_LOCK}) + try: + posts = [pool.submit(client.post, "/api/v1/operations", json=body, headers=headers) for _ in range(2)] + time.sleep(1.5) # both are waiting: on the lock, or (before) one on the other's insert + finally: + holder.execute(text("SELECT pg_advisory_unlock(:k)"), {"k": engine._ENGINE_LOCK}) + answers = [post.result(timeout=30) for post in posts] + assert [a.status_code for a in answers] == [202, 202], [a.text for a in answers] + assert answers[0].json()["operationId"] == answers[1].json()["operationId"] + with ctx.db.session() as session: + assert len(list(session.scalars(select(OperationRow)))) == 1 + + +WORKFLOW_FACTS = {"plugin": "namespaces", "action": "update", "environment": "dev", "namespace": "payments-dev", + "tier": "small", "capacity": "fits", "capacityFresh": True, "automated": True, + "requesterClient": engine.WORKFLOWS_CLIENT, "reason": ops.RERENDER_REASON, + "starterApprovalFacts": {"automated": False, "requesterClient": None, "reason": None}} +SENT_BY_WORKFLOWS = f'requesterClient == "{engine.WORKFLOWS_CLIENT}"' + + +@pytest.mark.parametrize("rules, auto, slots", [ + # A policy for the workflow client alone: the starter's own request needs one approver, so the delegated one does. + ({"autoApproval": {"enabled": True, "policies": [{"name": "workflows", "requester": {"clients": [engine.WORKFLOWS_CLIENT]}}]}}, + None, {"approver-platform": 1}), + # A policy that reads the operation's reason, which a person's request never has: the same. + ({"autoApproval": {"enabled": True, "policies": [{"name": "rerenders", "match": {"reason": ops.RERENDER_REASON}}]}}, + None, {"approver-platform": 1}), + # A policy that covers the starter's own request covers the delegated one. + ({"autoApproval": {"enabled": True, "policies": [{"name": "dev-changes", "match": {"actions": ["update"]}}]}}, + "auto:dev-changes", {}), + # A rule about the workflow client still adds its approvers: the larger count of a group both name. + ({"thresholds": [{"when": SENT_BY_WORKFLOWS, "add": 1}]}, None, {"approver-platform": 2}), + # A rule that only the starter's own request meets is kept, with the other group's slot beside it. + ({"thresholds": [{"when": "automated == False", "add": 2, "group": "approver-dev"}, + {"when": SENT_BY_WORKFLOWS, "add": 1}]}, None, {"approver-platform": 2, "approver-dev": 2}), + # The starter's policy does not cover the sender when a rule adds approvers for the sender. + ({"thresholds": [{"when": SENT_BY_WORKFLOWS, "add": 1}], + "autoApproval": {"enabled": True, "policies": [{"name": "dev-changes", "match": {"actions": ["update"]}}]}}, + None, {"approver-platform": 2}), +]) +def test_a_delegated_request_needs_what_the_starter_and_the_sender_each_need(rules, auto, slots): + """Finding 2's rule, on the rules alone: never fewer approvers than the starter's own request, and never fewer than the + request as the workflow client sends it.""" + decision = ApprovalRules({"environments": {"dev": {"required": 1}}, **rules}).decide(WORKFLOW_FACTS) + assert (decision.auto, {slot.group: slot.count for slot in decision.slots}) == (auto, slots) + + +def test_a_delegated_change_carries_the_held_key_warning_of_the_starters_own_change(test_config, keys, monkeypatch): + """Reviewer 2, finding 1. Git holds a namespace without a required key. The starter's own PATCH carries the + missing_required_key warning, and a warning keeps auto-approval from applying. The same change sent by an operation has + a reason, and a plan with a reason got no such finding: the policy that could not approve the PATCH approved it.""" + import yaml + + with build_world(test_config, keys, monkeypatch) as (_, ctx, git, *_): + monkeypatch.setattr(ctx.pipeline, "auto_paused", lambda session: False) + monkeypatch.setattr(ctx.pipeline.capacity, "check", lambda *args, **kwargs: CapacityResult("fits", True, None, {})) + files = ctx.pipeline.plan_namespace(STARTER, "CRC", NS, action="create").files + for path in list(files): + doc = yaml.safe_load(files[path]) + if doc["kind"] == "ResourceQuota": + doc["spec"]["hard"]["requests.cpu"] = "6" # an older catalog's value: the re-render changes it + if doc["kind"] == "Namespace": + del doc["metadata"]["annotations"]["cmapi.net/team-dl"] + files[path] = yaml.safe_dump(doc) + git.branches["main"].update(files) + raw = {"environments": {"dev": {"required": 1}}, "autoApproval": {"enabled": True, "policies": [ + {"name": "dev-changes", "match": {"plugin": "namespaces", "actions": ["update"]}}]}} + monkeypatch.setattr(ctx.cfg, "approvals", ApprovalRules(raw)) + etag = f'"{folder_etag(ctx.pipeline.read_folder("CRC", NS["namespace"])[0])}"' + body = {"namespace": NS["namespace"]} + own = ctx.pipeline.plan_namespace(STARTER, "CRC", body, action="update", if_match=etag) + assert any("cmapi.net/team-dl" in warning for warning in own.facts["warnings"]), own.facts["warnings"] + assert (own.requirement.auto, own.requirement.auto_fallback, own.requirement.total) == (None, "warnings", 1) + actor = Identity(engine.WORKFLOWS_CLIENT, engine.WORKFLOWS_CLIENT, "service", engine.WORKFLOWS_CLIENT, + roles=STARTER.roles) + sent = ctx.pipeline.plan_namespace(STARTER, "CRC", body, action="update", if_match=etag, reason=ops.RERENDER_REASON, + submitted_by=actor) + assert (sent.requirement.auto, sent.requirement.auto_fallback, sent.requirement.total) == (None, "warnings", 1) + assert sent.facts["warnings"] == own.facts["warnings"] diff --git a/cmapi/tests/service/test_usage_verdicts_310.py b/cmapi/tests/service/test_usage_verdicts_310.py index 6a286dab..bd28aa74 100644 --- a/cmapi/tests/service/test_usage_verdicts_310.py +++ b/cmapi/tests/service/test_usage_verdicts_310.py @@ -18,7 +18,7 @@ import conftest # noqa: E402 from cmapi.capacity.sweep import VerdictRepo, run_sweep # noqa: E402 from cmapi.capacity.usage import EXPECTED_STEPS, PromUsage # noqa: E402 -from cmapi.core.db import Database # noqa: E402 +from cmapi.core.db import Database, REQUIRED_REVISION # noqa: E402 from cmapi.core.db.models import AnalysisSweepRow, NamespaceVerdictRow # noqa: E402 from cmapi.core.db.repo import JobRepo # noqa: E402 from test_flow import NS, OLA, auth, run_jobs # noqa: E402 @@ -323,7 +323,6 @@ def test_a_database_at_0009_is_behind_this_code(monkeypatch): db = Database(conftest.DB_URL) monkeypatch.setattr(db, "schema_version", lambda: "0009") try: - # Since #21 the code needs 0012 (capacity_snapshots, placement holds); a 0009 schema is still behind, now by three. - assert db.schema_status() == "behind: at 0009, needs 0012" + assert db.schema_status() == f"behind: at 0009, needs {REQUIRED_REVISION}" finally: db.engine.dispose() diff --git a/docs/14-authorization.md b/docs/14-authorization.md index d4e55259..558dd9b5 100644 --- a/docs/14-authorization.md +++ b/docs/14-authorization.md @@ -63,7 +63,7 @@ A role is a client role on the client of the instance: `cmapi-nonprod`, `cmapi-s | `audit:export` | | | | | | | yes | | 0 | | `approvals:relay` | | | | | | | | yes | 0 | -`namespaces:protect` is what makes an operator (#366). No route declares it: the routes check it inside, in the environment of the object. It lets a caller set and remove the operator-only labels and annotations of `metadata-keys.yaml` (`cmapi.net/protected` and `do-not-delete`; a requester gets 403), cancel another person's request, and read employee IDs in the directory (`cmapi/src/cmapi/core/authz.py:160-166`, `cmapi/src/cmapi/core/pipeline.py:304`). It is a permission, not a role name: a role of `authz-roles.yaml` that inherits `cmapi-operator` is an operator, and a role that grants it in some environments makes an operator there only. A file that lists `permissions:` for `cmapi-operator` itself must name `namespaces:protect`, or that role is no longer an operator. +`namespaces:protect` is what makes an operator (#366). No route declares it: the routes check it inside, in the environment of the object. It lets a caller set and remove the operator-only labels and annotations of `metadata-keys.yaml` (`cmapi.net/protected` and `do-not-delete`; a requester gets 403), cancel another person's request, and read employee IDs in the directory (`cmapi/src/cmapi/core/authz.py:160-166`, `cmapi/src/cmapi/core/pipeline.py:307`). It is a permission, not a role name: a role of `authz-roles.yaml` that inherits `cmapi-operator` is an operator, and a role that grants it in some environments makes an operator there only. A file that lists `permissions:` for `cmapi-operator` itself must name `namespaces:protect`, or that role is no longer an operator. Each column name has the prefix `cmapi-` in Keycloak. An operator or an admin cannot approve with those roles alone: `requests:approve` is only in `cmapi-approver`. On CRC the group `app-cmapi-rbac-operator` also gives `cmapi-approver`. @@ -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:290`, `:598` | +| Create, change, delete or extend a namespace, or set or remove its expiry | The cluster's environment | `cmapi/src/cmapi/core/pipeline.py:292`, `:610` | | 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:715` | +| 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:727` | | 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` | @@ -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:358-385`). 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:376-377`) | | 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:376-377`). 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. @@ -313,7 +313,7 @@ The users filter of realm `cmapi` is `(uid=cmapi.*)` (`docs/15`, "The LDAP feder ### Tools that act for people -A tool signs in with the client credentials grant. It is a service client, or an account that holds a role in `identity.automationRoles`. The default role is `cmapi-onboarding`, and `cmapi-automation` holds it (`checks.py:1-15`; `docs/15`, "The clients"). The tool is the caller. Three cases follow (`checks.py:70-95`, called from `pipeline.py:296`): +A tool signs in with the client credentials grant. It is a service client, or an account that holds a role in `identity.automationRoles`. The default role is `cmapi-onboarding`, and `cmapi-automation` holds it (`checks.py:1-15`; `docs/15`, "The clients"). The tool is the caller. Three cases follow (`checks.py:70-95`, called from `pipeline.py:298`): | Case | What cmapi does | Source | |---|---|---| @@ -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:105` | -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:873`, `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:885`, `approvals.py:376-377`). 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:374-375`). 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:1405` | -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:368`), 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:365-368`. 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/21-usage-from-thanos.md b/docs/21-usage-from-thanos.md index 6588cd3e..ebb17803 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:678-688`), 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:690-700`), 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:261-267`) | -| 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:678-688`). 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:690-700`). 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 | @@ -215,7 +215,7 @@ they are kept. While any finding stands, `ThanosQuerier.query` refuses before it - **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`). - **A namespace create never queries Thanos.** Only a quota change on an existing namespace reads usage - (`cmapi/src/cmapi/core/pipeline.py:462-469`). A test creates a namespace on PostgreSQL with `usage.source: thanos` and both + (`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 usage `unavailable` (`cmapi/tests/service/test_reader_thanos_grants_724.py:428-470`). diff --git a/docs/citations.lock.json b/docs/citations.lock.json index 1a1ac2b2..d679b1c6 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|358-385": [ " 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|365-368": [ " 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|368-368": [ " 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|374-375": [ " 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|376-377": [ " if approver.sub == self.requester_sub and not self.requirement.self_approval:", " raise Problem.conflict(\"self-approval\", \"Requesters cannot approve their own request here\")" ], @@ -504,22 +504,22 @@ " self.identity.get(\"requireOnBehalfOf\", False),", " self.identity.get(\"automationRoles\", [\"cmapi-onboarding\"]))" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|290-290": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|292-292": [ " self.cfg.roles.require(who, \"namespaces:create\" if action == \"create\" else \"namespaces:write\", env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|296-296": [ - " requester = requester or self.requester_for(who, body.get(\"onBehalfOf\"))" + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|298-298": [ + " direct = self.requester_for(who, body.get(\"onBehalfOf\"))" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|304-304": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|307-307": [ " operator = self.cfg.roles.is_operator(who, env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|598-598": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|610-610": [ " self.cfg.roles.require(who, \"namespaces:write\", env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|715-715": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|727-727": [ " self.cfg.roles.require(who, ADOPT_PERMISSION, env)" ], - "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|873-873": [ + "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|885-885": [ " 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|105-105": [ @@ -1559,7 +1559,7 @@ " return (len(client.list(\"Pod\", namespace=ns)[\"items\"]),", " len(client.list(\"PersistentVolumeClaim\", namespace=ns)[\"items\"]))" ], - "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|462-469": [ + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|467-474": [ " # A quota change on an existing namespace reads its live 14-day usage (docs/01, \"Quota changes on existing namespaces\");", " # nothing else does: \"Never queried while creating a namespace or setting its first quota\" (docs/01, Thanos on onboarding).", " usage_view, usage_facts = None, {}", @@ -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|678-688": [ + "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|690-700": [ " 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/docs/reviews/2026-12-01-issue-26-operations/README.md b/docs/reviews/2026-12-01-issue-26-operations/README.md new file mode 100644 index 00000000..e24d350b --- /dev/null +++ b/docs/reviews/2026-12-01-issue-26-operations/README.md @@ -0,0 +1,30 @@ +# PR #774 review: #26 criterion 3, the built-in operations engine (first slice) + +Who did what: +- Implementer: Opus 5.5 at high. The design is in [design.md](design.md), decisions D1 to D14. +- Reviewer 1: Codex (gpt-6.2-astra, xhigh). Its [report](reviewer-1-codex.md) has 13 findings, 7 of them High. +- Reviewer 2: Fable. [report](reviewer-2-fable.md); the applied [final.diff](final.diff) was made against the pristine head `703da75d`. +- Coordinator: Opus 5.5. It read the production hunks line by line and confirmed the applied tree is byte-identical to reviewer 2's tested tree. + +| # | Codex finding | Ruling | +|---|---|---| +| 1 | The starter's identity checks were skipped | Accepted | +| 2 | A delegated change could be auto-approved where the starter's own would need a person | Accepted. It is decided both as sent and as the starter's own request, and must satisfy both (RFC 8693 §1.1) | +| 3 | A replay returned a run outside the caller's current scope | Accepted | +| 4 | A cluster moved to another environment mid-run | Accepted | +| 5 | A cancel committed after a worker loaded the run (it ended Succeeded) | Accepted (`populate_existing`). A two-session PostgreSQL test fails on the head | +| 6 | A Waiting row should hold a slot | Rejected: D2 says a Waiting row holds no slot, and the fix doubles the jobs per poll under the engine lock | +| 7 to 13 | Start races, the step key's length, Gitea paging, the report's order, permission checked before the key, the API standard's verb, the revision assertion | Accepted | + +Reviewer 2's own findings: +- R2-1 (Medium): an operation's PATCH lacked the missing-required-key warning, so a namespace-update policy could auto-approve it. Fixed. +- R2-2: Codex's patch broke the citation check. Fixed. +- R2-3: design.md was updated to match. + +Tests, run by reviewer 2 on PostgreSQL 16.15, one file at a time: +- `test_operations_26.py`: before, 1 failed and 20 passed; after, 21 passed. +- `test_operations_review_774.py`: before, 15 failed and 5 passed; after, 20 passed. +- `test_api_standard.py`: 177 passed. +- The migration round trip (0013 up, down, up) passes, and so does the worker-crash test. + +Not tested: kind, CRC, two worker pods. Four Low observations from reviewer 2 are filed together in one Backlog issue. diff --git a/docs/reviews/2026-12-01-issue-26-operations/design.md b/docs/reviews/2026-12-01-issue-26-operations/design.md index bb94ce2e..c29ea948 100644 --- a/docs/reviews/2026-12-01-issue-26-operations/design.md +++ b/docs/reviews/2026-12-01-issue-26-operations/design.md @@ -42,6 +42,9 @@ one row per item, capped per cluster." So: queued for later. `maxConcurrentSteps` (integrations.yaml, default 4) counts only the rows `Running` across every run: the jobs that are due or running now. docs/02: "separate from request jobs, so operations never starve them". A run of 500 namespaces therefore never puts 500 due jobs ahead of the request jobs. + A Waiting row's poll, and the next attempt of a retry after its backoff, run without taking a slot (review of #774, + reviewer 1's finding 6, not taken): each is the row's one job, a fan-out's `parallelism` bounds how many rows of a run + wait, and a second job to admit each poll would double the jobs the cap is there to keep down. ## D3. The step's identity: delegation, not impersonation @@ -53,9 +56,24 @@ from B", where impersonation makes A "indistinguishable from B in that context". - The step acts as `svc-cmapi-workflows` (`StepContext.actor`), a service identity of its own, holding the roles of the token that started the run (stored in `operations.started_by`). A step can do no more than its starter could, in the environments where the starter could (a confused deputy is not possible), and a plan checks `namespaces:write` against those roles. -- Each request it opens has the starter as its requester and the step's client as the sender (`StepContext.requester`): - `requester_username` and `requester_sub` are the starter's, `requester_kind` is `service`, `requester_client` and - `requester.submittedByClient` are `svc-cmapi-workflows`, and `automated` is true. +- Each request it opens has the starter as its requester and the step's client as the sender + (`Pipeline.plan_namespace(starter, ..., submitted_by=actor)`): `requester_username` and `requester_sub` are the starter's, + `requester_kind` is `service`, `requester_client` and `requester.submittedByClient` are `svc-cmapi-workflows`, and + `automated` is true. +- The plan checks the starter as it checks the starter's own request (review of #774): the permission, and the identity + rules of `resolve_requester` (a token with no `employee_id` where the instance requires one is 422 `identity-incomplete`, + and the step's row is Failed with it). +- The approval rules decide the request twice (`ApprovalRules.decide`, review of #774): as sent (`automated` true, + `requesterClient` `svc-cmapi-workflows`, the operation's `reason`), and as the starter's own request (the plan's + `starterApprovalFacts`: the starter's `automated` and client, and no `reason`). The request must satisfy both: where both + need approvers, every slot of each, with the larger count in a group both name. So an operation never gets an approval + that the starter's own request would not get. An auto-approval policy that names `svc-cmapi-workflows` in + `requester.clients`, or the operation's reason in `match.reason`, cannot approve alone what the starter's request needs a + person for. A rule that reads the sender can still add approvers to an operation's requests. This is the delegation of + RFC 8693, section 1.1: "while B may have delegated some of its rights to A, any actions taken are being taken by A + representing B" (fetched 2026-12-01); the rights are B's, the starter's, and no more. +- The plan of an operation's change carries the `missing_required_key` warning of a namespace that lacks a required key, + as the starter's own PATCH does, so the warning guard of auto-approval holds for both (`Pipeline._plan_namespace`). - The approval ledger refuses the requester's subject as an approver, so the starter cannot approve the requests of the run where the environment forbids self-approval. docs/01, "Approval of record": the approver is "not the person who started the operation". Where an environment allows self-approval (rnd and dev in the examples), the same rule as for a person's own @@ -183,6 +201,10 @@ MAY be used in conjunction with an idempotency key". The start requires the head fingerprint of the template and the parameters: the same caller, key and body get the run it started for as long as the run is kept; the same key with another body is 409 `idempotency-replay`. The header's description in the API says so. +A replay is a read of the run, so it is checked as `GET /api/v1/operations/{id}` is (D9): `operations:run`, and the +template's own permissions, where the stored run acts, before the run or its ID is returned (review of #774). The key is +read under the engine's lock, so two starts with one key at the same moment start one run and both answer with it. + ## D14. Smaller choices - Operation IDs are `op-YYYYMMDD-<8 hex>`, random like a placement's ID, so a start takes no day lock. @@ -193,6 +215,13 @@ kept; the same key with another body is 409 `idempotency-replay`. The header's d namespace with no ResourceQuota that cmapi rendered (an adopted one) is not selected. - "a decrease below current use is skipped": the live quota's `status.used` against the plan's new hard values, through `TierCatalog.compare`'s `below_used`. +- A step about a cluster runs only while the cluster is in the environments recorded at the start (`operations.environments`, + D9); a cluster that clusters.yaml moved to another environment since fails the step, so a report is never read under an + environment's grant that no longer covers its cluster (review of #774). +- A step's Idempotency-Key is `//` when that fits the 100 characters of + `change_requests.idempotency_key`, and `op-step:` with its SHA-256 otherwise (a cluster ID and a namespace are up to 63 + characters each). +- The report lists the steps in the template's order, then the items by name. - The requests a run opens do not take tokens from the team's rate-limit bucket (`team_request`, #689), which counts the writes of callers of the API. A run is bounded by its own caps instead: `batchSize` and `maxOpenPerCluster` (D10). - The locks, in one order everywhere: a step's job locks its own row, then the engine's advisory lock, then the runs' rows; a diff --git a/docs/reviews/2026-12-01-issue-26-operations/final.diff b/docs/reviews/2026-12-01-issue-26-operations/final.diff new file mode 100644 index 00000000..cbb1b39e --- /dev/null +++ b/docs/reviews/2026-12-01-issue-26-operations/final.diff @@ -0,0 +1,997 @@ +diff --git a/cmapi/src/cmapi/core/approvals.py b/cmapi/src/cmapi/core/approvals.py +--- a/cmapi/src/cmapi/core/approvals.py ++++ b/cmapi/src/cmapi/core/approvals.py +@@ -17,7 +17,7 @@ + """ + from __future__ import annotations + +-from dataclasses import dataclass, field ++from dataclasses import dataclass, field, replace + from fnmatch import fnmatchcase + from pathlib import Path + from typing import Any, Mapping +@@ -168,6 +168,27 @@ + # ---- decide + def decide(self, facts: Mapping[str, Any], *, paused: bool = False, + team_auto_today: int = 0) -> Requirement: ++ """The approvals a request needs. A delegated request (an operation's step: sent by svc-cmapi-workflows for the ++ person who started the run) is decided twice: as sent, and as the starter's own request (`starterApprovalFacts` ++ replace the facts about the sender). It must satisfy both, so delegation never lowers what the starter's own request ++ needs (RFC 8693, section 1.1: the delegate acts with rights the starter delegated, no more), and a rule about the ++ workflow client or about automated requests still adds its approvers.""" ++ req = self._requirement(facts, paused, team_auto_today) ++ if "starterApprovalFacts" not in facts: ++ return req ++ direct = self._requirement({**facts, **facts["starterApprovalFacts"]}, paused, team_auto_today) ++ if direct.approved_at_plan: ++ return req # the starter's own request needs nobody: what the sender's needs is the answer ++ if req.approved_at_plan: ++ return replace(direct, reasons=(*direct.reasons, "delegated change requires the starter's approvals")) ++ # Both need approvers: every slot of each. In a group that both name, the larger count covers both. ++ slots = {slot.group: slot for slot in req.slots} ++ for slot in direct.slots: ++ if slot.group not in slots or slot.count > slots[slot.group].count: ++ slots[slot.group] = slot ++ return replace(direct, slots=tuple(slots.values()), reasons=tuple(dict.fromkeys((*direct.reasons, *req.reasons)))) ++ ++ def _requirement(self, facts: Mapping[str, Any], paused: bool, team_auto_today: int) -> Requirement: + env = facts["environment"] + if env not in self.environments: # Pipeline._decide refuses first, with the serving instance's URLs (#671) + raise Problem.unprocessable("environment-not-served", f"No approval rules for {env}") +diff --git a/cmapi/src/cmapi/core/git/gitea.py b/cmapi/src/cmapi/core/git/gitea.py +--- a/cmapi/src/cmapi/core/git/gitea.py ++++ b/cmapi/src/cmapi/core/git/gitea.py +@@ -204,13 +204,23 @@ + r = self._call("delete_branch", "DELETE", f"{self._repo()}/branches/{quote(branch)}", ok=(204, 404)) + return r.status_code in (204, 404) + ++ def _list_pages(self, operation: str, resource: str, **filters: str) -> Iterator[dict[str, Any]]: ++ path = f"{self._repo()}/{resource}" ++ for page in count(1): ++ response = self._call(operation, "GET", path, params={**filters, "limit": 50, "page": page}) ++ if response.status_code != 200: ++ raise GitUnavailable(f"{operation}: GET {path} page {page}: HTTP {response.status_code}") ++ yield from response.json() ++ if "next" not in response.links: ++ return ++ + def list_open(self, prefix: str) -> list[PrRef]: +- r = self._call("find_pr", "GET", f"{self._repo()}/pulls", params={"state": "open", "limit": 50}) +- return [self._pr_ref(p) for p in r.json() if p["head"]["ref"].startswith(prefix)] ++ return [self._pr_ref(p) for p in self._list_pages("find_pr", "pulls", state="open") ++ if p["head"]["ref"].startswith(prefix)] + + def list_branches(self, prefix: str) -> dict[str, str]: +- r = self._call("branches", "GET", f"{self._repo()}/branches", params={"limit": 50}) +- return {b["name"]: b["commit"]["id"] for b in r.json() if b["name"].startswith(prefix)} ++ return {b["name"]: b["commit"]["id"] for b in self._list_pages("branches", "branches") ++ if b["name"].startswith(prefix)} + + def branch_time(self, sha: str) -> int: + from datetime import datetime +diff --git a/cmapi/src/cmapi/core/operations.py b/cmapi/src/cmapi/core/operations.py +--- a/cmapi/src/cmapi/core/operations.py ++++ b/cmapi/src/cmapi/core/operations.py +@@ -24,7 +24,7 @@ + - Runs start only through cmapi, which records an operations row: `Operations.start`, from POST /api/v1/operations. + - No pause nodes: a step that needs approval opens a request and polls it (StepResult.wait). + - Steps act as svc-cmapi-workflows, and every request they open records that client and the person who started the run +- (`StepContext.actor`, `StepContext.requester`). ++ (`StepContext.actor`, `StepContext.starter`; `Pipeline.plan_namespace(starter, ..., submitted_by=actor)`). + + The design decisions, with their sources: docs/reviews/2026-12-01-issue-26-operations/design.md. + """ +@@ -45,7 +45,6 @@ + from cmapi.core.db.models import JobRow, OperationRow, OperationStepRow + from cmapi.core.db.repo import JobRepo, utcnow + from cmapi.core.errors import Problem +-from cmapi.core.identity.checks import Requester + from cmapi.core.identity.claims import Identity + from cmapi.core.observability import OPERATION_RUNS, log + +@@ -365,8 +364,11 @@ + rows within the caps, and end a run that has nothing left in flight.""" + lock_engine(s) + s.flush() ++ # populate_existing: a step's job loaded its run before the step ran, and a cancel may have committed since. Without it ++ # the ORM keeps the row it holds, and this pass would start the next step, or end the run Succeeded, of a cancelled run. + runs = list(s.scalars(select(OperationRow).where(OperationRow.finished_at.is_(None)) +- .order_by(OperationRow.started_at, OperationRow.operation_id).with_for_update())) ++ .order_by(OperationRow.started_at, OperationRow.operation_id).with_for_update() ++ .execution_options(populate_existing=True))) + for op in runs: + template = engine.templates.get(op.template) + if template is None: +@@ -482,13 +484,14 @@ + phase = "Failed" # a step failed, so the steps after it never ran + else: + phase = "Succeeded" +- _finish(s, op, phase, None) ++ _finish(s, op, phase, None, template) + + +-def _finish(s: Session, op: OperationRow, phase: str, error: str | None) -> None: ++def _finish(s: Session, op: OperationRow, phase: str, error: str | None, ++ template: OperationTemplate | None = None) -> None: + now = utcnow() + op.phase, op.finished_at, op.updated_at = phase, now, now +- op.report = build_report(op, _rows(s, op.operation_id), error) ++ op.report = build_report(_rows(s, op.operation_id), error, template) + log.info("operation_finished", operation_id=op.operation_id, template=op.template, phase=phase) + OPERATION_RUNS.labels(op.template, op.engine, phase).inc() + +@@ -505,10 +508,11 @@ + row.last_error = error[:2000] + + +-def build_report(op: OperationRow, rows: list[OperationStepRow], error: str | None) -> dict[str, Any]: ++def build_report(rows: list[OperationStepRow], error: str | None, template: OperationTemplate | None) -> dict[str, Any]: + """What the run did, by step: how many rows ended in each phase, and each item that did not succeed with why.""" + steps: dict[str, dict[str, Any]] = {} +- for r in sorted(rows, key=lambda r: (r.started_at or op.started_at, r.step, r.item)): ++ order = {step.name: i for i, step in enumerate(template.steps)} if template else {} ++ for r in sorted(rows, key=lambda r: (order.get(r.step, len(order)), r.step, r.item)): + st = steps.setdefault(r.step, {"step": r.step, "phases": {}, "items": []}) + st["phases"][r.phase] = st["phases"].get(r.phase, 0) + 1 + # An item that did not succeed, and one that succeeded with something to read (rebuild-verify's drift). +@@ -604,15 +608,14 @@ + roles=st.roles) + + @property +- def requester(self) -> Requester: +- """The person who started the run, sent by svc-cmapi-workflows: both are recorded (docs/02, rule 4), and the ledger +- refuses the starter as an approver (docs/01, "Approval of record").""" +- return Requester(person=self.starter, caller=self.actor, automated=True) +- +- @property + def key(self) -> str: + """The Idempotency-Key of the request this row opens: one per row, so a step that runs again finds its request.""" +- return f"{self.operation.operation_id}/{self.row.step}/{self.row.item}" ++ raw = f"{self.operation.operation_id}/{self.row.step}/{self.row.item}" ++ # change_requests.idempotency_key holds 100 characters, and a cluster ID and a namespace are up to 63 each. A key that ++ # fits stays readable; a longer one is its hash, which is as stable and as distinct. ++ if len(raw) <= 100: ++ return raw ++ return "op-step:" + hashlib.sha256(raw.encode()).hexdigest() + + + def starter_identity(record: Mapping[str, Any]) -> Identity: +@@ -657,6 +660,14 @@ + job_transaction = s.get_transaction() + try: + with s.begin_nested(): # a step that raises leaves nothing it wrote ++ # The run acts, and is read, where its start was authorized (operations.environments; design.md, D9). A cluster ++ # that clusters.yaml moved to another environment since is refused: its report would be read under the old one. ++ cluster = row.cluster_id or op.parameters.get("cluster-id") ++ if cluster and op.environments is not None: ++ current = ctx.registry.clusters.get(cluster) ++ if current is None or current.environment not in op.environments: ++ raise StepRefused(f"{cluster} is not in the environments this run was started for " ++ f"({', '.join(op.environments)}): start it again") + if step.not_built: + raise StepRefused(f"{row.step} is not built yet ({step.not_built}); the steps before it ran") + result = STEPS[(template.name, row.step)](sc) +diff --git a/cmapi/src/cmapi/core/pipeline.py b/cmapi/src/cmapi/core/pipeline.py +--- a/cmapi/src/cmapi/core/pipeline.py ++++ b/cmapi/src/cmapi/core/pipeline.py +@@ -271,18 +271,20 @@ + + # ---- plan a create or update + def plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any], *, action: str, +- if_match: str | None = None, reason: str | None = None, requester: Requester | None = None) -> Plan: +- """`requester`: who the request is for, when the caller already knows it (an operation's step: the person who started +- the run, sent by svc-cmapi-workflows, docs/02 rule 4). Otherwise it is resolved from `who` and `onBehalfOf`.""" ++ if_match: str | None = None, reason: str | None = None, submitted_by: Identity | None = None) -> Plan: ++ """`submitted_by`: the client that sends the request for `who`, when it is not `who` (an operation's step: `who` is ++ the person who started the run and `submitted_by` is svc-cmapi-workflows, docs/02 rule 4). `who` is checked as on ++ their own request: the permission, the identity rules (requester_for) and the approval rules. The approval rules ++ are also decided for the sender, and the request must satisfy both (ApprovalRules.decide; design.md, D3).""" + try: + return self._plan_namespace(who, cluster_id, body, action=action, if_match=if_match, reason=reason, +- requester=requester) ++ submitted_by=submitted_by) + except Problem as exc: + count_refusal(exc) + raise + + def _plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any], *, action: str, +- if_match: str | None = None, reason: str | None = None, requester: Requester | None = None) -> Plan: ++ if_match: str | None = None, reason: str | None = None, submitted_by: Identity | None = None) -> Plan: + st = self.registry.writable(cluster_id) + env = st.policy.environment + self.check_env_served(env) +@@ -293,7 +295,8 @@ + if action == "create": + check_name(ns, self.reserved) + check_not_unmanaged(ns, cache.namespace(ns)) +- requester = requester or self.requester_for(who, body.get("onBehalfOf")) ++ direct = self.requester_for(who, body.get("onBehalfOf")) ++ requester = Requester(direct.person, submitted_by, automated=True) if submitted_by else direct + if action == "create": + # The label is only written at create; refuse here, not as a 422 from the API server at apply. The refusal is + # explicit: a ValueError that escapes a route is the service's fault, 500 internal-error (#648). +@@ -436,8 +439,10 @@ + if action != "create": + metadata_diff = self.cfg.metadata.metadata_diff(metadata_of(prev_ns), metadata_of(namespace_doc(files)), sent) + findings = [*findings, *self._environment_moved(cluster_id, ns, prev_ns, env)] +- if action == "update" and reason is None: +- # A PATCH, whose body can add a key: the expiry calls (reason expiration:...) cannot, so they get no finding. ++ if action == "update" and (reason is None or submitted_by is not None): ++ # A PATCH, whose body can add a key: the expiry calls (reason expiration:...) cannot, so they get no finding. An ++ # operation's request is decided as its starter's own PATCH would be, so it carries the finding, and the warning ++ # keeps auto-approval from applying to it as it does to the PATCH. + findings = [*findings, *self._held_key_findings(cluster_id, sources, labels, anns)] + # Every change is sized from the quota that Git holds and the cluster enforces, never from the catalog (#710). A + # namespace rendered from an older catalog is tier-outdated, and the change that renders it again is "an ordinary +@@ -488,6 +493,13 @@ + # tier gives). It does not depend on the beyond-tier keys: a change to a tier with a higher value raises it too. + exposure_base = hard if quotas_held else resolved.quota if action == "create" else old_hard + raised = exposure_raised(exposure_base, hard) ++ if submitted_by: ++ # What the rules read about the sender, as the starter's own request would say it: decided beside the facts of ++ # the request as sent, which name the workflow client (ApprovalRules.decide). Stored with the plan, so the ++ # decision that submit takes again is the same one. ++ facts["starterApprovalFacts"] = {"automated": direct.automated, "requesterClient": facts["requesterClient"], ++ "reason": None} ++ facts["requesterClient"] = submitted_by.client_id + facts.update({"beyondTier": bool(beyond), "beyondTierKeys": sorted(beyond), "networkExposure": bool(raised)}) + requirement = self._decide(facts) + beyond_view = self.beyond_view(facts, beyond) +diff --git a/cmapi/src/cmapi/ops/__init__.py b/cmapi/src/cmapi/ops/__init__.py +--- a/cmapi/src/cmapi/ops/__init__.py ++++ b/cmapi/src/cmapi/ops/__init__.py +@@ -127,9 +127,9 @@ + files, _ = ctx.pipeline.read_folder(cid, ns) + from cmapi.core.pipeline import folder_etag + try: +- plan = ctx.pipeline.plan_namespace(sc.actor, cid, {"namespace": ns}, action="update", ++ plan = ctx.pipeline.plan_namespace(sc.starter, cid, {"namespace": ns}, action="update", + if_match=f'"{folder_etag(files)}"', reason=RERENDER_REASON, +- requester=sc.requester) ++ submitted_by=sc.actor) + except Problem as exc: + if exc.code == "no-change": + return StepResult.skipped("Git already holds it rendered from the current catalog", outcome="current") +diff --git a/cmapi/src/cmapi/routers/operations.py b/cmapi/src/cmapi/routers/operations.py +--- a/cmapi/src/cmapi/routers/operations.py ++++ b/cmapi/src/cmapi/routers/operations.py +@@ -211,7 +211,7 @@ + problems=["operation-template-unknown", "validation-failed", "environment-forbidden", "environment-not-served", + "cluster-not-found", "policy-violation", "idempotency-key-required", + "idempotency-replay", "operations-engine-unavailable"]) +-def start(body: OperationStart, key: str = Depends(start_key), who: Identity = Depends(require(PERMISSION)), ++def start(body: OperationStart, who: Identity = Depends(require(PERMISSION)), key: str = Depends(start_key), + c: AppContext = Depends(ctx)) -> dict: + """Starts a run of a template on the engine that integrations.yaml names. The answer comes before any step runs; read + `GET /api/v1/operations/{id}` for its progress. A step that changes a namespace opens an ordinary request, which the +@@ -220,22 +220,30 @@ + from cmapi.ops import START_CHECKS + + c.operations.check_available() +- template = c.operations.template(body.template) +- params = template.validate(body.parameters) +- environments = _environments(c, template, params) +- for permission in (PERMISSION, *template.permissions): +- _require(c, who, permission, environments) +- if template.name in START_CHECKS: +- START_CHECKS[template.name](c, params) + sent = fingerprint({"template": body.template, "parameters": body.parameters}) + with c.db.session() as s: ++ # The engine's lock before the key is read: of two starts with one key at the same moment, the second waits here and ++ # then finds the first one's run. Without it both miss the key, and the second insert breaks uq_op_idempotency (500). ++ lock_engine(s) + held = s.scalars(select(OperationRow).where(OperationRow.started_by_sub == who.sub, + OperationRow.idempotency_key == key)).first() + if held is not None: ++ # A replay is a read of the run it started: checked where that run acts, as GET is, before the run or its ID ++ # is returned. The caller's grant may be narrower now than when it started the run (design.md, D13). ++ _require(c, who, PERMISSION, held.environments) + if held.idempotency_fingerprint != sent: + raise Problem.conflict("idempotency-replay", "Idempotency-Key was used for a different operation", + operationId=held.operation_id) ++ for permission in c.operations.template(held.template).permissions: ++ _require(c, who, permission, held.environments) + return _full(c, s, held) ++ template = c.operations.template(body.template) ++ params = template.validate(body.parameters) ++ environments = _environments(c, template, params) ++ for permission in (PERMISSION, *template.permissions): ++ _require(c, who, permission, environments) ++ if template.name in START_CHECKS: ++ START_CHECKS[template.name](c, params) + op_id = new_operation_id() + row = OperationRow(operation_id=op_id, template=template.name, parameters=params, engine=c.operations.engine.name, + run_name=op_id, phase="Pending", environments=environments, started_by_sub=who.sub, +diff --git a/cmapi/tests/service/test_api_standard.py b/cmapi/tests/service/test_api_standard.py +--- a/cmapi/tests/service/test_api_standard.py ++++ b/cmapi/tests/service/test_api_standard.py +@@ -44,7 +44,7 @@ + SCALARS = ("string", "integer", "number", "boolean") + # S1: a summary starts with what the caller does. A new kind of operation adds its verb here. + VERBS = {"Adopt", "Approve", "Cancel", "Change", "Confirm", "Create", "Delete", "Export", "Extend", "Get", "Give", "List", "Pause", +- "Place", "Probe", "Reject", "Remove", "Resume", "Retry", "Revert", "Run", "Search"} # Place, Run: #21 ++ "Place", "Probe", "Reject", "Remove", "Resume", "Retry", "Revert", "Run", "Search", "Start"} # Place, Run: #21 + # S3: the operations that need a token and no permission (GET /me is how a caller finds out what it may do). + TOKEN_ONLY = {("get", "/api/v1/me")} + # S7: the reads that answer 304 to a matching If-None-Match (routers/me.py, plugins/capacity/router.py). +diff --git a/cmapi/tests/service/test_operations_26.py b/cmapi/tests/service/test_operations_26.py +--- a/cmapi/tests/service/test_operations_26.py ++++ b/cmapi/tests/service/test_operations_26.py +@@ -490,3 +490,34 @@ + assert conn.execute("SELECT to_regclass('capacity_snapshots')").fetchone() != (None,) + run("head") + assert conn.execute("SELECT count(*) FROM operations").fetchone() == (0,) ++ ++ ++def test_cancel_during_step_suppresses_its_successor(world, monkeypatch): ++ """Two DB sessions. Cancel commits while the worker holds the step row and has already read the run.""" ++ from concurrent.futures import ThreadPoolExecutor ++ from threading import Event ++ ++ from cmapi.core.operations import StepResult ++ from cmapi.ops import STEPS ++ ++ client, ctx, _, _, _, keys = world ++ op_id = start(world, "rebuild-verify", {"cluster-id": "CRC"}).json()["operationId"] ++ entered, resume = Event(), Event() ++ ++ def hold_first_step(sc): ++ entered.set() ++ assert resume.wait(10) ++ return StepResult.done(items=[]) ++ ++ monkeypatch.setitem(STEPS, ("rebuild-verify", "list-folders"), hold_first_step) ++ with ThreadPoolExecutor(max_workers=1) as pool: ++ worker = pool.submit(run_jobs, ctx, 1) ++ try: ++ assert entered.wait(10) ++ cancelled = client.post(f"{URL}/{op_id}:cancel", headers=auth(keys, "opal", **OPAL)) ++ assert cancelled.status_code == 200, cancelled.text ++ finally: ++ resume.set() ++ assert worker.result(timeout=10) == ["operation_step"] ++ view = get(world, op_id) ++ assert view["phase"] == "Stopped" and [row["step"] for row in view["steps"]] == ["list-folders"] +diff --git a/cmapi/tests/service/test_operations_review_774.py b/cmapi/tests/service/test_operations_review_774.py +new file mode 100644 +--- /dev/null ++++ b/cmapi/tests/service/test_operations_review_774.py +@@ -0,0 +1,357 @@ ++"""Focused operation regressions of the review of PR #774 (reviewer 1, then reviewer 2). The engine tests exercise the ORM ++identity map on SQLite and stub only scheduler I/O; the tests that take `world` or build_world run on PostgreSQL.""" ++from contextlib import nullcontext ++from datetime import timedelta ++from types import SimpleNamespace ++from unittest.mock import Mock ++ ++import pytest ++from sqlalchemy import JSON, MetaData, create_engine, select, update ++from sqlalchemy.dialects.postgresql import JSONB ++from sqlalchemy.orm import Session ++ ++from cmapi import ops ++from cmapi.core import operations as engine ++from cmapi.core.approvals import ApprovalRules ++from cmapi.core.authz import RolePolicy ++from cmapi.core.db.models import ChangeRequestRow, JobRow, OperationRow, OperationStepRow ++from cmapi.core.db.repo import fingerprint, utcnow ++from cmapi.core.errors import Problem ++from cmapi.core.identity.claims import Identity ++from cmapi.core.pipeline import folder_etag ++from cmapi.core.ports import CapacityResult ++from cmapi.routers import operations as api ++from conftest import build_world ++from test_flow import NS, OPAL, auth ++ ++STARTER = Identity("sub-opal", "opal", "user", "portal", employee_id="123", roles=frozenset(OPAL["roles"])) ++ ++ ++@pytest.fixture ++def runtime(monkeypatch): ++ db = create_engine("sqlite://") ++ schema = MetaData() ++ for model in (OperationRow, OperationStepRow): ++ table = model.__table__.to_metadata(schema) ++ for col in table.columns: ++ if isinstance(col.type, JSONB): ++ col.type = JSON() ++ schema.create_all(db) ++ monkeypatch.setattr(engine, "lock_engine", lambda session: None) ++ ctx = SimpleNamespace(operations=engine.Operations.from_integrations({"operations": {"builtin": {"maxConcurrentSteps": 1}}}), ++ registry=SimpleNamespace(clusters={"CRC": SimpleNamespace(environment="dev")})) ++ with Session(db) as session: ++ yield session, ctx ++ db.dispose() ++ ++ ++def run_row(op_id="op-one", template="rebuild-verify"): ++ return OperationRow(operation_id=op_id, run_name=op_id, template=template, engine="builtin", phase="Running", ++ environments=["dev"], parameters={"cluster-id": "CRC", "parallelism": 2}, ++ started_by_sub=STARTER.sub, started_by=STARTER.record()) ++ ++ ++def step_row(op_id, step, phase, item=""): ++ return OperationStepRow(operation_id=op_id, step=step, phase=phase, item=item, cluster_id="", attempts=0, ++ finished_at=utcnow() if phase == "Succeeded" else None) ++ ++ ++def job_for(row): ++ return JobRow(kind=engine.STEP_JOB, payload={"operationId": row.operation_id, "step": row.step, "item": row.item}) ++ ++ ++def test_advance_observes_a_cancel_recorded_after_worker_loaded_run(runtime): ++ session, ctx = runtime ++ run = run_row() ++ session.add_all([run, step_row(run.operation_id, "list-folders", "Succeeded")]) ++ session.commit() ++ session.refresh(run) # the worker loaded every column before entering its step function ++ # Database state of the cancel transaction at the instant the worker acquires the lock. ++ session.execute(update(OperationRow).values(cancel_requested_at=utcnow(), cancel_requested_by="opal") ++ .execution_options(synchronize_session=False)) ++ assert run.cancel_requested_at is None ++ engine.advance(session, ctx.operations.builtin) ++ assert run.phase == "Stopped" ++ assert list(session.scalars(select(OperationStepRow.step))) == ["list-folders"] ++ ++ ++def test_worker_holds_cluster_steps_to_recorded_scope(runtime, monkeypatch): ++ session, ctx = runtime ++ run = run_row() ++ row = step_row(run.operation_id, "list-folders", "Running") ++ session.add_all([run, row]) ++ session.flush() ++ ctx.registry.clusters["CRC"].environment = "rnd" ++ handler = Mock(return_value=engine.StepResult.done(items=[])) ++ monkeypatch.setitem(ops.STEPS, (run.template, row.step), handler) ++ engine.run_step(ctx, session, job_for(row)) ++ handler.assert_not_called() ++ assert row.phase == "Failed" and run.phase == "Failed" ++ ++ ++def test_cancel_report_preserves_template_order_for_unstarted_items(runtime): ++ session, ctx = runtime ++ run = run_row() ++ first = step_row(run.operation_id, "list-folders", "Succeeded") ++ pending = step_row(run.operation_id, "verify-namespace", "Pending", "example") ++ run.started_at = utcnow() - timedelta(minutes=2) ++ first.started_at = run.started_at + timedelta(seconds=1) ++ run.cancel_requested_at, run.cancel_requested_by = utcnow(), "opal" ++ session.add_all([run, first, pending]) ++ engine.advance(session, ctx.operations.builtin) ++ assert [entry["step"] for entry in run.report["steps"]] == ["list-folders", "verify-namespace"] ++ ++ ++def test_step_keys_fit_the_request_column_and_preserve_existing_short_keys(): ++ op = run_row("op-20261201-01234567") ++ row = step_row(op.operation_id, "rerender-namespace", "Pending", "CRC/example") ++ sc = engine.StepContext(None, None, op, None, row) ++ assert sc.key == f"{op.operation_id}/{row.step}/{row.item}" ++ row.item = "c" * 63 + "/" + "n" * 63 ++ original = sc.key ++ assert len(original) <= ChangeRequestRow.idempotency_key.type.length ++ assert original == sc.key ++ row.item = row.item[:-1] + "x" ++ assert sc.key != original ++ ++ ++def replay_context(held, monkeypatch): ++ session = Mock() ++ ctx = SimpleNamespace(db=SimpleNamespace(session=lambda: nullcontext(session)), ++ operations=engine.Operations.from_integrations({}), cfg=SimpleNamespace(roles=RolePolicy()), ++ registry=SimpleNamespace(clusters={"CRC": SimpleNamespace(environment="dev")}, get=Mock())) ++ monkeypatch.setattr(api, "_full", lambda c, s, row: row) ++ session.scalars.return_value.first.return_value = held ++ return session, ctx ++ ++ ++def replay_input(): ++ body = api.OperationStart(template="rebuild-verify", parameters={"cluster-id": "CRC"}) ++ held = run_row() ++ held.idempotency_fingerprint = fingerprint(body.model_dump()) ++ return body, held ++ ++ ++def test_start_reads_the_key_after_acquiring_the_scheduler_lock(monkeypatch): ++ body, held = replay_input() ++ session, ctx = replay_context(held, monkeypatch) ++ locked = Mock() ++ monkeypatch.setattr(api, "lock_engine", locked) ++ ++ def lookup(query): ++ locked.assert_called_once_with(session) ++ return SimpleNamespace(first=lambda: held) ++ session.scalars.side_effect = lookup ++ assert api.start(body, key="key", who=STARTER, c=ctx) is held ++ ++ ++def test_replay_uses_the_stored_visibility_scope(monkeypatch): ++ body, held = replay_input() ++ held.environments = None ++ _, ctx = replay_context(held, monkeypatch) ++ monkeypatch.setattr(api, "lock_engine", lambda session: None) ++ ctx.cfg.roles = RolePolicy({"roles": {"cmapi-operator": {"environments": ["dev"]}}}) ++ with pytest.raises(Problem) as denied: ++ api.start(body, key="key", who=STARTER, c=ctx) ++ assert denied.value.status == 403 ++ ++ ++def test_start_checks_permission_before_the_key(test_config, keys, monkeypatch): ++ with build_world(test_config, keys, monkeypatch) as (client, *_): ++ response = client.post("/api/v1/operations", json={"template": "reconcile"}, ++ headers={"Authorization": "Bearer " + keys.token("viewer", roles=["cmapi-viewer"])}) ++ assert response.status_code == 403 ++ ++ ++@pytest.mark.parametrize("employee, expected", [(None, "identity-incomplete"), ("123", "approval")]) ++def test_delegated_plan_preserves_starter_checks(employee, expected, test_config, keys, monkeypatch): ++ from dataclasses import replace ++ import yaml ++ ++ with build_world(test_config, keys, monkeypatch) as (_, ctx, git, *_): ++ monkeypatch.setattr(ctx.pipeline, "auto_paused", lambda session: False) ++ monkeypatch.setattr(ctx.pipeline.capacity, "check", lambda *args, **kwargs: CapacityResult("fits", True, None, {})) ++ files = ctx.pipeline.plan_namespace(STARTER, "CRC", NS, action="create").files ++ path = next(p for p in files if yaml.safe_load(files[p])["kind"] == "ResourceQuota") ++ quota = yaml.safe_load(files[path]) ++ quota["spec"]["hard"]["requests.cpu"] = "6" ++ files[path] = yaml.safe_dump(quota) ++ git.branches["main"].update(files) ++ raw = {"environments": {"dev": {"required": 1}}, "autoApproval": {"enabled": True, "policies": [ ++ {"name": "client-policy", "requester": {"clients": [engine.WORKFLOWS_CLIENT]}}]}} ++ monkeypatch.setattr(ctx.cfg, "approvals", ApprovalRules(raw)) ++ run = run_row(template="tiers-rerender") ++ run.started_by = {**replace(STARTER, employee_id=employee).record(), "roles": list(STARTER.roles)} ++ run.parameters = {"tier": "small", "environments": ["dev"]} ++ row = step_row(run.operation_id, "rerender-namespace", "Running", "CRC/payments-dev") ++ row.inputs = {"clusterId": "CRC", "namespace": NS["namespace"]} ++ sc = engine.StepContext(ctx, Mock(), run, None, row) ++ repo = Mock() ++ repo.open_for.return_value = repo.by_idempotency.return_value = None ++ monkeypatch.setattr(ops, "RequestRepo", lambda session: repo) ++ submit = Mock(return_value=SimpleNamespace(request_id="req-example", status="pending_approval")) ++ monkeypatch.setattr(ctx.pipeline, "submit", submit) ++ if expected == "identity-incomplete": ++ with pytest.raises(Problem) as refused: ++ ops.rerender_namespace(sc) ++ assert refused.value.code == expected ++ submit.assert_not_called() ++ else: ++ ops.rerender_namespace(sc) ++ actor, plan = submit.call_args.args[:2] ++ assert actor.client_id == engine.WORKFLOWS_CLIENT and plan.requester.sub == STARTER.sub ++ assert plan.requester.record()["submittedByClient"] == actor.client_id ++ for decision in (plan.requirement, ctx.pipeline._decide(plan.facts, team_auto_today=1)): ++ assert decision.auto is None and decision.total == 1 ++ ++ ++def test_cancel_takes_the_engine_lock_before_locking_the_run(runtime, monkeypatch): ++ session, ctx = runtime ++ ctx.db = SimpleNamespace(session=lambda: nullcontext(session)) ++ ctx.cfg = SimpleNamespace(roles=RolePolicy()) ++ run = run_row() ++ session.add_all([run, step_row(run.operation_id, "list-folders", "Running")]) ++ session.flush() ++ locks = [] ++ monkeypatch.setattr(api, "lock_engine", lambda s: locks.append("engine")) ++ get_row = api._get ++ ++ def observe_get(s, operation_id, *, lock=False): ++ if lock: ++ locks.append("row") ++ return get_row(s, operation_id, lock=lock) ++ monkeypatch.setattr(api, "_get", observe_get) ++ monkeypatch.setattr(api, "AuditRepo", Mock()) ++ view = api.cancel(run.operation_id, who=STARTER, c=ctx) ++ assert view["cancelRequestedBy"] == STARTER.username ++ assert locks == ["engine", "row"] ++ ++ ++def test_unavailable_engine_and_unknown_template_remain_distinct(monkeypatch): ++ _, ctx = replay_context(None, monkeypatch) ++ monkeypatch.setattr(api, "lock_engine", lambda s: None) ++ body = api.OperationStart(template="missing") ++ for backend, status, code in (("builtin", 422, "operation-template-unknown"), ++ ("tekton", 503, "operations-engine-unavailable")): ++ ctx.operations = engine.Operations.from_integrations({"operations": {"engine": backend}}) ++ with pytest.raises(Problem) as refused: ++ api.start(body, key="unused", who=STARTER, c=ctx) ++ assert (refused.value.status, refused.value.code) == (status, code) ++ ++ ++def test_reconcile_reads_later_gitea_result_pages(monkeypatch): ++ import httpx ++ from cmapi.core.git.gitea import GiteaProvider ++ ++ git = GiteaProvider("https://example.test", "org/repo", "") ++ name = "cmapi/CRC/req-later" ++ ++ def page(operation, method, path, *, params): ++ number = params.get("page", 1) ++ branch = "main" if number == 1 else name ++ row = ({"name": branch, "commit": {"id": "sha"}} if path.endswith("/branches") else ++ {"number": 5, "head": {"ref": branch, "sha": "sha"}}) ++ return httpx.Response(200, headers={"Link": '; rel="next"'} if number == 1 else {}, json=[row]) ++ ++ monkeypatch.setattr(git, "_call", page) ++ try: ++ assert git.list_branches("cmapi/CRC/") == {name: "sha"} ++ assert [pr.branch for pr in git.list_open("cmapi/CRC/")] == [name] ++ finally: ++ git._client.close() ++ ++ ++# --------------------------------------------------------------------------- reviewer 2 ++ ++ ++def test_two_starts_with_one_key_at_once_start_one_run(world): ++ """Finding 7 on PostgreSQL. This connection holds the engine's lock while both POSTs arrive, so neither has read the key ++ when the other writes it. Released, one starts the run and the other answers with it; before, the second insert broke ++ uq_op_idempotency and the caller got a 500.""" ++ import time ++ from concurrent.futures import ThreadPoolExecutor ++ from sqlalchemy import text ++ ++ client, ctx, *_, keys = world ++ headers = {**auth(keys, "opal", **OPAL), "Idempotency-Key": "one-key-twice"} ++ body = {"template": "rebuild-verify", "parameters": {"cluster-id": "CRC"}} ++ with ctx.db.engine.connect() as holder, ThreadPoolExecutor(max_workers=2) as pool: ++ holder.execute(text("SELECT pg_advisory_lock(:k)"), {"k": engine._ENGINE_LOCK}) ++ try: ++ posts = [pool.submit(client.post, "/api/v1/operations", json=body, headers=headers) for _ in range(2)] ++ time.sleep(1.5) # both are waiting: on the lock, or (before) one on the other's insert ++ finally: ++ holder.execute(text("SELECT pg_advisory_unlock(:k)"), {"k": engine._ENGINE_LOCK}) ++ answers = [post.result(timeout=30) for post in posts] ++ assert [a.status_code for a in answers] == [202, 202], [a.text for a in answers] ++ assert answers[0].json()["operationId"] == answers[1].json()["operationId"] ++ with ctx.db.session() as session: ++ assert len(list(session.scalars(select(OperationRow)))) == 1 ++ ++ ++WORKFLOW_FACTS = {"plugin": "namespaces", "action": "update", "environment": "dev", "namespace": "payments-dev", ++ "tier": "small", "capacity": "fits", "capacityFresh": True, "automated": True, ++ "requesterClient": engine.WORKFLOWS_CLIENT, "reason": ops.RERENDER_REASON, ++ "starterApprovalFacts": {"automated": False, "requesterClient": None, "reason": None}} ++SENT_BY_WORKFLOWS = f'requesterClient == "{engine.WORKFLOWS_CLIENT}"' ++ ++ ++@pytest.mark.parametrize("rules, auto, slots", [ ++ # A policy for the workflow client alone: the starter's own request needs one approver, so the delegated one does. ++ ({"autoApproval": {"enabled": True, "policies": [{"name": "workflows", "requester": {"clients": [engine.WORKFLOWS_CLIENT]}}]}}, ++ None, {"approver-platform": 1}), ++ # A policy that reads the operation's reason, which a person's request never has: the same. ++ ({"autoApproval": {"enabled": True, "policies": [{"name": "rerenders", "match": {"reason": ops.RERENDER_REASON}}]}}, ++ None, {"approver-platform": 1}), ++ # A policy that covers the starter's own request covers the delegated one. ++ ({"autoApproval": {"enabled": True, "policies": [{"name": "dev-changes", "match": {"actions": ["update"]}}]}}, ++ "auto:dev-changes", {}), ++ # A rule about the workflow client still adds its approvers: the larger count of a group both name. ++ ({"thresholds": [{"when": SENT_BY_WORKFLOWS, "add": 1}]}, None, {"approver-platform": 2}), ++ # A rule that only the starter's own request meets is kept, with the other group's slot beside it. ++ ({"thresholds": [{"when": "automated == False", "add": 2, "group": "approver-dev"}, ++ {"when": SENT_BY_WORKFLOWS, "add": 1}]}, None, {"approver-platform": 2, "approver-dev": 2}), ++ # The starter's policy does not cover the sender when a rule adds approvers for the sender. ++ ({"thresholds": [{"when": SENT_BY_WORKFLOWS, "add": 1}], ++ "autoApproval": {"enabled": True, "policies": [{"name": "dev-changes", "match": {"actions": ["update"]}}]}}, ++ None, {"approver-platform": 2}), ++]) ++def test_a_delegated_request_needs_what_the_starter_and_the_sender_each_need(rules, auto, slots): ++ """Finding 2's rule, on the rules alone: never fewer approvers than the starter's own request, and never fewer than the ++ request as the workflow client sends it.""" ++ decision = ApprovalRules({"environments": {"dev": {"required": 1}}, **rules}).decide(WORKFLOW_FACTS) ++ assert (decision.auto, {slot.group: slot.count for slot in decision.slots}) == (auto, slots) ++ ++ ++def test_a_delegated_change_carries_the_held_key_warning_of_the_starters_own_change(test_config, keys, monkeypatch): ++ """Reviewer 2, finding 1. Git holds a namespace without a required key. The starter's own PATCH carries the ++ missing_required_key warning, and a warning keeps auto-approval from applying. The same change sent by an operation has ++ a reason, and a plan with a reason got no such finding: the policy that could not approve the PATCH approved it.""" ++ import yaml ++ ++ with build_world(test_config, keys, monkeypatch) as (_, ctx, git, *_): ++ monkeypatch.setattr(ctx.pipeline, "auto_paused", lambda session: False) ++ monkeypatch.setattr(ctx.pipeline.capacity, "check", lambda *args, **kwargs: CapacityResult("fits", True, None, {})) ++ files = ctx.pipeline.plan_namespace(STARTER, "CRC", NS, action="create").files ++ for path in list(files): ++ doc = yaml.safe_load(files[path]) ++ if doc["kind"] == "ResourceQuota": ++ doc["spec"]["hard"]["requests.cpu"] = "6" # an older catalog's value: the re-render changes it ++ if doc["kind"] == "Namespace": ++ del doc["metadata"]["annotations"]["cmapi.net/team-dl"] ++ files[path] = yaml.safe_dump(doc) ++ git.branches["main"].update(files) ++ raw = {"environments": {"dev": {"required": 1}}, "autoApproval": {"enabled": True, "policies": [ ++ {"name": "dev-changes", "match": {"plugin": "namespaces", "actions": ["update"]}}]}} ++ monkeypatch.setattr(ctx.cfg, "approvals", ApprovalRules(raw)) ++ etag = f'"{folder_etag(ctx.pipeline.read_folder("CRC", NS["namespace"])[0])}"' ++ body = {"namespace": NS["namespace"]} ++ own = ctx.pipeline.plan_namespace(STARTER, "CRC", body, action="update", if_match=etag) ++ assert any("cmapi.net/team-dl" in warning for warning in own.facts["warnings"]), own.facts["warnings"] ++ assert (own.requirement.auto, own.requirement.auto_fallback, own.requirement.total) == (None, "warnings", 1) ++ actor = Identity(engine.WORKFLOWS_CLIENT, engine.WORKFLOWS_CLIENT, "service", engine.WORKFLOWS_CLIENT, ++ roles=STARTER.roles) ++ sent = ctx.pipeline.plan_namespace(STARTER, "CRC", body, action="update", if_match=etag, reason=ops.RERENDER_REASON, ++ submitted_by=actor) ++ assert (sent.requirement.auto, sent.requirement.auto_fallback, sent.requirement.total) == (None, "warnings", 1) ++ assert sent.facts["warnings"] == own.facts["warnings"] +diff --git a/cmapi/tests/service/test_usage_verdicts_310.py b/cmapi/tests/service/test_usage_verdicts_310.py +--- a/cmapi/tests/service/test_usage_verdicts_310.py ++++ b/cmapi/tests/service/test_usage_verdicts_310.py +@@ -18,7 +18,7 @@ + import conftest # noqa: E402 + from cmapi.capacity.sweep import VerdictRepo, run_sweep # noqa: E402 + from cmapi.capacity.usage import EXPECTED_STEPS, PromUsage # noqa: E402 +-from cmapi.core.db import Database # noqa: E402 ++from cmapi.core.db import Database, REQUIRED_REVISION # noqa: E402 + from cmapi.core.db.models import AnalysisSweepRow, NamespaceVerdictRow # noqa: E402 + from cmapi.core.db.repo import JobRepo # noqa: E402 + from test_flow import NS, OLA, auth, run_jobs # noqa: E402 +@@ -323,7 +323,6 @@ + db = Database(conftest.DB_URL) + monkeypatch.setattr(db, "schema_version", lambda: "0009") + try: +- # Since #21 the code needs 0012 (capacity_snapshots, placement holds); a 0009 schema is still behind, now by three. +- assert db.schema_status() == "behind: at 0009, needs 0012" ++ assert db.schema_status() == f"behind: at 0009, needs {REQUIRED_REVISION}" + finally: + db.engine.dispose() +diff --git a/docs/14-authorization.md b/docs/14-authorization.md +--- a/docs/14-authorization.md ++++ b/docs/14-authorization.md +@@ -63,7 +63,7 @@ + | `audit:export` | | | | | | | yes | | 0 | + | `approvals:relay` | | | | | | | | yes | 0 | + +-`namespaces:protect` is what makes an operator (#366). No route declares it: the routes check it inside, in the environment of the object. It lets a caller set and remove the operator-only labels and annotations of `metadata-keys.yaml` (`cmapi.net/protected` and `do-not-delete`; a requester gets 403), cancel another person's request, and read employee IDs in the directory (`cmapi/src/cmapi/core/authz.py:160-166`, `cmapi/src/cmapi/core/pipeline.py:304`). It is a permission, not a role name: a role of `authz-roles.yaml` that inherits `cmapi-operator` is an operator, and a role that grants it in some environments makes an operator there only. A file that lists `permissions:` for `cmapi-operator` itself must name `namespaces:protect`, or that role is no longer an operator. ++`namespaces:protect` is what makes an operator (#366). No route declares it: the routes check it inside, in the environment of the object. It lets a caller set and remove the operator-only labels and annotations of `metadata-keys.yaml` (`cmapi.net/protected` and `do-not-delete`; a requester gets 403), cancel another person's request, and read employee IDs in the directory (`cmapi/src/cmapi/core/authz.py:160-166`, `cmapi/src/cmapi/core/pipeline.py:307`). It is a permission, not a role name: a role of `authz-roles.yaml` that inherits `cmapi-operator` is an operator, and a role that grants it in some environments makes an operator there only. A file that lists `permissions:` for `cmapi-operator` itself must name `namespaces:protect`, or that role is no longer an operator. + + Each column name has the prefix `cmapi-` in Keycloak. An operator or an admin cannot approve with those roles alone: `requests:approve` is only in `cmapi-approver`. On CRC the group `app-cmapi-rbac-operator` also gives `cmapi-approver`. + +@@ -175,9 +175,9 @@ + + | 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:290`, `:598` | ++| Create, change, delete or extend a namespace, or set or remove its expiry | The cluster's environment | `cmapi/src/cmapi/core/pipeline.py:292`, `:610` | + | 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:715` | ++| 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:727` | + | 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` | +@@ -200,7 +200,7 @@ + + ### 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:358-385`). They are in this order: + + | Check | Refusal | + |---|---| +@@ -283,7 +283,7 @@ + + | 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:376-377`) | + | 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 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:376-377`). 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. +@@ -313,7 +313,7 @@ + + ### Tools that act for people + +-A tool signs in with the client credentials grant. It is a service client, or an account that holds a role in `identity.automationRoles`. The default role is `cmapi-onboarding`, and `cmapi-automation` holds it (`checks.py:1-15`; `docs/15`, "The clients"). The tool is the caller. Three cases follow (`checks.py:70-95`, called from `pipeline.py:296`): ++A tool signs in with the client credentials grant. It is a service client, or an account that holds a role in `identity.automationRoles`. The default role is `cmapi-onboarding`, and `cmapi-automation` holds it (`checks.py:1-15`; `docs/15`, "The clients"). The tool is the caller. Three cases follow (`checks.py:70-95`, called from `pipeline.py:298`): + + | Case | What cmapi does | Source | + |---|---|---| +@@ -321,7 +321,7 @@ + | 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:105` | + +-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:873`, `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:885`, `approvals.py:376-377`). 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:374-375`). 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 @@ + | 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` | + +-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:368`), 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 @@ + |---|---| + | 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:365-368`. 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/21-usage-from-thanos.md b/docs/21-usage-from-thanos.md +--- a/docs/21-usage-from-thanos.md ++++ b/docs/21-usage-from-thanos.md +@@ -115,9 +115,9 @@ + + | 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:678-688`), 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:690-700`), 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:261-267`) | +-| 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:678-688`). 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:690-700`). 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 | +@@ -215,7 +215,7 @@ + - **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`). + - **A namespace create never queries Thanos.** Only a quota change on an existing namespace reads usage +- (`cmapi/src/cmapi/core/pipeline.py:462-469`). A test creates a namespace on PostgreSQL with `usage.source: thanos` and both ++ (`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 + usage `unavailable` (`cmapi/tests/service/test_reader_thanos_grants_724.py:428-470`). + +diff --git a/docs/citations.lock.json b/docs/citations.lock.json +--- 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|358-385": [ + " 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|365-368": [ + " 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|368-368": [ + " 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|374-375": [ + " 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|376-377": [ + " if approver.sub == self.requester_sub and not self.requirement.self_approval:", + " raise Problem.conflict(\"self-approval\", \"Requesters cannot approve their own request here\")" + ], +@@ -504,22 +504,22 @@ + " self.identity.get(\"requireOnBehalfOf\", False),", + " self.identity.get(\"automationRoles\", [\"cmapi-onboarding\"]))" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|290-290": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|292-292": [ + " self.cfg.roles.require(who, \"namespaces:create\" if action == \"create\" else \"namespaces:write\", env)" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|296-296": [ +- " requester = requester or self.requester_for(who, body.get(\"onBehalfOf\"))" ++ "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|298-298": [ ++ " direct = self.requester_for(who, body.get(\"onBehalfOf\"))" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|304-304": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|307-307": [ + " operator = self.cfg.roles.is_operator(who, env)" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|598-598": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|610-610": [ + " self.cfg.roles.require(who, \"namespaces:write\", env)" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|715-715": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|727-727": [ + " self.cfg.roles.require(who, ADOPT_PERMISSION, env)" + ], +- "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|873-873": [ ++ "docs/14-authorization.md|cmapi/src/cmapi/core/pipeline.py|885-885": [ + " 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|105-105": [ +@@ -1559,7 +1559,7 @@ + " return (len(client.list(\"Pod\", namespace=ns)[\"items\"]),", + " len(client.list(\"PersistentVolumeClaim\", namespace=ns)[\"items\"]))" + ], +- "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|462-469": [ ++ "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|467-474": [ + " # A quota change on an existing namespace reads its live 14-day usage (docs/01, \"Quota changes on existing namespaces\");", + " # nothing else does: \"Never queried while creating a namespace or setting its first quota\" (docs/01, Thanos on onboarding).", + " usage_view, usage_facts = None, {}", +@@ -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|678-688": [ ++ "docs/21-usage-from-thanos.md|cmapi/src/cmapi/core/pipeline.py|690-700": [ + " 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/docs/reviews/2026-12-01-issue-26-operations/design.md b/docs/reviews/2026-12-01-issue-26-operations/design.md +--- a/docs/reviews/2026-12-01-issue-26-operations/design.md ++++ b/docs/reviews/2026-12-01-issue-26-operations/design.md +@@ -42,6 +42,9 @@ + queued for later. `maxConcurrentSteps` (integrations.yaml, default 4) counts only the rows `Running` across every run: the + jobs that are due or running now. docs/02: "separate from request jobs, so operations never starve them". A run of 500 + namespaces therefore never puts 500 due jobs ahead of the request jobs. ++ A Waiting row's poll, and the next attempt of a retry after its backoff, run without taking a slot (review of #774, ++ reviewer 1's finding 6, not taken): each is the row's one job, a fan-out's `parallelism` bounds how many rows of a run ++ wait, and a second job to admit each poll would double the jobs the cap is there to keep down. + + ## D3. The step's identity: delegation, not impersonation + +@@ -53,9 +56,24 @@ + - The step acts as `svc-cmapi-workflows` (`StepContext.actor`), a service identity of its own, holding the roles of the token + that started the run (stored in `operations.started_by`). A step can do no more than its starter could, in the environments + where the starter could (a confused deputy is not possible), and a plan checks `namespaces:write` against those roles. +-- Each request it opens has the starter as its requester and the step's client as the sender (`StepContext.requester`): +- `requester_username` and `requester_sub` are the starter's, `requester_kind` is `service`, `requester_client` and +- `requester.submittedByClient` are `svc-cmapi-workflows`, and `automated` is true. ++- Each request it opens has the starter as its requester and the step's client as the sender ++ (`Pipeline.plan_namespace(starter, ..., submitted_by=actor)`): `requester_username` and `requester_sub` are the starter's, ++ `requester_kind` is `service`, `requester_client` and `requester.submittedByClient` are `svc-cmapi-workflows`, and ++ `automated` is true. ++- The plan checks the starter as it checks the starter's own request (review of #774): the permission, and the identity ++ rules of `resolve_requester` (a token with no `employee_id` where the instance requires one is 422 `identity-incomplete`, ++ and the step's row is Failed with it). ++- The approval rules decide the request twice (`ApprovalRules.decide`, review of #774): as sent (`automated` true, ++ `requesterClient` `svc-cmapi-workflows`, the operation's `reason`), and as the starter's own request (the plan's ++ `starterApprovalFacts`: the starter's `automated` and client, and no `reason`). The request must satisfy both: where both ++ need approvers, every slot of each, with the larger count in a group both name. So an operation never gets an approval ++ that the starter's own request would not get. An auto-approval policy that names `svc-cmapi-workflows` in ++ `requester.clients`, or the operation's reason in `match.reason`, cannot approve alone what the starter's request needs a ++ person for. A rule that reads the sender can still add approvers to an operation's requests. This is the delegation of ++ RFC 8693, section 1.1: "while B may have delegated some of its rights to A, any actions taken are being taken by A ++ representing B" (fetched 2026-12-01); the rights are B's, the starter's, and no more. ++- The plan of an operation's change carries the `missing_required_key` warning of a namespace that lacks a required key, ++ as the starter's own PATCH does, so the warning guard of auto-approval holds for both (`Pipeline._plan_namespace`). + - The approval ledger refuses the requester's subject as an approver, so the starter cannot approve the requests of the run + where the environment forbids self-approval. docs/01, "Approval of record": the approver is "not the person who started the + operation". Where an environment allows self-approval (rnd and dev in the examples), the same rule as for a person's own +@@ -183,6 +201,10 @@ + fingerprint of the template and the parameters: the same caller, key and body get the run it started for as long as the run is + kept; the same key with another body is 409 `idempotency-replay`. The header's description in the API says so. + ++A replay is a read of the run, so it is checked as `GET /api/v1/operations/{id}` is (D9): `operations:run`, and the ++template's own permissions, where the stored run acts, before the run or its ID is returned (review of #774). The key is ++read under the engine's lock, so two starts with one key at the same moment start one run and both answer with it. ++ + ## D14. Smaller choices + + - Operation IDs are `op-YYYYMMDD-<8 hex>`, random like a placement's ID, so a start takes no day lock. +@@ -193,6 +215,13 @@ + namespace with no ResourceQuota that cmapi rendered (an adopted one) is not selected. + - "a decrease below current use is skipped": the live quota's `status.used` against the plan's new hard values, through + `TierCatalog.compare`'s `below_used`. ++- A step about a cluster runs only while the cluster is in the environments recorded at the start (`operations.environments`, ++ D9); a cluster that clusters.yaml moved to another environment since fails the step, so a report is never read under an ++ environment's grant that no longer covers its cluster (review of #774). ++- A step's Idempotency-Key is `//` when that fits the 100 characters of ++ `change_requests.idempotency_key`, and `op-step:` with its SHA-256 otherwise (a cluster ID and a namespace are up to 63 ++ characters each). ++- The report lists the steps in the template's order, then the items by name. + - The requests a run opens do not take tokens from the team's rate-limit bucket (`team_request`, #689), which counts the writes + of callers of the API. A run is bounded by its own caps instead: `batchSize` and `maxOpenPerCluster` (D10). + - The locks, in one order everywhere: a step's job locks its own row, then the engine's advisory lock, then the runs' rows; a diff --git a/docs/reviews/2026-12-01-issue-26-operations/reviewer-1-codex.md b/docs/reviews/2026-12-01-issue-26-operations/reviewer-1-codex.md new file mode 100644 index 00000000..12815b82 --- /dev/null +++ b/docs/reviews/2026-12-01-issue-26-operations/reviewer-1-codex.md @@ -0,0 +1,721 @@ +# PR #774 review at `703da75d` + +**Request changes.** The built-in engine can approve a delegated change that requires a person on the ordinary request path. A worker can also finish a cancelled run as Succeeded, and a replay can return a run outside the caller’s current grant. These have separate regression tests. The three API-standard failures share one cause. Migration 0013’s compiled PostgreSQL DDL matches the ORM. + +The [complete patch](codex-fix.diff) contains the production changes and regression tests, applies at the root of `export/`, and passed `git apply --check --whitespace=error`. Tests ran against separate copies of the supplied head and the patched tree. Source locations below refer to the **original head**. + +## Findings + +Each row gives the regression test and its measured outcome. For rows 1–11, the test name is relative to `tests/service/test_operations_review_774.py`. Run the service command below with `tests/service/test_operations_review_774.py::`. The full implementations are in the patch appendix. + +| # | Severity and original location | Failure scenario and fix | Regression test and observed change | +|---|---|---|---| +| 1 | High · `cmapi/src/cmapi/core/pipeline.py:296`, `ops/__init__.py:130` | The rerender step constructs a requester before calling the ordinary pipeline. This skips the starter’s identity checks, including required employee ID and the instance’s on-behalf-of policy. Resolve the starter through the ordinary path before attaching the workflow sender to the audit record. | `test_delegated_plan_preserves_starter_checks[None-identity-incomplete]` reached submission on the head. The patch returns `identity-incomplete` and never submits. | +| 2 | High · `cmapi/src/cmapi/core/pipeline.py:472`, `core/approvals.py:274` | A configured client-only auto-approval can match the shared workflow client even when the same change from the starter requires a human. Evaluate both identities against the same capacity, switch and daily-allowance facts, at planning and again whenever submit recalculates approval. Require the larger quorum for each approving group. Keep the workflow client and starter in the audit record. | `test_delegated_plan_preserves_starter_checks[123-approval]` observed `auto:client-policy` on the head. After the fix both decisions require one approver. The reference policies need no change. | +| 3 | High · `cmapi/src/cmapi/routers/operations.py:232` | A caller originally had an unrestricted grant for onboarding an unregistered cluster. After registration and a role restriction, its current environment can pass the start check although the stored run still requires unrestricted access. Replay returned the entire historical run. Check the stored scope before returning the run or disclosing its ID in a conflict. | `test_replay_uses_the_stored_visibility_scope` returned a held row on the head. It now raises 403. | +| 4 | High · `cmapi/src/cmapi/core/operations.py:662` | A queued cluster verification survives a rollout that moves the cluster to another environment. The worker reads the cluster under its new assignment, while the old environment still governs access to the report. Check the cluster against the run’s recorded environments before dispatch, including persisted fan-out items. | `test_worker_holds_cluster_steps_to_recorded_scope` called the step on the head. It now ends Failed before the handler is called. | +| 5 | High · `cmapi/src/cmapi/core/operations.py:368` | A worker loads the run, cancellation commits while the step is in progress, and the worker later takes the engine lock. Its locking query reuses the already-loaded run. It can schedule a successor or mark the run Succeeded. Flush local work and refresh the run from the locking query. | `test_advance_observes_a_cancel_recorded_after_worker_loaded_run` produced Succeeded on the head, then Stopped with no successor after the fix. The patch also adds a two-session service test. Its PostgreSQL fixture was blocked here. | +| 6 | High · `cmapi/src/cmapi/core/operations.py:636` | With one slot occupied, a due Waiting row goes straight into its step handler. A retry can execute a full change while the configured slot is already in use. Under the scheduler lock, admit a due row into Running only when a slot is free. Execute it in a subsequent job so the lock stays out of the external call. | `test_waiting_poll_reserves_a_global_slot_before_execution` observed a handler call with the only slot occupied. It now defers, reserves the freed slot, then calls the handler once. | +| 7 | Medium · `cmapi/src/cmapi/routers/operations.py:232` | Two simultaneous starts by one subject can both miss the same key before either inserts it. The unique index prevents a second run, but the losing flush can raise an unhandled integrity error. Take the transaction-scoped engine lock before the lookup. The second transaction then reads the winner and uses the existing replay/conflict logic. | `test_start_reads_the_key_after_acquiring_the_scheduler_lock` observed an unlocked lookup on the head and a locked replay after the fix. This test checks ordering with a session double. A live simultaneous POST was unavailable. | +| 8 | Medium · `cmapi/src/cmapi/core/operations.py:615`, `core/db/models.py:56` | A valid 63-character cluster ID and 63-character namespace produce a 167-character request key. The request column accepts 100. Retrying repeats the same oversized key. Preserve existing short keys and deterministically hash long ones. | `test_step_keys_fit_the_request_column_and_preserve_existing_short_keys` measured 167 against 100 before. The patched long key fits, is stable, and differs for distinct items. | +| 9 | High · `cmapi/src/cmapi/ops/__init__.py:238`, `core/git/gitea.py:208` | The new recovery operation treats Gitea’s first page of branches and open PRs as the entire repository. A missing request on page two can yield a successful clean report. Read all indicated pages for both endpoints and propagate page errors. | `test_reconcile_reads_later_gitea_result_pages` got an empty branch result on the head. After the fix both the branch and PR on page two are returned. | +| 10 | Medium · `cmapi/src/cmapi/core/operations.py:511` | Cancel a fan-out with a Pending item. The report substitutes the run start time for the never-started row and sorts its step before its prerequisite. This also invalidates the report index used by the PR’s own cancel test. Order the report by template step, then item. | `test_cancel_report_preserves_template_order_for_unstarted_items` listed verification before folder discovery. The patch lists discovery first. | +| 11 | Medium · `cmapi/src/cmapi/routers/operations.py:214` | A signed-in viewer sending a start without a key gets 400 before the route evaluates the missing permission. The authz walk expects 403 for that caller. Check the route permission before validating the key. | `test_start_checks_permission_before_the_key` called the actual HTTP route with a fake identity provider. The response changed from 400 to 403. | +| 12 | Low · `cmapi/tests/service/test_api_standard.py:46`, `routers/operations.py:209` | The documented summary “Start an operation” uses a verb absent from the standard’s permitted set. Add Start to that set, as the test’s S1 comment directs for a new kind of operation. | `tests/service/test_api_standard.py` produced **3 failed, 174 passed** before and **177 passed** after. All three were `test_every_operation_meets_the_standard`, S1, for `metadata-keys.yaml`, `metadata-keys.company.yaml`, and `design`. These account for three measured failures. The stopped run’s node IDs are unavailable. | +| 13 | Low · `cmapi/tests/service/test_usage_verdicts_310.py:327` | The readiness regression pins the diagnostic to 0012. Raising the actual required revision to 0013 breaks the assertion for a correctly rejected 0009 database. Keep the 0009 case and compare the reported target with `REQUIRED_REVISION`. | `tests/service/test_usage_verdicts_310.py::test_a_database_at_0009_is_behind_this_code` failed with “needs 0013” before and passed after. | + +## Checks that held + +- **Migration.** Compared the PostgreSQL DDL emitted by Alembic for upgrade with SQLAlchemy’s compiled `CreateTable` and `CreateIndex` for both models, normalizing whitespace and definition order. They agree on both PKs, the FK, defaults, nullability, seven CHECKs, and all four indexes including predicates and uniqueness. Upgrade creates only the two new tables and their indexes. The FK refers to the new parent. Downgrade emits `DROP TABLE operation_steps` followed by `DROP TABLE operations`. Revision chain is `0012 → 0013`. Alembic head and `REQUIRED_REVISION` both equal 0013. The repository’s head-revision test passed. This verifies the DDL and table targets. Real lock acquisition, constraint enforcement and the up/down/up round trip still require PostgreSQL. +- **Ordinary authorization.** Start checks every requested environment and reconcile adds `approvals:pause`. A null run scope checks an unrestricted grant, including when onboarding an unknown cluster. List filters by stored scope. GET and cancel recheck that scope after lookup by ID. Knowing an ID does not grant access to the report or permit cancellation. A missing ID gives 404 and a known out-of-scope ID gives 403, so those results distinguish existence. `RolePolicy` grants permissions by environment. Two clusters in one environment share that grant. A template’s selector narrows the work and does not establish a separate cluster-level grant. +- **Attribution and self-approval.** Start snapshots the token’s roles and groups. The request records the starter’s subject and the workflow client separately. The ledger compares the approver’s subject with `requester_sub` and enforces `selfApproval` from the stored requirement. Core tests cover both a delegated requester refused as their own approver and an environment explicitly allowing it. Revocation of a token role during a run has the snapshot behavior documented in D3. +- **Scheduling, retries and crash handling.** Initial admission counts Running rows across runs under the engine lock. Per-template batch and per-cluster counts include Running and Waiting items within each run. Cancel takes the engine lock before the run row. The offline cancel test confirmed the order on both trees. The lease-generation fence precedes worker commit. Request creation and step outputs share a transaction. Polls use the recorded request ID, and a rerender also checks its own key under the workflow subject. The retry block allows four total failed attempts with 30, 60 and 120 seconds of backoff. A permanent refusal ends the step. The live worker-death and concurrent-cancel scenarios remain unverified here. +- **API and generated files.** The offline check verified 503 `operations-engine-unavailable` for an unavailable adapter and 422 `operation-template-unknown` for an unknown template on the built-in engine. All four operation IDs agree across OpenAPI, samples and generated portal types. All four portal permission entries name `operations:run`, and the paths appear in docs/04. The reference contract rendered byte-for-byte in the offline suite. The original committed-contract HTTP assertion also passed on both trees when invoked with the service’s existing fake application fixture, bypassing only the unused database setup. + +## Primary sources + +Read on **2026-12-01**. The application-specific permissions, row transitions and test outcomes above come from the supplied head and the local runs. + +- PostgreSQL describes transaction advisory locks as “automatically released at the end of the transaction.” This is the lifetime needed to serialize admission and key lookup through commit. [PostgreSQL, Explicit Locking §13.3.5](https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS) +- PostgreSQL states that “Read Committed is the default isolation level in PostgreSQL.” A lookup begun after acquiring the lock sees the preceding transaction’s committed start under that isolation level. [PostgreSQL, Transaction Isolation §13.2.1](https://www.postgresql.org/docs/current/transaction-iso.html#XACT-READ-COMMITTED) +- SQLAlchemy explains that when an already-loaded primary key appears in another result, “the row is not applied to the object.” The cancellation regression exercises that behavior with a real ORM session. [SQLAlchemy, Populate Existing](https://docs.sqlalchemy.org/en/20/orm/queryguide/api.html#populate-existing) +- Gitea documents that “The API supports pagination.” Its branch and PR handlers both set the link header for the result set. [Gitea 1.25 API pagination](https://docs.gitea.com/1.25/development/api-usage/#pagination) · [Branch handler](https://github.com/go-gitea/gitea/blob/release/v1.25/routers/api/v1/repo/branch.go) · [Pull request handler](https://github.com/go-gitea/gitea/blob/release/v1.25/routers/api/v1/repo/pull.go) + +## Test record + +Commands ran from `cmapi/` in each tree, one file at a time, using the review database URL from BRIEF.md. The first operations run was interrupted during the migrator’s default 540-second database wait. After a direct socket check returned `PermissionError: [Errno 1] Operation not permitted` for loopback port 55432, the serial rerun used `CMAPI_MIGRATE_WAIT_SECONDS=0`. Database existence and creation could not be checked. No cluster or remote service was contacted by the tests. + +```sh +# CMAPI_TEST_DATABASE_URL is the review database URL in BRIEF.md. +export CMAPI_TEST_DATABASE_URL PYTHONDONTWRITEBYTECODE=1 CMAPI_MIGRATE_WAIT_SECONDS=0 +export PYTHONPATH=src:tests/service +svc=/Users/olasumbo/gitRepos/workbench/cmapi/wt-655-outputs/venv-merged/bin/python +core=/Users/olasumbo/gitRepos/workbench/cmapi/venv-ref/bin/python +"$svc" -m pytest tests/service/test_operations_review_774.py -q -W ignore -p no:cacheprovider +"$svc" -m pytest tests/service/test_api_standard.py -q -W ignore -p no:cacheprovider +"$svc" -m pytest tests/service/test_usage_verdicts_310.py::test_a_database_at_0009_is_behind_this_code -q -W ignore -p no:cacheprovider +"$core" -m pytest tests/core/test_approvals.py -q -W ignore -p no:cacheprovider +``` + +For the focused before-run, copy only `test_operations_review_774.py` from the patch into the original tests directory. Running that identical file against the head gave **11 failed, 2 passed**. The patch gave **13 passed**. The two positive controls are the cancel lock order and the distinction between 503 and 422. These tests use the actual planner, rules, ORM or HTTP route as applicable, with SQLite or test doubles where PostgreSQL would otherwise be required. + +| Test file or node | PR head | Patched tree | +|---|---|---| +| `tests/service/test_operations_26.py` | 1 passed, 19 database setup errors, including the migration round trip | 1 passed, 20 database setup errors including the added two-session cancel test | +| `tests/service/test_review_h_tools_migrate.py` | 18 passed, 6 database setup errors | — | +| `tests/service/test_models_match_migrations.py` | 15 database setup errors | — | +| `tests/service/test_api_docs.py` | 7 passed, 19 setup errors. 18 required the database and the fake npm registry could not bind a loopback socket. | Committed-contract HTTP assertion passed separately | +| `tests/service/test_api_standard.py` | 174 passed, 3 failed | 177 passed | +| `tests/service/test_review_c_authz.py` | 13 database setup errors including the route walk | Operations permission/key ordering verified separately over HTTP | +| `tests/service/test_openapi_render_337.py` | 8 passed | 8 passed | +| `tests/service/test_api_contract.py` | 3 passed, 4 database setup errors | — | +| `tests/core/test_approvals.py` | 36 passed | 36 passed | +| `tests/core/test_identity_metadata.py` | 21 passed | 21 passed | +| `test_pr40_convergence.py::test_required_revision_is_the_newest_migration` | — | 1 passed | +| `test_usage_verdicts_310.py::test_a_database_at_0009_is_behind_this_code` | 1 failed | 1 passed | + +## Full fixes and regression tests + +The appendix reproduces [codex-fix.diff](codex-fix.diff). The patch includes the complete changes for every finding. Finding 12 uses the existing API-standard test that failed in all three configurations. + +
+Unified diff against the supplied export + +```diff +diff --git a/cmapi/src/cmapi/core/approvals.py b/cmapi/src/cmapi/core/approvals.py +--- a/cmapi/src/cmapi/core/approvals.py ++++ b/cmapi/src/cmapi/core/approvals.py +@@ -17,7 +17,7 @@ + """ + from __future__ import annotations + +-from dataclasses import dataclass, field ++from dataclasses import dataclass, field, replace + from fnmatch import fnmatchcase + from pathlib import Path + from typing import Any, Mapping +@@ -168,6 +168,22 @@ + # ---- decide + def decide(self, facts: Mapping[str, Any], *, paused: bool = False, + team_auto_today: int = 0) -> Requirement: ++ req = self._requirement(facts, paused, team_auto_today) ++ if "starterApprovalFacts" not in facts: ++ return req ++ direct = self._requirement({**facts, **facts["starterApprovalFacts"]}, paused, team_auto_today) ++ if direct.approved_at_plan: ++ return req ++ if req.approved_at_plan: ++ return replace(direct, reasons=(*direct.reasons, "delegated change requires the starter's approvals")) ++ # Satisfy both sets of slots. In a shared group the larger quorum covers both. ++ slots = {slot.group: slot for slot in req.slots} ++ for slot in direct.slots: ++ if slot.group not in slots or slot.count > slots[slot.group].count: ++ slots[slot.group] = slot ++ return replace(direct, slots=tuple(slots.values()), reasons=tuple(dict.fromkeys((*direct.reasons, *req.reasons)))) ++ ++ def _requirement(self, facts: Mapping[str, Any], paused: bool, team_auto_today: int) -> Requirement: + env = facts["environment"] + if env not in self.environments: # Pipeline._decide refuses first, with the serving instance's URLs (#671) + raise Problem.unprocessable("environment-not-served", f"No approval rules for {env}") +diff --git a/cmapi/src/cmapi/core/git/gitea.py b/cmapi/src/cmapi/core/git/gitea.py +--- a/cmapi/src/cmapi/core/git/gitea.py ++++ b/cmapi/src/cmapi/core/git/gitea.py +@@ -204,13 +204,23 @@ + r = self._call("delete_branch", "DELETE", f"{self._repo()}/branches/{quote(branch)}", ok=(204, 404)) + return r.status_code in (204, 404) + ++ def _list_pages(self, operation: str, resource: str, **filters: str) -> Iterator[dict[str, Any]]: ++ path = f"{self._repo()}/{resource}" ++ for page in count(1): ++ response = self._call(operation, "GET", path, params={**filters, "limit": 50, "page": page}) ++ if response.status_code != 200: ++ raise GitUnavailable(f"{operation}: GET {path} page {page}: HTTP {response.status_code}") ++ yield from response.json() ++ if "next" not in response.links: ++ return ++ + def list_open(self, prefix: str) -> list[PrRef]: +- r = self._call("find_pr", "GET", f"{self._repo()}/pulls", params={"state": "open", "limit": 50}) +- return [self._pr_ref(p) for p in r.json() if p["head"]["ref"].startswith(prefix)] ++ return [self._pr_ref(p) for p in self._list_pages("find_pr", "pulls", state="open") ++ if p["head"]["ref"].startswith(prefix)] + + def list_branches(self, prefix: str) -> dict[str, str]: +- r = self._call("branches", "GET", f"{self._repo()}/branches", params={"limit": 50}) +- return {b["name"]: b["commit"]["id"] for b in r.json() if b["name"].startswith(prefix)} ++ return {b["name"]: b["commit"]["id"] for b in self._list_pages("branches", "branches") ++ if b["name"].startswith(prefix)} + + def branch_time(self, sha: str) -> int: + from datetime import datetime +diff --git a/cmapi/src/cmapi/core/operations.py b/cmapi/src/cmapi/core/operations.py +--- a/cmapi/src/cmapi/core/operations.py ++++ b/cmapi/src/cmapi/core/operations.py +@@ -45,7 +45,6 @@ + from cmapi.core.db.models import JobRow, OperationRow, OperationStepRow + from cmapi.core.db.repo import JobRepo, utcnow + from cmapi.core.errors import Problem +-from cmapi.core.identity.checks import Requester + from cmapi.core.identity.claims import Identity + from cmapi.core.observability import OPERATION_RUNS, log + +@@ -366,7 +365,8 @@ + lock_engine(s) + s.flush() + runs = list(s.scalars(select(OperationRow).where(OperationRow.finished_at.is_(None)) +- .order_by(OperationRow.started_at, OperationRow.operation_id).with_for_update())) ++ .order_by(OperationRow.started_at, OperationRow.operation_id).with_for_update() ++ .execution_options(populate_existing=True))) + for op in runs: + template = engine.templates.get(op.template) + if template is None: +@@ -482,13 +482,14 @@ + phase = "Failed" # a step failed, so the steps after it never ran + else: + phase = "Succeeded" +- _finish(s, op, phase, None) +- +- +-def _finish(s: Session, op: OperationRow, phase: str, error: str | None) -> None: ++ _finish(s, op, phase, None, template) ++ ++ ++def _finish(s: Session, op: OperationRow, phase: str, error: str | None, ++ template: OperationTemplate | None = None) -> None: + now = utcnow() + op.phase, op.finished_at, op.updated_at = phase, now, now +- op.report = build_report(op, _rows(s, op.operation_id), error) ++ op.report = build_report(_rows(s, op.operation_id), error, template) + log.info("operation_finished", operation_id=op.operation_id, template=op.template, phase=phase) + OPERATION_RUNS.labels(op.template, op.engine, phase).inc() + +@@ -505,10 +506,11 @@ + row.last_error = error[:2000] + + +-def build_report(op: OperationRow, rows: list[OperationStepRow], error: str | None) -> dict[str, Any]: ++def build_report(rows: list[OperationStepRow], error: str | None, template: OperationTemplate | None) -> dict[str, Any]: + """What the run did, by step: how many rows ended in each phase, and each item that did not succeed with why.""" + steps: dict[str, dict[str, Any]] = {} +- for r in sorted(rows, key=lambda r: (r.started_at or op.started_at, r.step, r.item)): ++ order = {step.name: i for i, step in enumerate(template.steps)} if template else {} ++ for r in sorted(rows, key=lambda r: (order.get(r.step, len(order)), r.step, r.item)): + st = steps.setdefault(r.step, {"step": r.step, "phases": {}, "items": []}) + st["phases"][r.phase] = st["phases"].get(r.phase, 0) + 1 + # An item that did not succeed, and one that succeeded with something to read (rebuild-verify's drift). +@@ -604,15 +606,13 @@ + roles=st.roles) + + @property +- def requester(self) -> Requester: +- """The person who started the run, sent by svc-cmapi-workflows: both are recorded (docs/02, rule 4), and the ledger +- refuses the starter as an approver (docs/01, "Approval of record").""" +- return Requester(person=self.starter, caller=self.actor, automated=True) +- +- @property + def key(self) -> str: + """The Idempotency-Key of the request this row opens: one per row, so a step that runs again finds its request.""" +- return f"{self.operation.operation_id}/{self.row.step}/{self.row.item}" ++ raw = f"{self.operation.operation_id}/{self.row.step}/{self.row.item}" ++ # Keep keys already used by existing runs. Longer keys never fit change_requests. ++ if len(raw) <= 100: ++ return raw ++ return "op-step:" + hashlib.sha256(raw.encode()).hexdigest() + + + def starter_identity(record: Mapping[str, Any]) -> Identity: +@@ -653,10 +653,26 @@ + _final(row, "Failed", error=f"{row.step} did not finish within {step.timeout_seconds} seconds") + advance(s, engine) + return ++ if row.phase == "Waiting": ++ # A due poll reserves a slot in a short transaction. Its next job runs the ++ # step without holding the scheduler lock during external reads. ++ lock_engine(s) ++ active = s.scalar(select(func.count()).select_from(OperationStepRow).where(OperationStepRow.phase == "Running")) ++ if active < engine.settings.max_concurrent_steps: ++ row.phase = "Running" ++ queue_step(jobs, row) ++ else: ++ queue_step(jobs, row, delay=1) ++ return + sc = StepContext(ctx, s, op, template, row) + job_transaction = s.get_transaction() + try: + with s.begin_nested(): # a step that raises leaves nothing it wrote ++ cluster = row.cluster_id or op.parameters.get("cluster-id") ++ if cluster and op.environments is not None: ++ current = ctx.registry.clusters.get(cluster) ++ if current is None or current.environment not in op.environments: ++ raise StepRefused("cluster is outside the environments authorized at start") + if step.not_built: + raise StepRefused(f"{row.step} is not built yet ({step.not_built}); the steps before it ran") + result = STEPS[(template.name, row.step)](sc) +diff --git a/cmapi/src/cmapi/core/pipeline.py b/cmapi/src/cmapi/core/pipeline.py +--- a/cmapi/src/cmapi/core/pipeline.py ++++ b/cmapi/src/cmapi/core/pipeline.py +@@ -271,18 +271,17 @@ + + # ---- plan a create or update + def plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any], *, action: str, +- if_match: str | None = None, reason: str | None = None, requester: Requester | None = None) -> Plan: +- """`requester`: who the request is for, when the caller already knows it (an operation's step: the person who started +- the run, sent by svc-cmapi-workflows, docs/02 rule 4). Otherwise it is resolved from `who` and `onBehalfOf`.""" ++ if_match: str | None = None, reason: str | None = None, submitted_by: Identity | None = None) -> Plan: ++ """Plan as the starter. A delegated submission also evaluates the workflow client's approval rules.""" + try: + return self._plan_namespace(who, cluster_id, body, action=action, if_match=if_match, reason=reason, +- requester=requester) ++ submitted_by=submitted_by) + except Problem as exc: + count_refusal(exc) + raise + + def _plan_namespace(self, who: Identity, cluster_id: str, body: Mapping[str, Any], *, action: str, +- if_match: str | None = None, reason: str | None = None, requester: Requester | None = None) -> Plan: ++ if_match: str | None = None, reason: str | None = None, submitted_by: Identity | None = None) -> Plan: + st = self.registry.writable(cluster_id) + env = st.policy.environment + self.check_env_served(env) +@@ -293,7 +292,8 @@ + if action == "create": + check_name(ns, self.reserved) + check_not_unmanaged(ns, cache.namespace(ns)) +- requester = requester or self.requester_for(who, body.get("onBehalfOf")) ++ direct = self.requester_for(who, body.get("onBehalfOf")) ++ requester = Requester(direct.person, submitted_by, automated=True) if submitted_by else direct + if action == "create": + # The label is only written at create; refuse here, not as a 422 from the API server at apply. The refusal is + # explicit: a ValueError that escapes a route is the service's fault, 500 internal-error (#648). +@@ -488,6 +488,10 @@ + # tier gives). It does not depend on the beyond-tier keys: a change to a tier with a higher value raises it too. + exposure_base = hard if quotas_held else resolved.quota if action == "create" else old_hard + raised = exposure_raised(exposure_base, hard) ++ if submitted_by: ++ facts["starterApprovalFacts"] = {"automated": direct.automated, "requesterClient": facts["requesterClient"], ++ "reason": None} ++ facts["requesterClient"] = submitted_by.client_id + facts.update({"beyondTier": bool(beyond), "beyondTierKeys": sorted(beyond), "networkExposure": bool(raised)}) + requirement = self._decide(facts) + beyond_view = self.beyond_view(facts, beyond) +diff --git a/cmapi/src/cmapi/ops/__init__.py b/cmapi/src/cmapi/ops/__init__.py +--- a/cmapi/src/cmapi/ops/__init__.py ++++ b/cmapi/src/cmapi/ops/__init__.py +@@ -127,9 +127,9 @@ + files, _ = ctx.pipeline.read_folder(cid, ns) + from cmapi.core.pipeline import folder_etag + try: +- plan = ctx.pipeline.plan_namespace(sc.actor, cid, {"namespace": ns}, action="update", ++ plan = ctx.pipeline.plan_namespace(sc.starter, cid, {"namespace": ns}, action="update", + if_match=f'"{folder_etag(files)}"', reason=RERENDER_REASON, +- requester=sc.requester) ++ submitted_by=sc.actor) + except Problem as exc: + if exc.code == "no-change": + return StepResult.skipped("Git already holds it rendered from the current catalog", outcome="current") +diff --git a/cmapi/src/cmapi/routers/operations.py b/cmapi/src/cmapi/routers/operations.py +--- a/cmapi/src/cmapi/routers/operations.py ++++ b/cmapi/src/cmapi/routers/operations.py +@@ -211,7 +211,7 @@ + problems=["operation-template-unknown", "validation-failed", "environment-forbidden", "environment-not-served", + "cluster-not-found", "policy-violation", "idempotency-key-required", + "idempotency-replay", "operations-engine-unavailable"]) +-def start(body: OperationStart, key: str = Depends(start_key), who: Identity = Depends(require(PERMISSION)), ++def start(body: OperationStart, who: Identity = Depends(require(PERMISSION)), key: str = Depends(start_key), + c: AppContext = Depends(ctx)) -> dict: + """Starts a run of a template on the engine that integrations.yaml names. The answer comes before any step runs; read + `GET /api/v1/operations/{id}` for its progress. A step that changes a namespace opens an ordinary request, which the +@@ -220,22 +220,26 @@ + from cmapi.ops import START_CHECKS + + c.operations.check_available() +- template = c.operations.template(body.template) +- params = template.validate(body.parameters) +- environments = _environments(c, template, params) +- for permission in (PERMISSION, *template.permissions): +- _require(c, who, permission, environments) +- if template.name in START_CHECKS: +- START_CHECKS[template.name](c, params) + sent = fingerprint({"template": body.template, "parameters": body.parameters}) + with c.db.session() as s: ++ lock_engine(s) + held = s.scalars(select(OperationRow).where(OperationRow.started_by_sub == who.sub, + OperationRow.idempotency_key == key)).first() + if held is not None: ++ _require(c, who, PERMISSION, held.environments) + if held.idempotency_fingerprint != sent: + raise Problem.conflict("idempotency-replay", "Idempotency-Key was used for a different operation", + operationId=held.operation_id) ++ for permission in c.operations.template(held.template).permissions: ++ _require(c, who, permission, held.environments) + return _full(c, s, held) ++ template = c.operations.template(body.template) ++ params = template.validate(body.parameters) ++ environments = _environments(c, template, params) ++ for permission in (PERMISSION, *template.permissions): ++ _require(c, who, permission, environments) ++ if template.name in START_CHECKS: ++ START_CHECKS[template.name](c, params) + op_id = new_operation_id() + row = OperationRow(operation_id=op_id, template=template.name, parameters=params, engine=c.operations.engine.name, + run_name=op_id, phase="Pending", environments=environments, started_by_sub=who.sub, +diff --git a/cmapi/tests/service/test_api_standard.py b/cmapi/tests/service/test_api_standard.py +--- a/cmapi/tests/service/test_api_standard.py ++++ b/cmapi/tests/service/test_api_standard.py +@@ -44,7 +44,7 @@ + SCALARS = ("string", "integer", "number", "boolean") + # S1: a summary starts with what the caller does. A new kind of operation adds its verb here. + VERBS = {"Adopt", "Approve", "Cancel", "Change", "Confirm", "Create", "Delete", "Export", "Extend", "Get", "Give", "List", "Pause", +- "Place", "Probe", "Reject", "Remove", "Resume", "Retry", "Revert", "Run", "Search"} # Place, Run: #21 ++ "Place", "Probe", "Reject", "Remove", "Resume", "Retry", "Revert", "Run", "Search", "Start"} # Place, Run: #21 + # S3: the operations that need a token and no permission (GET /me is how a caller finds out what it may do). + TOKEN_ONLY = {("get", "/api/v1/me")} + # S7: the reads that answer 304 to a matching If-None-Match (routers/me.py, plugins/capacity/router.py). +diff --git a/cmapi/tests/service/test_operations_26.py b/cmapi/tests/service/test_operations_26.py +--- a/cmapi/tests/service/test_operations_26.py ++++ b/cmapi/tests/service/test_operations_26.py +@@ -490,3 +490,34 @@ + assert conn.execute("SELECT to_regclass('capacity_snapshots')").fetchone() != (None,) + run("head") + assert conn.execute("SELECT count(*) FROM operations").fetchone() == (0,) ++ ++ ++def test_cancel_during_step_suppresses_its_successor(world, monkeypatch): ++ """Two DB sessions. Cancel commits while the worker holds the step row and has already read the run.""" ++ from concurrent.futures import ThreadPoolExecutor ++ from threading import Event ++ ++ from cmapi.core.operations import StepResult ++ from cmapi.ops import STEPS ++ ++ client, ctx, _, _, _, keys = world ++ op_id = start(world, "rebuild-verify", {"cluster-id": "CRC"}).json()["operationId"] ++ entered, resume = Event(), Event() ++ ++ def hold_first_step(sc): ++ entered.set() ++ assert resume.wait(10) ++ return StepResult.done(items=[]) ++ ++ monkeypatch.setitem(STEPS, ("rebuild-verify", "list-folders"), hold_first_step) ++ with ThreadPoolExecutor(max_workers=1) as pool: ++ worker = pool.submit(run_jobs, ctx, 1) ++ try: ++ assert entered.wait(10) ++ cancelled = client.post(f"{URL}/{op_id}:cancel", headers=auth(keys, "opal", **OPAL)) ++ assert cancelled.status_code == 200, cancelled.text ++ finally: ++ resume.set() ++ assert worker.result(timeout=10) == ["operation_step"] ++ view = get(world, op_id) ++ assert view["phase"] == "Stopped" and [row["step"] for row in view["steps"]] == ["list-folders"] +diff --git a/cmapi/tests/service/test_operations_review_774.py b/cmapi/tests/service/test_operations_review_774.py +new file mode 100644 +--- /dev/null ++++ b/cmapi/tests/service/test_operations_review_774.py +@@ -0,0 +1,281 @@ ++"""Focused operation regressions. Exercise the ORM identity map locally and stub only scheduler I/O.""" ++from contextlib import nullcontext ++from datetime import timedelta ++from types import SimpleNamespace ++from unittest.mock import Mock ++ ++import pytest ++from sqlalchemy import JSON, MetaData, create_engine, select, update ++from sqlalchemy.dialects.postgresql import JSONB ++from sqlalchemy.orm import Session ++ ++from cmapi import ops ++from cmapi.core import operations as engine ++from cmapi.core.approvals import ApprovalRules ++from cmapi.core.authz import RolePolicy ++from cmapi.core.db.models import ChangeRequestRow, JobRow, OperationRow, OperationStepRow ++from cmapi.core.db.repo import fingerprint, utcnow ++from cmapi.core.errors import Problem ++from cmapi.core.identity.claims import Identity ++from cmapi.core.ports import CapacityResult ++from cmapi.routers import operations as api ++from conftest import build_world ++from test_flow import NS, OPAL ++ ++STARTER = Identity("sub-opal", "opal", "user", "portal", employee_id="123", roles=frozenset(OPAL["roles"])) ++ ++ ++@pytest.fixture ++def runtime(monkeypatch): ++ db = create_engine("sqlite://") ++ schema = MetaData() ++ for model in (OperationRow, OperationStepRow): ++ table = model.__table__.to_metadata(schema) ++ for col in table.columns: ++ if isinstance(col.type, JSONB): ++ col.type = JSON() ++ schema.create_all(db) ++ monkeypatch.setattr(engine, "lock_engine", lambda session: None) ++ ctx = SimpleNamespace(operations=engine.Operations.from_integrations({"operations": {"builtin": {"maxConcurrentSteps": 1}}}), ++ registry=SimpleNamespace(clusters={"CRC": SimpleNamespace(environment="dev")})) ++ with Session(db) as session: ++ yield session, ctx ++ db.dispose() ++ ++ ++def run_row(op_id="op-one", template="rebuild-verify"): ++ return OperationRow(operation_id=op_id, run_name=op_id, template=template, engine="builtin", phase="Running", ++ environments=["dev"], parameters={"cluster-id": "CRC", "parallelism": 2}, ++ started_by_sub=STARTER.sub, started_by=STARTER.record()) ++ ++ ++def step_row(op_id, step, phase, item=""): ++ return OperationStepRow(operation_id=op_id, step=step, phase=phase, item=item, cluster_id="", attempts=0, ++ finished_at=utcnow() if phase == "Succeeded" else None) ++ ++ ++def job_for(row): ++ return JobRow(kind=engine.STEP_JOB, payload={"operationId": row.operation_id, "step": row.step, "item": row.item}) ++ ++ ++def test_advance_observes_a_cancel_recorded_after_worker_loaded_run(runtime): ++ session, ctx = runtime ++ run = run_row() ++ session.add_all([run, step_row(run.operation_id, "list-folders", "Succeeded")]) ++ session.commit() ++ session.refresh(run) # the worker loaded every column before entering its step function ++ # Database state of the cancel transaction at the instant the worker acquires the lock. ++ session.execute(update(OperationRow).values(cancel_requested_at=utcnow(), cancel_requested_by="opal") ++ .execution_options(synchronize_session=False)) ++ assert run.cancel_requested_at is None ++ engine.advance(session, ctx.operations.builtin) ++ assert run.phase == "Stopped" ++ assert list(session.scalars(select(OperationStepRow.step))) == ["list-folders"] ++ ++ ++def test_waiting_poll_reserves_a_global_slot_before_execution(runtime, monkeypatch): ++ session, ctx = runtime ++ first, second = run_row(), run_row("op-two") ++ running = step_row(first.operation_id, "list-folders", "Running") ++ waiting = step_row(second.operation_id, "list-folders", "Waiting") ++ session.add_all([first, second, running, waiting]) ++ session.flush() ++ handler = Mock(return_value=engine.StepResult.done(items=[])) ++ monkeypatch.setitem(ops.STEPS, (second.template, waiting.step), handler) ++ enqueue = Mock() ++ monkeypatch.setattr(engine, "queue_step", enqueue) ++ engine.run_step(ctx, session, job_for(waiting)) ++ handler.assert_not_called() ++ assert waiting.phase == "Waiting" and enqueue.call_args.kwargs["delay"] > 0 ++ running.phase, running.finished_at = "Succeeded", utcnow() ++ engine.run_step(ctx, session, job_for(waiting)) ++ assert waiting.phase == "Running" ++ handler.assert_not_called() ++ engine.run_step(ctx, session, job_for(waiting)) ++ handler.assert_called_once() ++ ++ ++def test_worker_holds_cluster_steps_to_recorded_scope(runtime, monkeypatch): ++ session, ctx = runtime ++ run = run_row() ++ row = step_row(run.operation_id, "list-folders", "Running") ++ session.add_all([run, row]) ++ session.flush() ++ ctx.registry.clusters["CRC"].environment = "rnd" ++ handler = Mock(return_value=engine.StepResult.done(items=[])) ++ monkeypatch.setitem(ops.STEPS, (run.template, row.step), handler) ++ engine.run_step(ctx, session, job_for(row)) ++ handler.assert_not_called() ++ assert row.phase == "Failed" and run.phase == "Failed" ++ ++ ++def test_cancel_report_preserves_template_order_for_unstarted_items(runtime): ++ session, ctx = runtime ++ run = run_row() ++ first = step_row(run.operation_id, "list-folders", "Succeeded") ++ pending = step_row(run.operation_id, "verify-namespace", "Pending", "example") ++ run.started_at = utcnow() - timedelta(minutes=2) ++ first.started_at = run.started_at + timedelta(seconds=1) ++ run.cancel_requested_at, run.cancel_requested_by = utcnow(), "opal" ++ session.add_all([run, first, pending]) ++ engine.advance(session, ctx.operations.builtin) ++ assert [entry["step"] for entry in run.report["steps"]] == ["list-folders", "verify-namespace"] ++ ++ ++def test_step_keys_fit_the_request_column_and_preserve_existing_short_keys(): ++ op = run_row("op-20261201-01234567") ++ row = step_row(op.operation_id, "rerender-namespace", "Pending", "CRC/example") ++ sc = engine.StepContext(None, None, op, None, row) ++ assert sc.key == f"{op.operation_id}/{row.step}/{row.item}" ++ row.item = "c" * 63 + "/" + "n" * 63 ++ original = sc.key ++ assert len(original) <= ChangeRequestRow.idempotency_key.type.length ++ assert original == sc.key ++ row.item = row.item[:-1] + "x" ++ assert sc.key != original ++ ++ ++def replay_context(held, monkeypatch): ++ session = Mock() ++ ctx = SimpleNamespace(db=SimpleNamespace(session=lambda: nullcontext(session)), ++ operations=engine.Operations.from_integrations({}), cfg=SimpleNamespace(roles=RolePolicy()), ++ registry=SimpleNamespace(clusters={"CRC": SimpleNamespace(environment="dev")}, get=Mock())) ++ monkeypatch.setattr(api, "_full", lambda c, s, row: row) ++ session.scalars.return_value.first.return_value = held ++ return session, ctx ++ ++ ++def replay_input(): ++ body = api.OperationStart(template="rebuild-verify", parameters={"cluster-id": "CRC"}) ++ held = run_row() ++ held.idempotency_fingerprint = fingerprint(body.model_dump()) ++ return body, held ++ ++ ++def test_start_reads_the_key_after_acquiring_the_scheduler_lock(monkeypatch): ++ body, held = replay_input() ++ session, ctx = replay_context(held, monkeypatch) ++ locked = Mock() ++ monkeypatch.setattr(api, "lock_engine", locked) ++ ++ def lookup(query): ++ locked.assert_called_once_with(session) ++ return SimpleNamespace(first=lambda: held) ++ session.scalars.side_effect = lookup ++ assert api.start(body, key="key", who=STARTER, c=ctx) is held ++ ++ ++def test_replay_uses_the_stored_visibility_scope(monkeypatch): ++ body, held = replay_input() ++ held.environments = None ++ _, ctx = replay_context(held, monkeypatch) ++ monkeypatch.setattr(api, "lock_engine", lambda session: None) ++ ctx.cfg.roles = RolePolicy({"roles": {"cmapi-operator": {"environments": ["dev"]}}}) ++ with pytest.raises(Problem) as denied: ++ api.start(body, key="key", who=STARTER, c=ctx) ++ assert denied.value.status == 403 ++ ++ ++def test_start_checks_permission_before_the_key(test_config, keys, monkeypatch): ++ with build_world(test_config, keys, monkeypatch) as (client, *_): ++ response = client.post("/api/v1/operations", json={"template": "reconcile"}, ++ headers={"Authorization": "Bearer " + keys.token("viewer", roles=["cmapi-viewer"])}) ++ assert response.status_code == 403 ++ ++ ++@pytest.mark.parametrize("employee, expected", [(None, "identity-incomplete"), ("123", "approval")]) ++def test_delegated_plan_preserves_starter_checks(employee, expected, test_config, keys, monkeypatch): ++ from dataclasses import replace ++ import yaml ++ ++ with build_world(test_config, keys, monkeypatch) as (_, ctx, git, *_): ++ monkeypatch.setattr(ctx.pipeline, "auto_paused", lambda session: False) ++ monkeypatch.setattr(ctx.pipeline.capacity, "check", lambda *args, **kwargs: CapacityResult("fits", True, None, {})) ++ files = ctx.pipeline.plan_namespace(STARTER, "CRC", NS, action="create").files ++ path = next(p for p in files if yaml.safe_load(files[p])["kind"] == "ResourceQuota") ++ quota = yaml.safe_load(files[path]) ++ quota["spec"]["hard"]["requests.cpu"] = "6" ++ files[path] = yaml.safe_dump(quota) ++ git.branches["main"].update(files) ++ raw = {"environments": {"dev": {"required": 1}}, "autoApproval": {"enabled": True, "policies": [ ++ {"name": "client-policy", "requester": {"clients": [engine.WORKFLOWS_CLIENT]}}]}} ++ monkeypatch.setattr(ctx.cfg, "approvals", ApprovalRules(raw)) ++ run = run_row(template="tiers-rerender") ++ run.started_by = {**replace(STARTER, employee_id=employee).record(), "roles": list(STARTER.roles)} ++ run.parameters = {"tier": "small", "environments": ["dev"]} ++ row = step_row(run.operation_id, "rerender-namespace", "Running", "CRC/payments-dev") ++ row.inputs = {"clusterId": "CRC", "namespace": NS["namespace"]} ++ sc = engine.StepContext(ctx, Mock(), run, None, row) ++ repo = Mock() ++ repo.open_for.return_value = repo.by_idempotency.return_value = None ++ monkeypatch.setattr(ops, "RequestRepo", lambda session: repo) ++ submit = Mock(return_value=SimpleNamespace(request_id="req-example", status="pending_approval")) ++ monkeypatch.setattr(ctx.pipeline, "submit", submit) ++ if expected == "identity-incomplete": ++ with pytest.raises(Problem) as refused: ++ ops.rerender_namespace(sc) ++ assert refused.value.code == expected ++ submit.assert_not_called() ++ else: ++ ops.rerender_namespace(sc) ++ actor, plan = submit.call_args.args[:2] ++ assert actor.client_id == engine.WORKFLOWS_CLIENT and plan.requester.sub == STARTER.sub ++ assert plan.requester.record()["submittedByClient"] == actor.client_id ++ for decision in (plan.requirement, ctx.pipeline._decide(plan.facts, team_auto_today=1)): ++ assert decision.auto is None and decision.total == 1 ++ ++ ++def test_cancel_takes_the_engine_lock_before_locking_the_run(runtime, monkeypatch): ++ session, ctx = runtime ++ ctx.db = SimpleNamespace(session=lambda: nullcontext(session)) ++ ctx.cfg = SimpleNamespace(roles=RolePolicy()) ++ run = run_row() ++ session.add_all([run, step_row(run.operation_id, "list-folders", "Running")]) ++ session.flush() ++ locks = [] ++ monkeypatch.setattr(api, "lock_engine", lambda s: locks.append("engine")) ++ get_row = api._get ++ ++ def observe_get(s, operation_id, *, lock=False): ++ if lock: ++ locks.append("row") ++ return get_row(s, operation_id, lock=lock) ++ monkeypatch.setattr(api, "_get", observe_get) ++ monkeypatch.setattr(api, "AuditRepo", Mock()) ++ view = api.cancel(run.operation_id, who=STARTER, c=ctx) ++ assert view["cancelRequestedBy"] == STARTER.username ++ assert locks == ["engine", "row"] ++ ++ ++def test_unavailable_engine_and_unknown_template_remain_distinct(monkeypatch): ++ _, ctx = replay_context(None, monkeypatch) ++ monkeypatch.setattr(api, "lock_engine", lambda s: None) ++ body = api.OperationStart(template="missing") ++ for backend, status, code in (("builtin", 422, "operation-template-unknown"), ++ ("tekton", 503, "operations-engine-unavailable")): ++ ctx.operations = engine.Operations.from_integrations({"operations": {"engine": backend}}) ++ with pytest.raises(Problem) as refused: ++ api.start(body, key="unused", who=STARTER, c=ctx) ++ assert (refused.value.status, refused.value.code) == (status, code) ++ ++ ++def test_reconcile_reads_later_gitea_result_pages(monkeypatch): ++ import httpx ++ from cmapi.core.git.gitea import GiteaProvider ++ ++ git = GiteaProvider("https://example.test", "org/repo", "") ++ name = "cmapi/CRC/req-later" ++ ++ def page(operation, method, path, *, params): ++ number = params.get("page", 1) ++ branch = "main" if number == 1 else name ++ row = ({"name": branch, "commit": {"id": "sha"}} if path.endswith("/branches") else ++ {"number": 5, "head": {"ref": branch, "sha": "sha"}}) ++ return httpx.Response(200, headers={"Link": '; rel="next"'} if number == 1 else {}, json=[row]) ++ ++ monkeypatch.setattr(git, "_call", page) ++ try: ++ assert git.list_branches("cmapi/CRC/") == {name: "sha"} ++ assert [pr.branch for pr in git.list_open("cmapi/CRC/")] == [name] ++ finally: ++ git._client.close() +diff --git a/cmapi/tests/service/test_usage_verdicts_310.py b/cmapi/tests/service/test_usage_verdicts_310.py +--- a/cmapi/tests/service/test_usage_verdicts_310.py ++++ b/cmapi/tests/service/test_usage_verdicts_310.py +@@ -18,7 +18,7 @@ + import conftest # noqa: E402 + from cmapi.capacity.sweep import VerdictRepo, run_sweep # noqa: E402 + from cmapi.capacity.usage import EXPECTED_STEPS, PromUsage # noqa: E402 +-from cmapi.core.db import Database # noqa: E402 ++from cmapi.core.db import Database, REQUIRED_REVISION # noqa: E402 + from cmapi.core.db.models import AnalysisSweepRow, NamespaceVerdictRow # noqa: E402 + from cmapi.core.db.repo import JobRepo # noqa: E402 + from test_flow import NS, OLA, auth, run_jobs # noqa: E402 +@@ -323,7 +323,6 @@ + db = Database(conftest.DB_URL) + monkeypatch.setattr(db, "schema_version", lambda: "0009") + try: +- # Since #21 the code needs 0012 (capacity_snapshots, placement holds); a 0009 schema is still behind, now by three. +- assert db.schema_status() == "behind: at 0009, needs 0012" ++ assert db.schema_status() == f"behind: at 0009, needs {REQUIRED_REVISION}" + finally: + db.engine.dispose() +``` + +
diff --git a/docs/reviews/2026-12-01-issue-26-operations/reviewer-2-fable.md b/docs/reviews/2026-12-01-issue-26-operations/reviewer-2-fable.md new file mode 100644 index 00000000..01510b34 --- /dev/null +++ b/docs/reviews/2026-12-01-issue-26-operations/reviewer-2-fable.md @@ -0,0 +1,291 @@ +# PR #774 at `703da75d`: reviewer 2 (Fable) on reviewer 1's patch + +Reviewer 2 did not write the step. `final.diff` is one unified diff against `head/`: reviewer 1's patch with finding 6 taken +out, four small amendments, one more fix, the tests that go with them, and the documents that the patch left behind. It +applies to a fresh copy of `head/` with `patch -p1 -F0` and the result was tested (the last section). + +## What was measured, on PostgreSQL 16 at `127.0.0.1:55432`, fakes, no cluster + +| File | PR head (`head/` plus the new test files only) | `head/` plus `final.diff` | +|---|---|---| +| `tests/service/test_operations_26.py` | 1 failed, 20 passed: `test_cancel_during_step_suppresses_its_successor`, `'Succeeded' == 'Stopped'` | 21 passed | +| `tests/service/test_operations_review_774.py` (reviewer 1's 13 tests) | 11 failed, 2 passed | see the next row | +| `tests/service/test_operations_review_774.py` (final: 12 of reviewer 1's, 8 of reviewer 2's) | 15 failed, 5 passed | 20 passed | +| `tests/service/test_api_standard.py` | 3 failed, 174 passed (S1, the verb `Start`) | 177 passed | +| `tests/service/test_usage_verdicts_310.py` | 1 failed, 11 passed (`test_a_database_at_0009_is_behind_this_code`) | 12 passed | +| `tests/service/test_review_c_authz.py` (the authz walk) | 13 passed | 13 passed | +| `tests/service/test_models_match_migrations.py` | not run | 15 passed | +| `tests/service/test_review_h_tools_migrate.py` | not run | 24 passed | +| `tests/service/test_pr40_convergence.py` | not run | 9 passed | +| `tests/service/test_api_docs.py` | not run | 26 passed | +| `tests/service/test_api_contract.py` (the committed contract) | not run | 7 passed | +| `tests/service/test_api_samples.py` | not run | 3 passed | +| `tests/core/test_approvals.py` (reference venv) | not run | 36 passed | +| `tests/core/test_identity_metadata.py` (reference venv) | not run | 21 passed | +| `scripts/doc-citations.py --check` | 0 problems | 0 problems (14 problems on reviewer 1's patch alone) | + +What reviewer 1 could not run, now run on PostgreSQL: + +- `test_0013_roundtrip_and_its_constraints` (up, down, up, and the constraints): passed on the PR head and on the final tree. +- `test_a_worker_that_dies_mid_step_leaves_the_step_to_the_next_worker_and_one_request_is_opened`: passed on both. +- `test_cancel_during_step_suppresses_its_successor` (two sessions): failed on the PR head (`Succeeded`), passed on the + final tree (`Stopped`, one step row). +- Reviewer 1's first run of the patched tree as delivered (`codex-fix.diff` alone): `test_operations_26.py` 21 passed. + +Not tested: nothing ran on kind or CRC. No run had two worker pods. Gitea's paging was read in its source, and tested +against a stub of the provider's HTTP call, not against a Gitea. + +## Rulings on reviewer 1's 13 findings + +| # | Ruling | Severity (reviewer 1, then reviewer 2) | The guarantee the kept change protects | +|---|---|---|---| +| 1 | Accept | High, High | A request opened for the starter passes the starter's identity rules (`resolve_requester`: `employee_id`, on-behalf-of) as the starter's own request does | +| 2 | Accept, amended (documented in the code and in D3; tests on the rules alone added) | High, High | An operation never gets an approval outcome that the starter's own request would not get; a rule about the sender can add approvers, never remove one | +| 3 | Accept | High, Medium | A replay is a read: it passes the stored scope's check, as `GET /operations/{id}` does (D9) | +| 4 | Accept, amended (the refusal names the cluster and the environments; comment) | High, Medium | A run acts, and its report is read, only in the environments recorded at its start (D9) | +| 5 | Accept, amended (comment) | High, Medium | D6: after a cancel no new step starts and the run ends Stopped | +| 6 | **Reject** | High, not a defect | None: D2 decides that a Waiting row holds no slot, and the fix adds the load the cap exists to limit | +| 7 | Accept; a PostgreSQL test added | Medium, Medium | Two starts with one key start one run and both answer with it (D13); no 500 | +| 8 | Accept, amended (comment corrected) | Medium, Medium | A step's Idempotency-Key always fits `change_requests.idempotency_key` (100), so a long cluster and namespace name cannot fail the step | +| 9 | Accept | High, Medium | reconcile and `git_reconcile` read every page of branches and open pull requests before they report that none lacks its request | +| 10 | Accept | Medium, Low | The report lists the steps in the template's order, whatever the clocks say | +| 11 | Accept | Medium, Low | A caller without `operations:run` gets 403 on the start, with or without the header, as on every other write | +| 12 | Accept | Low, Low | The API standard's S1 passes; its comment sanctions the new verb | +| 13 | Accept | Low, Low | The readiness test follows `REQUIRED_REVISION` | + +### 1. The starter's identity checks: accept + +`head/cmapi/src/cmapi/core/pipeline.py:296` was `requester = requester or self.requester_for(who, body.get("onBehalfOf"))`, +and the step passed its own `Requester` (`head/cmapi/src/cmapi/ops/__init__.py:130-132`), so `resolve_requester` +(`core/identity/checks.py:70-95`) never saw the starter. Reviewer 1's change plans as the starter +(`plan_namespace(sc.starter, ..., submitted_by=sc.actor)`), so the permission, `requester_for` and the role policy all read +the starter, and only then is the workflow client attached as the sender. The row that `submit` writes is unchanged: +`requester_kind` `service`, `requester_client` `svc-cmapi-workflows`, `requester_sub` the starter's (D3), which +`test_tiers_rerender_reports_progress_and_honours_the_approval_rules` still asserts. + +Measured: `test_delegated_plan_preserves_starter_checks[None-identity-incomplete]`: `DID NOT RAISE` on the PR head, passes +on the final tree. The change is two lines and replaces a parameter (`requester`) by a simpler one (`submitted_by`). + +### 2. Delegated auto-approval: accept reviewer 1's rule; it is the simplest rule that is correct + +The question put: is "decide for the starter and for the workflow client, and require the larger quorum" the simplest +correct rule under D3? + +The facts it rests on: + +- RFC 8693, section 1.1 (, lines 203-207, fetched 2026-12-01): "With delegation + semantics, principal A still has its own identity separate from B, and it is explicitly understood that while B may have + delegated some of its rights to A, any actions taken are being taken by A representing B." A, the workflow client, keeps + its identity, and has B's rights, the starter's, and no more. +- docs/02 (`head/docs/02-technical-design-v2.md:506`): "Every request records automated, and approval rules get the facts + automated and requesterClient, so agent requests can be routed differently". So a rule may read the sender. +- `core/expression.py:26-36`: a threshold's `when:` may read `automated`, `requesterClient` and `reason`, with `not`, `==` and + `!=`. `core/approvals.py` `_matches`: a policy may name `requester.clients` and `match.reason`. + +Two simpler rules were considered and each loses a guarantee: + +1. **Decide once, with the starter's facts.** Three lines. It gives exactly the starter's outcome. But the request is then + decided as if no automation sent it: a threshold `when: automated` or `when: requesterClient == "svc-cmapi-workflows"`, + which an instance writes to put a person in front of bulk changes, no longer adds its approver, and the stored facts + would say `automated: false` beside a requester record that says `automated: true`. +2. **Decide once, with the sender's facts** (the PR head). A policy that names `svc-cmapi-workflows` approves what the + starter's own request needs a person for. Measured on the PR head: + `Requirement(rule='dev-change', slots=(), ..., auto='auto:client-policy')`. + +A threshold can be true for one identity and false for the other in either direction (`automated == False` is as valid a +line as `automated`), so no single evaluation is a bound for both. Deciding twice and taking every slot of each, with the +larger count in a shared group, is the smallest rule that keeps both. It is a dozen lines in `ApprovalRules.decide`, with no new +type, and the second set of facts is stored in the plan (`starterApprovalFacts`), so the decision that `submit` takes again +under the day's lock is the same one. + +Amendments, none of which changes reviewer 1's logic: + +- A docstring on `ApprovalRules.decide` and comments in `Pipeline._plan_namespace` that state the rule and its source. +- D3 of the design record states it, and its consequence for whoever writes approval-rules.yaml: a policy that names + `svc-cmapi-workflows` in `requester.clients`, or the operation's reason in `match.reason`, cannot approve alone. +- `"reason": None` in the starter's facts is kept: docs/02, "Changing a tier", says "the approval rules apply as for any + quota change", and a person's request has no reason. +- Tests on the rules alone, six cases (`test_a_delegated_request_needs_what_the_starter_and_the_sender_each_need`): a + policy for the client alone; a policy on the operation's reason; a policy that covers both (auto-approved); a threshold on + the sender (the larger count); a threshold that only the starter meets, with another group's slot; a policy stopped by a + sender's threshold. On the PR head the first, second and fifth fail (`'auto:workflows'`, `'auto:rerenders'`). + +### 3 and 4. The stored scope on replay and on dispatch: accept + +3: the replay now checks `operations:run`, and the template's own permissions, in `held.environments` before it returns the +run or names its ID in the 409. Reviewer 1 also moved the validation of the body after the key's lookup. That is needed, +not a liberty: D13 says the same caller, key and body "get the run it started for as long as the run is kept", and on the PR +head `_environments` ran before the lookup, so by the code (not run) a replay for a cluster since removed answers 404. Severity is +Medium, not High: the run returned is the caller's own, started when the caller had the grant. + +4: five lines in `run_step`, before the step's function, inside the savepoint, as a `StepRefused` (Failed, no retry). It +reads the cluster of the row (`cluster_id`) or of the run (`cluster-id`), as `routers/operations.py` `_environments` does at +the start. A run with no recorded environment (instance-wide, or a cluster that clusters.yaml did not name at the start) is +not checked, so cluster-onboard is unaffected. Severity is Medium: it needs an admin to move a cluster to another +environment while a run is open. Amended: the refusal reads +`CRC is not in the environments this run was started for (dev): start it again`. + +### 5. Cancel against a worker that loaded the run earlier: accept + +`advance` locks the runs with `SELECT ... FOR UPDATE`, but the job's session already holds its run, and SQLAlchemy keeps +the object it holds: "if they are matched up to the primary key in a subsequent result row, the row is not applied to the +object" (, "Populate Existing", fetched 2026-12-01). +`populate_existing` is the documented switch: "for all rows loaded, the corresponding instances in the Session will be fully +refreshed". The `s.flush()` on the line before means nothing unflushed is lost. One line; the same fix covers `job_gave_up` +and every other caller of `advance`. + +Proven on PostgreSQL with two sessions (`test_cancel_during_step_suppresses_its_successor`): `Succeeded` on the PR head, +`Stopped` with the one step row after. Severity Medium: by the code (not run), a successor that the PR head starts is then +stopped by its own job, because `run_step` refreshes the run before it calls the step; the harm measured is a cancelled run +that reads Succeeded, with a step row that should not have been created. + +### 6. Slot admission for Waiting rows: reject + +What the design says: D2, "A row that waits on something outside the engine (a request, an import, a retry's backoff) is +`Waiting`, with its next job queued for later. `maxConcurrentSteps` [...] counts only the rows `Running`", and the module's +docstring, "Waiting: its next job is queued for later and holds no slot". Reviewer 1's test asserts the opposite of a +decision the design records, so the test is wrong against the design, not the code. + +What the fix does (`codex-fix.diff`, `core/operations.py`, hunk `@@ -653,10 +653,26`), read line by line: + +- Every poll becomes two jobs: the first takes the engine's lock, sets the row Running and queues a second job that runs the + step. A run with `batchSize` 20 waiting on approvals goes from 20 to 40 jobs every 30 seconds. +- With every slot taken, each Waiting row queues itself again with `delay=1`: every Waiting row of the instance then runs one + job a second, each under the engine's lock, until a slot frees. The cap exists so that "operations never starve" the + request jobs (docs/02); this is the starvation. +- The worker "runs one job at a time" (`worker.py`, the module docstring), so "a retry executing while the slot is in use" + needs a second worker pod, and is then one step function more than the cap for the length of one step. + +Does deferring keep progress and retries correct? It keeps them correct: the timeout and the cancel are checked before the +deferral, the row's one pending job is kept by `uq_jobs_pending`, and a retry's attempt count is untouched. It is rejected +for its cost, not for a bug in it. `test_operations_26.py` passed 21 of 21 with it. + +Kept instead: D2 now says in so many words that a poll and a retry's next attempt take no slot, and why. If the owner wants +retries counted, the smaller change is to send a failed row back to Pending with a not-before time; that is a design +change, not a fix, and it is not in `final.diff`. + +### 7 to 13 + +- **7, accept.** `lock_engine` before the lookup; `advance` takes the same lock again in the same transaction, which + PostgreSQL allows. Reviewer 1's test used a session double. Added on PostgreSQL: + `test_two_starts_with_one_key_at_once_start_one_run` holds the lock on a third connection while two POSTs arrive. PR head: + `[202, 500]`, `internal-error`. Final tree: `[202, 202]`, one operation ID, one row. +- **8, accept.** A cluster ID and a namespace are up to 63 characters each; measured 167 against `String(100)`. The comment + "Keep keys already used by existing runs" was wrong (no run exists before this PR merges) and is corrected: a key that fits + stays readable for whoever debugs it. +- **9, accept.** `gitea.py` is not in the PR, but reconcile is the PR's new caller and reports "every bot branch and pull + request has its request" from one page. Gitea sets the header on both lists: `ctx.SetLinkHeader(int(totalNumOfBranches), + listOptions.PageSize)` () and + `ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)` (`.../repo/pull.go`), both fetched 2026-12-01. The loop follows + `_tree_entries` in the same file and `_pages` in `github.py`. +- **10, accept**, with one correction to the report. Reviewer 1 wrote that the bug "invalidates the report index used by the + PR's own cancel test". On this machine `test_batch_size_and_cancel` passes on the PR head. The reason is measured: the + database's clock is 0.14 s ahead of the host's (`select clock_timestamp()` against `datetime.now(timezone.utc)`, three + reads: 0.143, 0.138, 0.138), so `operations.started_at` (the database's `now()`) is later than a row's `started_at` (the + host's). With equal clocks the order flips. The fix removes the clocks from the order. +- **11, accept**, with one correction. Reviewer 1 wrote "The authz walk expects 403 for that caller". The walk + (`test_review_c_authz.py`) passes on the PR head, 13 of 13. The finding stands on its own test: a viewer's POST without the + header is 400 on the PR head and 403 after, as on the namespace writes, whose key check comes after the permission. +- **12 and 13, accept.** Test-only, as measured in the table above. + +## What reviewer 1 missed + +### R2-1. Medium, approvals: a delegated change did not carry the held-key warning of the starter's own change + +`cmapi/src/cmapi/core/pipeline.py` (PR head line 439, `if action == "update" and reason is None:`). A namespace that lacks +a required key (an adopted one, #234) gets the `missing_required_key` warning on every PATCH, and a warning keeps +auto-approval from applying (`_auto`, the `warnings` guard; docs/02, "The warning guard of auto-approval stays (#342)": "a +person approves it rather than a policy"). A plan +with a reason gets no such finding, and an operation's plan has a reason. So with reviewer 1's patch alone a policy that +covers namespace changes approves the operation's change of a namespace where it cannot approve the starter's own PATCH: +finding 2's guarantee, broken through `warnings` instead of `requesterClient`. + +Scenario, as the test builds it: Git holds `payments-dev` without `cmapi.net/team-dl`; dev needs one approver; one policy, +`match: {plugin: namespaces, actions: [update]}`. The starter's PATCH: `auto None`, `auto_fallback "warnings"`, 1 approver. +The same change with `submitted_by`: on reviewer 1's patch +`('auto:dev-changes', None, 0)`, auto-approved with no approver (measured on `hc/`); on the final tree `(None, 'warnings', 1)`, +the same as the PATCH. + +Fix (one condition; the comment says why): + +```python + if action == "update" and (reason is None or submitted_by is not None): + # A PATCH, whose body can add a key: the expiry calls (reason expiration:...) cannot, so they get no finding. An + # operation's request is decided as its starter's own PATCH would be, so it carries the finding, and the warning + # keeps auto-approval from applying to it as it does to the PATCH. + findings = [*findings, *self._held_key_findings(cluster_id, sources, labels, anns)] +``` + +Test: `test_a_delegated_change_carries_the_held_key_warning_of_the_starters_own_change` in +`tests/service/test_operations_review_774.py` (full code in `final.diff`). The reference rules have no policy for a +namespace update, so this bites only an instance that adds one; it is in lines the patch already edits, so it is fixed here. + +### R2-2. Medium, CI: reviewer 1's patch breaks `scripts/doc-citations.py --check` + +The patch moves lines in `core/pipeline.py` and `core/approvals.py`, which docs/14 and docs/21 cite by line (#178). On a +copy of the tree with `codex-fix.diff` applied, `python3 scripts/doc-citations.py --check` reports 14 problems and exits 1 +(13 "moved", and `docs/14-authorization.md:316`, `pipeline.py:296`, "changed: the cited code is not in the file any more"). +On the PR head it reports 0. + +Fix, in `final.diff`: the citation at docs/14:316 now names the line of `direct = self.requester_for(who, +body.get("onBehalfOf"))` (`pipeline.py:298`), read and recorded with `--write`; `--relocate` moved the other 15 (docs/14, +docs/21, `docs/citations.lock.json`). The check is the test: 14 problems before, `0 problems` after, exit 0. The script +needs a Git work tree, so it ran in a scratch copy with `git init` and `git add -A`; nothing was pushed. + +**The coordinator must run `--relocate` again if any other change lands in these two files before the merge.** + +### R2-3. Low, documents: the design record and a docstring described code the patch removed + +`design.md` D3 and the docstring of `core/operations.py` named `StepContext.requester`, which reviewer 1's patch deletes, +and nothing recorded the new rules. In `final.diff`: D3 (the starter's checks, the two decisions and the RFC sentence, the +held-key warning), D13 (a replay is a read; the key is read under the lock), D2 (a poll takes no slot), D14 (the recorded +environments at dispatch, the key's length, the report's order). No generated file changes: no route, model, description or +problem changed, and the contract tests in the table above pass on the final tree. + +### R2-4. Tests reviewer 1 could not write without PostgreSQL + +Covered above: finding 7 on three real connections, and finding 2 on the rules alone. Reviewer 1's test of finding 6 is +removed with the finding. + +### Seen, Low, not security, not fixed here (for one batched Backlog issue) + +Each is stated from the code; none was tested, and none is in `final.diff`. + +- `ops/templates/tiers-rerender.yaml` names no `permissions`. A custom role with `operations:run` and no `namespaces:write` + starts a run whose every item then fails 403. `permissions: [namespaces:write]` would refuse the start, as reconcile's + `approvals:pause` does. The built-in roles always hold both (`core/authz.py:28`). +- `routers/operations.py` `list_operations` reads every operations row and every step row of the rows it may show, then + pages in Python. +- `advance` gives slots to runs in the order they started, so a long rebuild-verify (no waiting steps) holds every slot + until it ends. +- `GET /operations/{id}` answers 404 for no run and 403 for a run out of scope, which tells the two apart (reviewer 1 noted + it); IDs carry 32 random bits a day. + +## Commands + +From `/cmapi/`, one file at a time, after `sysctl -n vm.loadavg` showed a 1-minute load under 16 (otherwise one +background wait until it did): + +```sh +CMAPI_TEST_DATABASE_URL=postgresql://cmapi:cmapi@127.0.0.1:55432/ PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=src:tests/service \ + /Users/olasumbo/gitRepos/workbench/cmapi/wt-655-outputs/venv-merged/bin/python -m pytest -q -W ignore -p no:cacheprovider +``` + +- Trees: `hb/` is `head/` plus the new test files only (the before-cases; database `cmapi_r774_head`). `hc/` is `head/` plus + `codex-fix.diff` plus the final review test file (the before-case of R2-1). `fin/` is a fresh copy of `head/` with + `final.diff` applied by `patch -p1 -F0` (database `cmapi_r774`); `r2/` is the working copy, identical to `fin/` + (`diff -rq --no-dereference r2 fin`). +- tests/core: the same command with `/Users/olasumbo/gitRepos/workbench/cmapi/venv-ref/bin/python`. +- Every run's whole output, with its load before and its exit code, is in `r2-out/*.txt`; the scripts are `r2-out/run.sh`, + `gate.sh`, `core.sh` and `mkdiff.sh`. `r2-out/superseded/` holds the runs of the final tree made before its last change (two + comments in `routers/operations.py` and a blank line at the end of the review test file); every file was run again on the + final tree, and those runs are the table's. The test runs left `fin/` byte-identical to `r2/`. +- `final.diff` also passes `git apply --check --whitespace=error` on a copy of `head/`. +- Both databases were created for this review (`create database cmapi_r774`, `cmapi_r774_head`). +- No command was refused. Nothing was pushed; GitHub was not written to. + +## Who wrote what + +The PR: Opus 5.5. `codex-fix.diff`: Codex (gpt-6.2-astra), reviewer 1. In `final.diff`, beyond reviewer 1's patch, by +reviewer 2 (Fable 5.2): the removal of finding 6's block and its test; the comments and the refusal text of findings 2, 4, +5 and 8; the fix of R2-1; eight tests in `test_operations_review_774.py`; `design.md`; the relocated citations. From b42883cd4a6dbe76a13bc320da7dc0f8716bc0f6 Mon Sep 17 00:00:00 2001 From: ephico2real2 Date: Tue, 1 Dec 2026 12:20:05 -0600 Subject: [PATCH 4/4] #26 CI fixes: rebuild-verify reads live, operations is a core router, the counts of the contract - rebuild-verify passed the watch cache to watch_sync._live, which since #753 B4 (merged from main) takes the cluster's reader and reads every object live: every verify-namespace step failed with AttributeError. It now passes the reader, so the verify reads the API server as the read that ends a request does. - The start's Idempotency-Key description promises the original request in its current state, as #587 requires of every write's key (the operation the key started, as GET returns it now). Behaviour unchanged. - core/plugins.py CORE gains operations: routers/operations.py is a core router (docs/02), so plugins.yaml cannot switch it and GET /admin/plugins lists it. test_plugins_switch's expected sets name the core parts, so they gain operations: the expectation changes because the core gained a part, not to pass a test. - docs/diagrams/portal-architecture/README.md and docs/08: the contract has 50 operations, and the four operations routes are listed as called by no mockup action (the mockup has no Operations view). - The contract and the portal's generated types written again for the key's text. --- cmapi-portal-ui/src/api/schema.generated.ts | 2 +- cmapi/contract/openapi.json | 4 ++-- cmapi/src/cmapi/core/plugins.py | 2 +- cmapi/src/cmapi/ops/__init__.py | 4 +++- cmapi/src/cmapi/routers/operations.py | 9 +++++---- cmapi/tests/service/test_operations_26.py | 2 +- cmapi/tests/service/test_plugins_switch.py | 6 +++--- docs/08-code-status.md | 2 +- docs/diagrams/portal-architecture/README.md | 7 ++++--- docs/reviews/2026-12-01-issue-26-operations/design.md | 3 ++- 10 files changed, 23 insertions(+), 18 deletions(-) diff --git a/cmapi-portal-ui/src/api/schema.generated.ts b/cmapi-portal-ui/src/api/schema.generated.ts index 3ac9e84b..4ceb7044 100644 --- a/cmapi-portal-ui/src/api/schema.generated.ts +++ b/cmapi-portal-ui/src/api/schema.generated.ts @@ -12838,7 +12838,7 @@ export interface operations { parameters: { query?: never; header?: { - /** @description A new random value for each new operation, such as a UUID, of at most 100 characters. Required. The same caller sending the same body with the same key gets the operation it started, in its current state, for as long as the operation is kept; the same key with another body is 409 `idempotency-replay`. */ + /** @description A new random value for each new operation, such as a UUID, of at most 100 characters. Required. The same caller retrying the same body with the same key gets the original request in its current state: the operation that the key started, as `GET /api/v1/operations/{id}` returns it now, for as long as the operation is kept. The same key with another body is 409 `idempotency-replay`. */ "Idempotency-Key"?: string | null; }; path?: never; diff --git a/cmapi/contract/openapi.json b/cmapi/contract/openapi.json index f812c1ef..05084b41 100644 --- a/cmapi/contract/openapi.json +++ b/cmapi/contract/openapi.json @@ -22294,7 +22294,7 @@ "operationId": "operations_start", "parameters": [ { - "description": "A new random value for each new operation, such as a UUID, of at most 100 characters. Required. The same caller sending the same body with the same key gets the operation it started, in its current state, for as long as the operation is kept; the same key with another body is 409 `idempotency-replay`.", + "description": "A new random value for each new operation, such as a UUID, of at most 100 characters. Required. The same caller retrying the same body with the same key gets the original request in its current state: the operation that the key started, as `GET /api/v1/operations/{id}` returns it now, for as long as the operation is kept. The same key with another body is 409 `idempotency-replay`.", "in": "header", "name": "Idempotency-Key", "required": false, @@ -22307,7 +22307,7 @@ "type": "null" } ], - "description": "A new random value for each new operation, such as a UUID, of at most 100 characters. Required. The same caller sending the same body with the same key gets the operation it started, in its current state, for as long as the operation is kept; the same key with another body is 409 `idempotency-replay`.", + "description": "A new random value for each new operation, such as a UUID, of at most 100 characters. Required. The same caller retrying the same body with the same key gets the original request in its current state: the operation that the key started, as `GET /api/v1/operations/{id}` returns it now, for as long as the operation is kept. The same key with another body is 409 `idempotency-replay`.", "examples": [ "0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10" ], diff --git a/cmapi/src/cmapi/core/plugins.py b/cmapi/src/cmapi/core/plugins.py index b7c48372..8fa250e4 100644 --- a/cmapi/src/cmapi/core/plugins.py +++ b/cmapi/src/cmapi/core/plugins.py @@ -38,7 +38,7 @@ # The built-in plugins with a write, which is what an override stops. tests/service/test_plugins_switch.py holds this to the routers. WRITERS: frozenset[str] = frozenset({"namespaces", "adoption", "capacity"}) # The routers of cmapi.routers. They are the service itself, so plugins.yaml cannot name them. -CORE: frozenset[str] = frozenset({"core", "requests", "admin"}) +CORE: frozenset[str] = frozenset({"core", "requests", "operations", "admin"}) class PluginSwitch: diff --git a/cmapi/src/cmapi/ops/__init__.py b/cmapi/src/cmapi/ops/__init__.py index 87e08fa4..b98341c3 100644 --- a/cmapi/src/cmapi/ops/__init__.py +++ b/cmapi/src/cmapi/ops/__init__.py @@ -196,7 +196,9 @@ def verify_namespace(sc: StepContext) -> StepResult: files, sha = ctx.pipeline.read_folder(cid, ns) if not files: return StepResult.skipped("the folder holds no manifest", outcome="empty") - read = read_plan(_live(ctx.registry.cache(cid)), ns, files, None, **_rules(ctx)) + # Every object read live from the API server through the cluster's reader, never from the watch cache, as the read that + # ends a request does since #753 B4: a watch that missed an event would report a rebuilt cluster as matching. + read = read_plan(_live(ctx.registry.cache(cid).client), ns, files, None, **_rules(ctx)) differences = [d.view() for d in read.differences] return StepResult.done(outcome="match" if read.ok else "drift", compared=read.compared, commit=sha, differences=differences[:50], differenceCount=len(differences)) diff --git a/cmapi/src/cmapi/routers/operations.py b/cmapi/src/cmapi/routers/operations.py index b8171b62..2788498d 100644 --- a/cmapi/src/cmapi/routers/operations.py +++ b/cmapi/src/cmapi/routers/operations.py @@ -131,10 +131,11 @@ class OperationPage(Api): def start_key(idempotency_key: str | None = Header(default=None, alias="Idempotency-Key", examples=["0d5f3c1e-7a44-4f0b-9b55-3f1a2c8e6d10"], description="A new random value for each new operation, such as a UUID, " - "of at most 100 characters. Required. The same caller sending " - "the same body with the same key gets the operation it " - "started, in its current state, for as long as the operation " - "is kept; the same key with another body is 409 " + "of at most 100 characters. Required. The same caller retrying " + "the same body with the same key gets the original request in " + "its current state: the operation that the key started, as " + "`GET /api/v1/operations/{id}` returns it now, for as long as " + "the operation is kept. The same key with another body is 409 " "`idempotency-replay`.")) -> str: if not idempotency_key: raise Problem.bad_request("idempotency-key-required", "Idempotency-Key header is required on writes") diff --git a/cmapi/tests/service/test_operations_26.py b/cmapi/tests/service/test_operations_26.py index 91bee74b..af584d5a 100644 --- a/cmapi/tests/service/test_operations_26.py +++ b/cmapi/tests/service/test_operations_26.py @@ -394,7 +394,7 @@ def test_rebuild_verify_reads_every_folder_against_the_cluster_and_reports_drift op_id = start(world, "rebuild-verify", {"cluster-id": "CRC"}).json()["operationId"] drive(ctx) view = get(world, op_id) - assert view["phase"] == "Succeeded" + assert view["phase"] == "Succeeded", [(r["item"], r["lastError"]) for r in view["steps"]] rows = {r["item"]: r for r in rows_of(view, "verify-namespace")} assert rows["kept"]["outputs"]["outcome"] == "match" assert rows["drifted"]["outputs"]["outcome"] == "drift" and rows["drifted"]["outputs"]["differenceCount"] == 1 diff --git a/cmapi/tests/service/test_plugins_switch.py b/cmapi/tests/service/test_plugins_switch.py index e27ee616..8dc69be4 100644 --- a/cmapi/tests/service/test_plugins_switch.py +++ b/cmapi/tests/service/test_plugins_switch.py @@ -45,11 +45,11 @@ def refused(plugin: str, env: str) -> float: def test_without_the_file_each_built_in_plugin_is_mounted(world): client, _, _, _, _, keys = world spec = client.get("/openapi.json").json() - assert {t["name"] for t in spec["tags"]} == {"core", "requests", "admin", *ALL} + assert {t["name"] for t in spec["tags"]} == {"core", "requests", "operations", "admin", *ALL} listed = client.get("/api/v1/admin/plugins", headers=auth(keys, "ada", **ADMIN)).json() assert listed["configured"] is False and listed["instance"] == "nonprod" assert [(p["name"], p["core"], p["enabled"], p["disabledEnvironments"]) for p in listed["items"]] == [ - ("admin", True, True, []), ("core", True, True, []), ("requests", True, True, []), + ("admin", True, True, []), ("core", True, True, []), ("operations", True, True, []), ("requests", True, True, []), ("adoption", False, True, []), ("capacity", False, True, []), ("directory", False, True, []), ("expiration", False, True, []), ("namespaces", False, True, []), ("policies", False, True, []), ("quotas", False, True, []), ("tiers", False, True, [])] @@ -87,7 +87,7 @@ def test_a_plugin_that_is_not_enabled_has_no_route_no_tag_and_no_line_in_the_spe def test_an_empty_list_leaves_the_core_only(test_config, tmp_path, fresh_db, keys, monkeypatch): with build_world(config_with(test_config, tmp_path, {"enabled": []}), keys, monkeypatch) as (client, *_): spec = client.get("/openapi.json").json() - assert {t["name"] for t in spec["tags"]} == {"core", "requests", "admin"} + assert {t["name"] for t in spec["tags"]} == {"core", "requests", "operations", "admin"} assert client.get("/api/v1/me", headers=auth(keys, "ola", **OLA)).status_code == 200 assert client.get("/api/v1/clusters/CRC/namespaces", headers=auth(keys, "ola", **OLA)).status_code == 404 diff --git a/docs/08-code-status.md b/docs/08-code-status.md index a1f58e17..86a83cf0 100644 --- a/docs/08-code-status.md +++ b/docs/08-code-status.md @@ -87,7 +87,7 @@ The design is `docs/01`, section "API documentation: Swagger UI and ReDoc". This | The pages | `/docs` is Swagger UI and `/redoc` is ReDoc. Both load only the bundles in the image, from `/static`. No page loads a file from another server. `/docs` links cmapi's stylesheet `/docs/swagger.css`, which imports Swagger UI's and keeps the page within a 390 px phone with every operation open (#556, #558) | `test_the_pages_load_only_from_this_server`, `test_swagger_ui_loads_the_bundles_stylesheet_through_cmapis`, and the 390 and 1440 px checks of `cmapi-portal-ui/tests/front-door.test.mjs` | | A source checkout | The bundles are not in a checkout. Then the two pages answer 503 `docs-assets-missing` and name the command. `cmapi-tools docs-assets --static-dir ` fetches the two npm packages at the versions and SHA-256 values of the `ARG` lines in `cmapi/Containerfile`. A wrong hash writes no file | `test_without_the_bundles_the_pages_say_so_and_name_the_command`, `test_docs_assets_fetches_what_the_containerfile_pins_and_refuses_another_hash` | | Tags and groups | Each plugin has one tag with a description and `x-plugin-version`. `x-tagGroups` has the six groups of `docs/01`. A router that the app does not include is not in the document | `test_each_tag_has_a_description_and_is_in_exactly_one_of_the_six_groups`, `test_a_plugin_that_is_not_included_is_not_in_the_spec` | -| curl samples | Each of the 46 operations has one `x-codeSamples` entry. It uses the instance's `publicUrl`, the documented example of each parameter, and `Authorization: Bearer $TOKEN`. A write sends `Idempotency-Key` and `If-Match` where it takes them. A conditional read sends neither optional precondition, `If-Match` or `If-None-Match` (#590). The body of a write is its recorded request, the one "Try it out" sends, so it holds together across fields (#349). The test sends each sample to the app, and a `policy-violation` fails it | `test_each_operation_has_one_curl_sample_that_the_app_accepts` | +| curl samples | Each of the 50 operations has one `x-codeSamples` entry. It uses the instance's `publicUrl`, the documented example of each parameter, and `Authorization: Bearer $TOKEN`. A write sends `Idempotency-Key` and `If-Match` where it takes them. A conditional read sends neither optional precondition, `If-Match` or `If-None-Match` (#590). The body of a write is its recorded request, the one "Try it out" sends, so it holds together across fields (#349). The test sends each sample to the app, and a `policy-violation` fails it | `test_each_operation_has_one_curl_sample_that_the_app_accepts` | | ETag | `/openapi.json` and `/openapi.yaml` each have a strong ETag: the first 32 hexadecimal characters of the SHA-256 of the bytes served. `If-None-Match` with that value returns 304. `If-Match` is evaluated first (RFC 9110, section 13.2.2): one that does not list the ETag, by the strong comparison, returns 412 `precondition-failed`, and `*` holds. The same on `GET /api/v1/metadata-keys` and `GET /api/v1/capacity` (#590), and on the files under `/static/swagger` and `/static/redoc`, which also read `If-Unmodified-Since` (412) and `If-Modified-Since` (304) against their `Last-Modified` (#604, #619, #620) | `test_each_document_has_a_strong_etag_and_answers_304_to_the_same_one`, `test_a_conditional_read_evaluates_if_match_first`, `test_static_preconditions_604.py` | | `Range` on `/static` | Each file under `/static/swagger` and `/static/redoc` answers 200 with the whole file, or 304, whatever `Range` and `If-Range` say, and both say `Accept-Ranges: none` (RFC 9110, sections 14.2 and 14.3; #649). Starlette's range code is never reached from `/static` | `test_static_range_649.py` | | Parameters | Each path, query and header parameter has a description and an example. `check_documented` stops startup without one | `test_each_parameter_in_the_spec_has_a_description_and_an_example`, `test_a_parameter_without_a_description_or_an_example_stops_startup` | diff --git a/docs/diagrams/portal-architecture/README.md b/docs/diagrams/portal-architecture/README.md index 21c73d82..957b1fcb 100644 --- a/docs/diagrams/portal-architecture/README.md +++ b/docs/diagrams/portal-architecture/README.md @@ -2,7 +2,7 @@ This folder holds one figure set. It shows the architecture of cmapi as the portal mockup sees it. -The source is `mockups/portal/Main.dc.html`, read in full at commit `ecc5cb3`. The list of built endpoints is `cmapi/contract/openapi.json`, which has 46 operations. `cmapi/tests/service/test_portal_map.py` holds this map to that file: a row that says built names an operation of it, a row that says not built names none, and the counts and the list of unused operations are true. +The source is `mockups/portal/Main.dc.html`, read in full at commit `ecc5cb3`. The list of built endpoints is `cmapi/contract/openapi.json`, which has 50 operations. `cmapi/tests/service/test_portal_map.py` holds this map to that file: a row that says built names an operation of it, a row that says not built names none, and the counts and the list of unused operations are true. The map is held to the contract by a test. The portal that calls these endpoints is measured in `docs/09-portal-ui-testing.md`, each result with the cluster or the stand-in it ran on. @@ -131,7 +131,7 @@ Three boxes were dashed because their state was not certain or not there. Argo C ## Built endpoints that no mockup action calls -The mockup has no action for these 25 operations of `openapi.json`: +The mockup has no action for these 29 operations of `openapi.json`: - `GET /api/v1/me`, `GET /api/v1/version`, `GET /api/v1/clusters` - `POST /api/v1/clusters/{id}:probe`: recheck a held cluster import (#397); the mockup has no probe action @@ -143,6 +143,7 @@ The mockup has no action for these 25 operations of `openapi.json`: - `GET /api/v1/admin/git-log`, `GET /api/v1/admin/integrations`, `POST /api/v1/admin/prune:confirm`, `GET /api/v1/admin/plugins` - `GET /api/v1/clusters/{cluster_id}/capacity` and `POST /api/v1/clusters/{cluster_id}/capacity/snapshots:run`: one cluster's stored snapshot, and a run now (#21) - `GET /api/v1/clusters/{cluster_id}/adoption/candidates`, `GET /api/v1/clusters/{cluster_id}/adoption/skipped` and `POST /api/v1/clusters/{cluster_id}/namespaces/{ns}:adopt`: story #26. Main.dc.html has no adoption screen; the portal's Adopt view calls them, from its own mockup, mockup-adopt.html in docs/reviews/2026-11-14-issue-26-adoption/ +- `POST /api/v1/operations`, `GET /api/v1/operations`, `GET /api/v1/operations/{operation_id}` and `POST /api/v1/operations/{operation_id}:cancel`: story #26, criterion 3 (the built-in operations engine). The mockup has no Operations view, so no portal screen calls them yet; a screen needs an approved mockup first ## Text twins @@ -159,7 +160,7 @@ CMAPI cmapi-api (built): core/auth.py, routers/requests.py, plugins/namespaces, routers/admin.py, core/pipeline.py, plugins/quotas and tiers, core/validate, plugins/directory, core/registry.py, routers/me and health not built: routes for one namespace's expiry read, capacity snapshots, placement, metadata, - operations, service accounts, grants, tokens, webhooks + service accounts, grants, tokens, webhooks (operations: built, #26, with no portal action) ------> Keycloak (JWKS, admin API) ------> PostgreSQL (requests, approvals, audit, jobs) - - proposed - -> cmapi-capacity diff --git a/docs/reviews/2026-12-01-issue-26-operations/design.md b/docs/reviews/2026-12-01-issue-26-operations/design.md index c29ea948..c39dab8e 100644 --- a/docs/reviews/2026-12-01-issue-26-operations/design.md +++ b/docs/reviews/2026-12-01-issue-26-operations/design.md @@ -227,7 +227,8 @@ read under the engine's lock, so two starts with one key at the same moment star - The locks, in one order everywhere: a step's job locks its own row, then the engine's advisory lock, then the runs' rows; a cancel takes the engine's lock before its run's row. A scheduler pass touches only Pending rows and the Waiting rows it can lock without waiting (`SKIP LOCKED`), never a row whose job runs (`lock_engine`). -- rebuild-verify reads each folder against the cluster with the read that ends a request (`read_plan`, #751), not Argo CD's +- rebuild-verify reads each folder against the cluster with the read that ends a request (`read_plan`, #751), each object + read live from the API server and never from the watch cache (#753 B4), not Argo CD's sync status: "a deliverer's report is never the proof" (docs/02, "Delivery modes and the read that ends a request"). ## Tests