From d61fa5267d2643bd24d7ac860ea3084e12317d3e Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 6 Nov 2026 20:37:39 +0000 Subject: [PATCH 1/2] feat(roadmap): size the runner Job resources from the plan --- docs/CONFIGURATION.md | 2 +- docs/ENV_VARS.md | 1 + docs/ROUTINE_TASKS.md | 2 +- k8s/README.md | 5 +- .../roadmap-service/admissionpolicy.yaml | 24 ++- .../.openspec.yaml | 2 + .../design.md | 25 ++++ .../proposal.md | 60 ++++++++ .../specs/roadmap-implement-job/spec.md | 57 +++++++ .../specs/roadmap-implement-runner/spec.md | 20 +++ .../tasks.md | 49 ++++++ src/devops_cli/config/defaults.py | 4 + src/devops_cli/config/settings.py | 15 ++ src/devops_cli/k8s/cluster_job.py | 20 ++- src/devops_cli/k8s/cluster_job_api.py | 6 +- src/devops_cli/roadmap/implement_size.py | 91 ++++++++++++ src/devops_cli/roadmap/implement_submit.py | 39 +++-- src/devops_cli/roadmap/plan_read.py | 11 ++ tests/gate/k8s_checks/job_admission_policy.py | 95 +++++++++++- tests/k8s/test_k8s_cluster_job_api.py | 38 +++++ tests/roadmap/test_roadmap_implement_size.py | 140 ++++++++++++++++++ .../roadmap/test_roadmap_implement_submit.py | 96 ++++++++++++ tests/security/test_config_declarations.py | 1 + 23 files changed, 778 insertions(+), 25 deletions(-) create mode 100644 openspec/changes/3193-size-the-runner-job-resources/.openspec.yaml create mode 100644 openspec/changes/3193-size-the-runner-job-resources/design.md create mode 100644 openspec/changes/3193-size-the-runner-job-resources/proposal.md create mode 100644 openspec/changes/3193-size-the-runner-job-resources/specs/roadmap-implement-job/spec.md create mode 100644 openspec/changes/3193-size-the-runner-job-resources/specs/roadmap-implement-runner/spec.md create mode 100644 openspec/changes/3193-size-the-runner-job-resources/tasks.md create mode 100644 src/devops_cli/roadmap/implement_size.py create mode 100644 tests/roadmap/test_roadmap_implement_size.py diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 6461e63444..faf873c631 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -278,7 +278,7 @@ roadmap configuration settings. |---|---|---|---|---| | `alternatives` | `AlternativesConfig` | `limit=5 first_pass_limit=20 recheck_days=30 retry_days=3` | - | - | | `stage` | `RoadmapStageConfig` | `filter=['status=ready'] limit=3 planned_limit=20 step_tokens=64000 retry_hours=6 toolset='extended'` | - | - | -| `implement` | `RoadmapImplementConfig` | `effort=['low', 'medium'] in_runner=False repair_rounds=3 step_token_budget=8000000 item_token_budget=20000000 step_time_limit_seconds=5400 item_time_limit_seconds=12600 digest_clears_per_class=1 digest_clears_per_item=3 continuations_per_item=2 ladder={'plan': ['devops-coder'], 'edit': ['devops-coder'], 'repair': ['devops-coder'], 'review': ['devops-coder']} request_timeout_seconds=1200 command_timeout_seconds=1800 monitor_timeout_seconds=3600 deadline_stall_seconds=4200 deadline_extension_seconds=5400 deadline_ceiling_seconds=14400` | - | - | +| `implement` | `RoadmapImplementConfig` | `effort=['low', 'medium'] in_runner=False repair_rounds=3 step_token_budget=8000000 item_token_budget=20000000 step_time_limit_seconds=5400 item_time_limit_seconds=12600 digest_clears_per_class=1 digest_clears_per_item=3 continuations_per_item=2 ladder={'plan': ['devops-coder'], 'edit': ['devops-coder'], 'repair': ['devops-coder'], 'review': ['devops-coder']} request_timeout_seconds=1200 command_timeout_seconds=1800 monitor_timeout_seconds=3600 deadline_stall_seconds=4200 deadline_extension_seconds=5400 deadline_ceiling_seconds=14400 max_memory_limit='8Gi'` | - | - | | `inbox` | `RoadmapInboxConfig` | `draft_days=7 wait_days=7` | - | - | ## Firecrawl Configuration (`firecrawl`) diff --git a/docs/ENV_VARS.md b/docs/ENV_VARS.md index 253663fb67..028278e572 100644 --- a/docs/ENV_VARS.md +++ b/docs/ENV_VARS.md @@ -108,6 +108,7 @@ All configuration options for `devops-cli` can be overridden via environment var | `DEVOPS_CLI_ROADMAP_IMPLEMENT_ITEM_TIME_LIMIT_SECONDS` | `roadmap.implement.item_time_limit_seconds` | No | The most seconds that one run of an item may take for its steps, counted from the start of the run. It must not be above `deadline_ceiling_seconds`, so the stop names this setting before the deadline ends the Job without a comment | | `DEVOPS_CLI_ROADMAP_IMPLEMENT_ITEM_TOKEN_BUDGET` | `roadmap.implement.item_token_budget` | No | The most input tokens that all the steps of one run of an item may use, the fix steps included. A step that starts after the budget is spent makes no request, and the item stops with the class `limit_reached`. A new run after a stop starts a new count | | `DEVOPS_CLI_ROADMAP_IMPLEMENT_LADDER` | `roadmap.implement.ladder` | No | The model tiers of each step class (`plan`, `edit`, `repair`, `review`), one tier per attempt, weakest first. A step moves to the next tier when a failure class selects `change_tier`, or when its run ends on a provider error, and the move spends no repair round. The gateway's health is read before a tier is chosen, and an unhealthy tier is skipped. A tier is a local gateway group, a hosted group that this setting names, or an `ollama:` model. The default names the local `devops-coder` group only | +| `DEVOPS_CLI_ROADMAP_IMPLEMENT_MAX_MEMORY_LIMIT` | `roadmap.implement.max_memory_limit` | No | The memory limit of every runner Job that the Service creates, as a whole number of Gi such as `8Gi`. The memory request follows the size of the plan (2Gi or 6Gi), and this limit is the burst class above it. It must not be below the largest request, 6Gi, and it must fit the smallest node of the cluster: a Job that bursts past the node memory starves the other pods | | `DEVOPS_CLI_ROADMAP_IMPLEMENT_MONITOR_TIMEOUT_SECONDS` | `roadmap.implement.monitor_timeout_seconds` | No | The most seconds that the implement job waits for the checks of a pull request to settle after a push. When it runs out, the item stops | | `DEVOPS_CLI_ROADMAP_IMPLEMENT_REPAIR_ROUNDS` | `roadmap.implement.repair_rounds` | No | The most extra turns that one implementation step gives the agent after its first run: one for each failed `ruff`, `mypy` or hook of the project. A missing tick takes no round, because the job ticks the group when its checks pass. The same number bounds the fix steps that the scoped checks before a push cause. When no round is left, the step or the item stops. 0 gives the agent no extra turn | | `DEVOPS_CLI_ROADMAP_IMPLEMENT_REQUEST_TIMEOUT_SECONDS` | `roadmap.implement.request_timeout_seconds` | No | The seconds that one model call of an implementation step may take, the read of its stream included. A call that runs past it ends the step as stopped. Keep it under the timeout of the LLM gateway router (1500 s in the stack), or the router ends the call first | diff --git a/docs/ROUTINE_TASKS.md b/docs/ROUTINE_TASKS.md index e819fea9de..555a329939 100644 --- a/docs/ROUTINE_TASKS.md +++ b/docs/ROUTINE_TASKS.md @@ -326,7 +326,7 @@ Executed on workspace initialization (DevContainer startup) or on-demand. #### 5. Roadmap Implement Job (Runner) - **Frequency**: Continuous. The Service's row `implement` is due every 7 minutes ([k8s/README.md](../k8s/README.md), Roadmap service step 16). -- **Methodology**: The Service runs no step. In namespace `devops` it makes a runner Job from the suspended CronJob `devops-cli-runner` for the first Staged or Planned item (a Planned item has its plan on the default branch because a person merged the staging pull request; the job makes its branch and its draft pull request), and makes no second Job for the repository while one runs. The runner has the dev tools, 2 CPU, 4 Gi of memory (8 Gi at most) and a deadline that the Service extends while the log of the Job changes, up to 14400 s, and ends after 2400 s without a change (`roadmap.implement.deadline_*`); its pod has no Kubernetes token, and its shell gets none of the variables of the job, except the uv paths and the worker bound of the test runner. The Service's ServiceAccount has a Role that creates, reads and patches Jobs, lists pods and reads pod logs in that namespace, and nothing else ([k8s/README.md](../k8s/README.md), Runner Jobs). A later round comments the state and the end of the log on the item. A Job that leaves its item In Progress, or Ready or Planned with no stop, sets the item Blocked and records `implement.stopped` as `job`. A person's comment `implement: retry` clears the stop. A stop `job` whose class has the action `retry` is also cleared by a continuation, up to `roadmap.implement.continuations_per_item` times (`implement.continuations`). A new runner image also clears a stop. The class of the stop must have the action `retry`, and the limits per class and per item must allow it (`implement.job_digest`, `implement.digest_clears`). A person merges the pull request. +- **Methodology**: The Service runs no step. In namespace `devops` it makes a runner Job from the suspended CronJob `devops-cli-runner` for the first Staged or Planned item (a Planned item has its plan on the default branch because a person merged the staging pull request; the job makes its branch and its draft pull request), and makes no second Job for the repository while one runs. The runner has the dev tools, a CPU and memory request that follow the number of files in the plan (1 CPU and 2 Gi, or 4 CPU and 6 Gi; `roadmap.implement.max_memory_limit`, 8 Gi by default, is the memory limit) and a deadline that the Service extends while the log of the Job changes, up to 14400 s, and ends after 2400 s without a change (`roadmap.implement.deadline_*`); its pod has no Kubernetes token, and its shell gets none of the variables of the job, except the uv paths and the worker bound of the test runner. The Service's ServiceAccount has a Role that creates, reads and patches Jobs, lists pods and reads pod logs in that namespace, and nothing else ([k8s/README.md](../k8s/README.md), Runner Jobs). A later round comments the state and the end of the log on the item. A Job that leaves its item In Progress, or Ready or Planned with no stop, sets the item Blocked and records `implement.stopped` as `job`. A person's comment `implement: retry` clears the stop. A stop `job` whose class has the action `retry` is also cleared by a continuation, up to `roadmap.implement.continuations_per_item` times (`implement.continuations`). A new runner image also clears a stop. The class of the stop must have the action `retry`, and the limits per class and per item must allow it (`implement.job_digest`, `implement.digest_clears`). A person merges the pull request. - **Commands**: ```bash kubectl -n devops get jobs -l implement-repo diff --git a/k8s/README.md b/k8s/README.md index 87835f7764..6f2e14460a 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -660,10 +660,11 @@ kubectl -n devops logs -f job/ The implement job runs tests, `ruff`, `mypy` and OpenSpec, which the Service image does not hold. A step runs `ruff check` on every changed Python file. It runs `mypy` with the options of `devops ci typecheck` on the changed files under `src/`, and no type check on a test file, because the gate checks `src` only (`src/devops_cli/ci/typecheck.py` is the one definition). Its steps run in a runner Job (#2667). `devops roadmap implement --item --confirm`, run on a workstation, makes one by hand for that item and follows its log (`--no-wait` prints the Job's name, `--dry-run` prints the Job). It refuses an item that an agent or a person claimed, an item that is neither Ready nor Planned, and a repository that has a runner Job that has not ended. It makes the Job with the code of `devops k8s run-job --template runner --repo -- roadmap implement --repo --item --confirm`, which is the way to pass `--filter` or `--limit` to the job. Both commands label the Job and its pod `implement-repo=`, the label that the row `implement` lists its Jobs by, and make no Job while a Job with that label has not ended. The label is a digest of the lower-case repository name. The lock is best effort: each command lists the Jobs just before it creates one, so a Job that starts between the two calls is not seen. If the App is not installed on the repository, the Job fails in its pod, and the error in its log names the repository. `--repo` is required with the runner template: it sets `service.github_app.token_repository` on the Job, and the job runs no step unless that setting equals the repository it acts on. The Service makes one for each Staged or Planned item in the row `implement` (Roadmap service, step 16). - **Image.** Stage `runner` of the `Dockerfile` is the `builder` stage with git, the dev dependencies of `uv.lock` (pytest, ruff, mypy, bandit, deptry, ast-grep, zizmor, pre-commit), and the tools that the gate and the hooks need (#3072): `curl` and `jq` from apt, and promtool at the pin of `tools.lock`, installed with `devops install-tools`. The table `RUNNER_TOOLS` in `src/devops_cli/roadmap/runner_tools.py` lists every tool with the reason it is there and its version command, and `NOT_IN_RUNNER` lists each program that the image leaves out, with the reason (no cluster tool, no scanner that the gate does not install, no npm, no tool that fails the image scan). The image holds neither `actionlint` nor `shellcheck` nor Trivy: the image scan fails on the newest release of each (Go standard library 1.27.0 in `actionlint` 1.17.0, go-jose 4.1.5 in Trivy 0.76.1), so a Job cannot run the `actionlint` row or the IaC scan, and without npm it cannot run the `audit` row. The pull request runs them. #3108 tracks their return. The apt tools have no pin, because Debian gives the version and a pin would fail the build on each security update; the image holds `git` 2.47.3, `curl` 8.14.1 and `jq` 1.7. The last step of the stage runs `python -m devops_cli.roadmap.runner_tools`, so an image that lacks a tool or holds it at another version than its pin does not build. Tests fail when a `devops ci` row, a hook of `.pre-commit-config.yaml`, a required job of `ci.yml`, a live-marked test or an entry of `tools.lock` needs a program that is in neither table, and when a pin of the table differs from a Dockerfile. The Service image holds none of the added tools. `trivy image --scanners vuln --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 --ignorefile .trivyignore` on the built stage exits 0. The measured growth is 56 MB compressed (522 MB to 578 MB, as `docker save` output through `gzip -1`) and about 70 MB in the new layers, which adds the transfer of those layers to the first pull on a node (about 5 s on 100 Mbit/s). The promtool step of the build takes 19 s. The smoke test of `ci.yml` and `release.yml` runs the same check on the loaded image and fails when `docker image inspect` reports more than 3000000000 bytes (2.51 GB measured). The release publishes the image as `ghcr.io/dan-petty/devops-cli/runner`, next to the Service image, and Image Updater keeps it on the digest of `latest` (Service Image Updates). Each Job runs `uv run` in its own worktree, with the uv cache on the home volume. -- **Template.** Suspended CronJob `devops-cli-runner` has 2 CPU, 4 Gi of memory requested and 8 Gi at most, an `emptyDir` home of 4 Gi, an `emptyDir` `/tmp` of 1 Gi, `ephemeral-storage` of 2 Gi requested and 6 Gi at most, `activeDeadlineSeconds: 7200` and `backoffLimit: 0`. It sets `DEVOPS_CLI_ROADMAP_IMPLEMENT_IN_RUNNER=true`, which no other pod sets, and `PYTEST_XDIST_AUTO_NUM_WORKERS=2`, the CPU limit, because `pytest-xdist` counts the CPUs of the node and not of the pod (about 280 MB for each worker). It uses ServiceAccount `devops-cli`, which mounts no token, and the Secret `devops-cli` through `envFrom`. A Job is made from the template and changes only the args, the name, the labels and the environment value `DEVOPS_CLI_SERVICE_GITHUB_APP_TOKEN_REPOSITORY`. +- **Template.** Suspended CronJob `devops-cli-runner` has 2 CPU, 4 Gi of memory requested and 8 Gi at most (the default of a manual run; the Service sets the size of its Jobs, see Size), an `emptyDir` home of 4 Gi, an `emptyDir` `/tmp` of 1 Gi, `ephemeral-storage` of 2 Gi requested and 6 Gi at most, `activeDeadlineSeconds: 7200` and `backoffLimit: 0`. It sets `DEVOPS_CLI_ROADMAP_IMPLEMENT_IN_RUNNER=true`, which no other pod sets, and `PYTEST_XDIST_AUTO_NUM_WORKERS=2`, the CPU limit, because `pytest-xdist` counts the CPUs of the node and not of the pod (about 280 MB for each worker). It uses ServiceAccount `devops-cli`, which mounts no token, and the Secret `devops-cli` through `envFrom`. A Job is made from the template and changes only the args, the name, the labels, the environment values `DEVOPS_CLI_SERVICE_GITHUB_APP_TOKEN_REPOSITORY` and `PYTEST_XDIST_AUTO_NUM_WORKERS`, the deadline and the CPU and memory values of `resources` (see Size and Deadline). - **Role.** ServiceAccount `roadmap-service` is the account of the Service pod. Role `roadmap-service-jobs` in namespace `devops` allows `create`, `get`, `list` and `patch` on `jobs`, `get` on CronJob `devops-cli-runner`, `get` on Deployment `roadmap-service` (#2917), `list` on `pods` and `get` on `pods/log`, and nothing else. Kubernetes limits `create` and `list` to no name, and the name of each Job is new, so those two and `patch` cover the namespace. The `patch` moves the deadline of a Job (see Deadline); the admission policy checks a patch as it checks a create. A holder of the Role can make any pod that Pod Security `restricted` admits in namespace `devops`, and such a pod can take Secret `devops-cli`. The Service pod holds that Secret already, so the Role gives no new secret. That holds only while namespace `devops` holds no Secret but `devops-cli`, so the admission policy below pins the Jobs of the Service. The Service pod mounts a projected token that expires after one hour; the client reads it again as the kubelet renews it. A Job pod mounts no token. -- **Admission policy.** ValidatingAdmissionPolicy `roadmap-service-jobs` and its binding (`k8s/devops/roadmap-service/admissionpolicy.yaml`, #2696) refuse a `CREATE` or an `UPDATE` of a Job in namespace `devops` unless the Job has: one container and no init container, with no `command`; the image `ghcr.io/dan-petty/devops-cli/runner`, alone or followed by `:` or `@`; ServiceAccount `devops-cli` with `automountServiceAccountToken: false`; only Secret `devops-cli` in `envFrom` and no `valueFrom` in `env`; only the volumes `tmp`, `home` and `config` of the template; no `hostNetwork`, `hostPID` or `hostIPC`; no `priorityClassName`, `nodeName`, `imagePullSecrets` or `manualSelector`; the pod label `app.kubernetes.io/name: devops-cli-job`, because the NetworkPolicies select pods by that label and a Job pod with the label of the Service would take its egress to the API server; `completions` and `parallelism` of 1 or not set; `backoffLimit: 0`; and an `activeDeadlineSeconds` of 14400 at most (`CONST_ROADMAP_IMPLEMENT_DEADLINE_CAP_SECONDS`, the most that the setting `roadmap.implement.deadline_ceiling_seconds` may be; a test holds both). The policy applies only to the user `system:serviceaccount:devops:roadmap-service`. It never evaluates a Job of another identity, such as the CLI user (`devops k8s run-job`), Argo CD or the CronJob controller. It runs in the API server, so no webhook can be down. `failurePolicy` is `Fail`: if an expression errors, the Job of the Service is refused, the create raises an error, and the next round tries again. Argo CD syncs the policy with the other manifests of the stack, and AppProject `homelab` already admits the two cluster-scoped kinds. The test `tests/test_k8s_job_admission_policy.py` runs the expressions against the Job that CronJob `devops-cli-runner` makes, so a change of the template that the policy refuses fails in CI. To check the live policy, make a Job as the Service with `kubectl --as=system:serviceaccount:devops:roadmap-service create --dry-run=server -f `. These are not pinned: the tag or digest of the image, the `args`, the plain `env` values, the resources, `nodeSelector`, `tolerations`, `hostUsers`, the security context (Pod Security `restricted` checks the pod) and the number of Jobs. A person with an admin role can delete the policy, and Argo CD restores it. +- **Admission policy.** ValidatingAdmissionPolicy `roadmap-service-jobs` and its binding (`k8s/devops/roadmap-service/admissionpolicy.yaml`, #2696) refuse a `CREATE` or an `UPDATE` of a Job in namespace `devops` unless the Job has: one container and no init container, with no `command`; the image `ghcr.io/dan-petty/devops-cli/runner`, alone or followed by `:` or `@`; ServiceAccount `devops-cli` with `automountServiceAccountToken: false`; only Secret `devops-cli` in `envFrom` and no `valueFrom` in `env`; only the volumes `tmp`, `home` and `config` of the template; no `hostNetwork`, `hostPID` or `hostIPC`; no `priorityClassName`, `nodeName`, `imagePullSecrets` or `manualSelector`; the pod label `app.kubernetes.io/name: devops-cli-job`, because the NetworkPolicies select pods by that label and a Job pod with the label of the Service would take its egress to the API server; `completions` and `parallelism` of 1 or not set; `backoffLimit: 0`; an `activeDeadlineSeconds` of 14400 at most (`CONST_ROADMAP_IMPLEMENT_DEADLINE_CAP_SECONDS`, the most that the setting `roadmap.implement.deadline_ceiling_seconds` may be; a test holds both); and a CPU request that equals the CPU limit and is 1 with a memory request of 2Gi, or 4 with 6Gi (the table of Size), a memory limit, and a `PYTEST_XDIST_AUTO_NUM_WORKERS` that equals the CPU limit. The policy applies only to the user `system:serviceaccount:devops:roadmap-service`. It never evaluates a Job of another identity, such as the CLI user (`devops k8s run-job`), Argo CD or the CronJob controller. It runs in the API server, so no webhook can be down. `failurePolicy` is `Fail`: if an expression errors, the Job of the Service is refused, the create raises an error, and the next round tries again. Argo CD syncs the policy with the other manifests of the stack, and AppProject `homelab` already admits the two cluster-scoped kinds. The gate check `tests/gate/k8s_checks/job_admission_policy.py` (row `k8s` of `devops ci`) runs the expressions against the Job that CronJob `devops-cli-runner` makes, so a change of the template that the policy refuses fails in CI. To check the live policy, make a Job as the Service with `kubectl --as=system:serviceaccount:devops:roadmap-service create --dry-run=server -f `. These are not pinned: the tag or digest of the image, the `args`, the plain `env` values but the worker count, the memory limit, `nodeSelector`, `tolerations`, `hostUsers`, the security context (Pod Security `restricted` checks the pod) and the number of Jobs. A person with an admin role can delete the policy, and Argo CD restores it. - **Network.** Policy `roadmap-service-egress` admits the Service pod, and no other pod, to TCP 6443, with the cloud metadata address excluded. A Job pod keeps the egress of `devops-default-perimeter`: DNS, the gateway, the cache, the OTLP collector and public HTTPS. No policy admits it to the API server. +- **Size.** The Service sizes the CPU and the memory request of a Job from its plan (#3193). It counts the distinct file paths in the code spans of `tasks.md`, read from `origin/` for a Planned item and from the branch of a Staged item, and takes a row of the table `RUNNER_SIZES` in `src/devops_cli/roadmap/implement_size.py`: at most 10 files, 1 CPU (request and limit) and 2 Gi of memory requested; more than 10 files, 4 CPU and 6 Gi. Each row names its measured sample: 2 Gi is above the 1.24 GB peak of the 10 Jobs that did not run out of memory, and 6 Gi is above the 4.13 GB that the killed Job had reached (#2806). The Service sets `PYTEST_XDIST_AUTO_NUM_WORKERS` to the CPU limit of the same Job, so the two cannot differ. The memory limit of every Job is the setting `roadmap.implement.max_memory_limit` (default `8Gi`, a whole number of Gi, not below 6Gi), which the admission policy does not pin. A change of a row is a change of the table and of the policy in one pull request: a gate check admits each row and every pair of a grid around them, and expects that only the rows pass. A Job from `devops k8s run-job` or `devops roadmap implement --item` keeps the size of the template. - **Deadline.** The Service makes the Job with `activeDeadlineSeconds` set to `roadmap.implement.deadline_extension_seconds` (default 5400) and the annotation `roadmap.devops-cli/progress-at` (#3063). The CronJob template keeps 7200 for `devops k8s run-job`. In each round the Service reads the last 20 lines of the log of each such Job that has not ended. The runner writes one line for each tool call, so a log that changed since the last round is progress. The Service then sets the deadline to the seconds since the Job started plus the extension step, up to `roadmap.implement.deadline_ceiling_seconds` (default 14400). It never lowers a deadline on progress. It keeps the digest of the log and the time of the progress in the annotations `roadmap.devops-cli/progress` and `roadmap.devops-cli/progress-at` of the Job, so a restart loses nothing. A log that stays the same for `roadmap.implement.deadline_stall_seconds` (default 2400) is a stall: the Service sets the deadline to the seconds since the start and the annotation `roadmap.devops-cli/stalled`, the Job controller ends the Job with the reason `DeadlineExceeded`, and the report on the item names the stall. Each change is a span `implement.deadline` with the Job, the old and the new deadline and the reason (`progress`, `progress, ceiling` or `stall`). The defaults come from the longest wait in which the runner writes no line: the watch of the checks of a pull request, 1800 s. The stall is 600 s above it. The extension is above the stall by a row (7 minutes) and a tick of the Service (151 s), so the Service sees a stall before the deadline passes; a test holds both. The settings validate: the stall is not above the extension, the extension is not above the ceiling, and the ceiling is not above 14400. The memory limit stays the 8 Gi of the template. - **Guarantees.** The shell of a step has none of the variables of the job, except the uv paths and the worker bound of the test runner. A step cannot read the environment or the memory of the job process, because the job clears its dumpable flag. The installation token of the job names one repository (`service.github_app.token_repository`), and the job runs no step unless that setting equals its repository and the process acts as the GitHub App. A Job ends by its deadline, 14400 s at most, and is not retried. The token is in the environment of a `git` or `gh` child of the job while that child runs, and a process of the same user can read it through `/proc`. A pod cannot hide it: the default seccomp profile refuses the user namespace that a sandbox for the shell needs. So the job guarantees an order: it adopts the orphans of its children, and when a step ends it kills every process the step left, also a daemon in a session of its own, before it runs any `git` or `gh`. A process that survives stops the item. These properties are not guaranteed: public HTTPS is open, so a step can send the clone to a public host; and a step runs as the same user as the job, so it can change the files that the job reads later, such as the clone, `.git/config` and the hooks of the worktree. A hook runs inside a `git` child of the job, with the token in its environment. The token limits the harm to one repository, to the permissions of ADR 0015 and to one hour. Those permissions include workflow files, so a workflow on a pushed branch can run with the secrets of the repository before a person reviews it. A real sandbox for the shell is planned (see Person steps). A person merges every pull request. - **Person steps.** After the first release that publishes the runner image, a person makes the GHCR package `runner` public, as the package `service` is. The Job takes the whole Secret `devops-cli`. A narrower Secret for the runner is the better end state, and a person makes secrets. A follow-up is filed: a real sandbox for the shell of a step ([#2695](https://github.com/dan-petty/devops-cli/issues/2695)). After the first sync of the admission policy, a person checks once that the Service's Job passes it, with the `kubectl --as` command of the policy above. diff --git a/k8s/devops/roadmap-service/admissionpolicy.yaml b/k8s/devops/roadmap-service/admissionpolicy.yaml index 8cac104e59..f5d228ab38 100644 --- a/k8s/devops/roadmap-service/admissionpolicy.yaml +++ b/k8s/devops/roadmap-service/admissionpolicy.yaml @@ -9,8 +9,13 @@ # the stack select pods by that label: a Job pod with the label of the Service would take its # egress to the API server. The Job runs its pod once, and it has no `command`, no # `imagePullSecrets`, no `priorityClassName` and no `nodeName`. -# Not pinned: the tag or digest of the image, the args and the plain `env` values, the resources, -# `nodeSelector`, `tolerations`, `hostUsers` and the number of Jobs (k8s/README.md, Runner Jobs). +# The CPU and the memory request of the container are a row of the size table of the Service +# (`RUNNER_SIZES` in src/devops_cli/roadmap/implement_size.py, #3193); a gate check holds the two +# equal. The memory limit is not pinned, because the setting `roadmap.implement.max_memory_limit` +# raises it. +# Not pinned: the tag or digest of the image, the args and the plain `env` values but one, the +# memory limit, `nodeSelector`, `tolerations`, `hostUsers` and the number of Jobs (k8s/README.md, +# Runner Jobs). apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicy metadata: @@ -129,6 +134,21 @@ spec: object.spec.activeDeadlineSeconds <= 14400 message: The Job must set a deadline (activeDeadlineSeconds) of 14400 seconds at most. reason: Forbidden + # The rows of `RUNNER_SIZES`: CPU 1 with 2Gi, and CPU 4 with 6Gi. The CPU request equals the + # CPU limit, and the worker count of the test runner equals the CPU limit, because + # `pytest-xdist` counts the CPUs of the node and not of the pod (#2806). + - expression: >- + object.spec.template.spec.containers.all(c, has(c.resources) && + has(c.resources.requests) && has(c.resources.limits) && + has(c.resources.requests.cpu) && has(c.resources.requests.memory) && + has(c.resources.limits.cpu) && has(c.resources.limits.memory) && + c.resources.requests.cpu == c.resources.limits.cpu && + ((c.resources.limits.cpu == "1" && c.resources.requests.memory == "2Gi") || + (c.resources.limits.cpu == "4" && c.resources.requests.memory == "6Gi")) && + has(c.env) && c.env.exists(e, e.name == "PYTEST_XDIST_AUTO_NUM_WORKERS" && + has(e.value) && e.value == c.resources.limits.cpu)) + message: The CPU and the memory request must be a row of the size table (1 CPU with 2Gi, or 4 CPU with 6Gi), the CPU request must equal the CPU limit, the memory limit must be set, and PYTEST_XDIST_AUTO_NUM_WORKERS must equal the CPU limit. + reason: Forbidden --- apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicyBinding diff --git a/openspec/changes/3193-size-the-runner-job-resources/.openspec.yaml b/openspec/changes/3193-size-the-runner-job-resources/.openspec.yaml new file mode 100644 index 0000000000..8a94d76947 --- /dev/null +++ b/openspec/changes/3193-size-the-runner-job-resources/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-06 diff --git a/openspec/changes/3193-size-the-runner-job-resources/design.md b/openspec/changes/3193-size-the-runner-job-resources/design.md new file mode 100644 index 0000000000..0ece84bb25 --- /dev/null +++ b/openspec/changes/3193-size-the-runner-job-resources/design.md @@ -0,0 +1,25 @@ +# Design + +## Decisions + +- **The size comes from the files that the tasks name.** The issue names it. The Service can count it before the Job starts, from `tasks.md` that the round can read with git. The count is the distinct paths in code spans: a span that has a `/` and no space, or a root file with a known suffix. The tasks of a plan name the files they read and change, so the count follows the work of the Job. +- **Two rows.** The repository holds two measured peaks, so the table has two rows, split at 10 files. A middle row would have no measurement behind it. +- **CPU request equals CPU limit, and the worker count is the CPU.** `pytest-xdist` counts the CPUs of the node, not of the pod (#2806). The row holds one CPU value, and the Service writes it to the limit, the request and `PYTEST_XDIST_AUTO_NUM_WORKERS`. One source cannot disagree with itself, and a test checks the Job of each row. +- **The memory limit is a setting, not a row value.** The limit is a burst class that protects the node. It is the same for both rows, 8Gi, and `roadmap.implement.max_memory_limit` raises it. The configuration refuses a value below the largest request, because the API refuses a Job whose request is above its limit. +- **The table is a constant next to the sizing code.** The policy mirrors it, and one gate check holds the two equal: it tries each CPU and memory pair in a grid and expects that exactly the rows of the table pass. +- **The Service overrides the spec before it creates the Job.** The policy sees the final spec, and no second write races the policy. `build_job` takes `resources` and replaces only the values it names. +- **The template keeps 2 CPU and 4Gi.** A Job that a person starts by hand is not selected by the policy and needs a valid default. +- **A plan that is archived at its revision counts zero files.** A retry after a stop in the scoped checks finds the change archived on the branch (#3645). The work left is the checks and the push, which fit the small row. +- **A failed read of the plan stops the round.** The round reads the default branch with git in the same way before it chooses an item, and a failure there raises `GitOperationError`. The size uses the same rule, and the round writes nothing before it has the size. + +## Rejected alternatives + +- **Three rows.** The repository holds no third measured peak, so the middle row would be a guess. +- **A formula from the file count.** It gives values that no measurement backs, and the policy cannot list them. +- **The packed token count.** The pack step runs inside the Job, after the request is fixed. +- **The peak memory of the previous Job.** A new plan has no previous Job. +- **A key in the Service config for the table.** A config change would not change the policy, so the policy would refuse the new class. +- **Patch the Job after it is created.** The policy would admit the template size first, and a patch can be refused after the Job exists. +- **A flag of `devops k8s run-job`.** The Service calls the API. A flag adds a process between the Service and the cluster. +- **LimitRange.** A LimitRange cannot refuse a request above the table and cannot check the environment value. +- **Parse the quantity with the Kubernetes client.** `kubernetes.utils` imports the whole client, which the startup budget refuses for a settings module. The setting is a whole number of Gi, which a pattern checks. diff --git a/openspec/changes/3193-size-the-runner-job-resources/proposal.md b/openspec/changes/3193-size-the-runner-job-resources/proposal.md new file mode 100644 index 0000000000..131e2b0d2f --- /dev/null +++ b/openspec/changes/3193-size-the-runner-job-resources/proposal.md @@ -0,0 +1,60 @@ +# Proposal + +## Why + +Issue #3193. The runner Job has one resource class for every item: 2 CPU and 4 Gi of memory requested, 8 Gi at most. A small item holds the same request as a refactor of 40 files, so the scheduler reserves memory and CPU that the Job never uses. The change that gave the Job a progress-based deadline (#3063) left the sizing out. + +## What Changes + +- New module `src/devops_cli/roadmap/implement_size.py` with the size table `RUNNER_SIZES` and `runner_size`. The table has two rows, chosen by the number of files that the tasks of the plan name: + - Small, at most 10 files: CPU request and limit 1, memory request 2Gi. + - Large, more than 10 files: CPU request and limit 4, memory request 6Gi. + - Each row names the measured Job sample and its peak memory. The memory request of a row is above that peak. + - `plan_file_count` counts the distinct file paths in the code spans of `tasks.md`. +- The Service sizes the Job in `run_implement_round`. It reads `tasks.md` of the item at the revision that holds the plan (`origin/` for a Planned item, `origin/` for a Staged item), counts the files, and passes the resources and the value of `PYTEST_XDIST_AUTO_NUM_WORKERS` to the Job. Both values come from the CPU of the row, so they cannot differ. +- `build_job` and `ClusterJobs.create` take `resources`, which replaces the named request and limit values of the container of the template. The other values of the template, such as `ephemeral-storage`, stay. +- New setting `roadmap.implement.max_memory_limit` (default `8Gi`, variable `DEVOPS_CLI_ROADMAP_IMPLEMENT_MAX_MEMORY_LIMIT`). It sets the memory limit of every runner Job that the Service creates. It is a whole number of Gi, and the configuration refuses a value below the largest memory request of the table. +- The admission policy `roadmap-service-jobs` gets one rule: the CPU request equals the CPU limit and is 1 with 2Gi, or 4 with 6Gi, and the environment value `PYTEST_XDIST_AUTO_NUM_WORKERS` equals the CPU limit. The memory limit is not pinned, so the setting can raise it. +- The template `k8s/devops/cronjob-runner.yaml` keeps 2 CPU and 4Gi, the default of a manual run (`devops k8s run-job`, `devops roadmap implement --item`). The policy does not select those Jobs. A gate check keeps its `PYTEST_XDIST_AUTO_NUM_WORKERS` equal to its CPU limit. +- Documents: `k8s/README.md` (Runner Jobs), and the generated `docs/ENV_VARS.md` and `docs/CONFIGURATION.md`. +- Observable behavior changes (a setting, the Job spec, a manifest), so the change carries a spec delta. +- The change fits one pull request. + +### Out of scope + +- A third row or a formula. The repository holds two measured peaks only (see Feasibility), so a middle row would be a guess. +- Any change in the cluster. A person lets Argo CD sync the policy with the Service image. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `roadmap-implement-job`: MODIFIED the memory limit requirement. ADDED the size table, the worker count, the table provenance and the setting. +- `roadmap-implement-runner`: ADDED the rule of the policy for the resources of a Job of the Service. + +## Impact + +- Code: `src/devops_cli/roadmap/implement_size.py` (new), `src/devops_cli/roadmap/implement_submit.py`, `src/devops_cli/roadmap/plan_read.py`, `src/devops_cli/k8s/cluster_job.py`, `src/devops_cli/k8s/cluster_job_api.py`, `src/devops_cli/config/settings.py`, `src/devops_cli/config/defaults.py`. +- Manifests: `k8s/devops/roadmap-service/admissionpolicy.yaml`. +- Documents: `k8s/README.md`, `docs/ENV_VARS.md`, `docs/CONFIGURATION.md` (generated). +- Tests: `tests/roadmap/test_roadmap_implement_size.py` (new), `tests/roadmap/test_roadmap_implement_submit.py`, `tests/k8s/test_k8s_cluster_job_api.py`, `tests/gate/k8s_checks/job_admission_policy.py`, `tests/roadmap/test_roadmap_limit_classes.py`, `tests/security/test_config_declarations.py`. + +## Feasibility + +Checked on 2026-11-06 against the repository on `origin/main`: + +- The issue says that the staging commit lacks a Job spec builder, the setting and the policy. The builder exists now: `build_job` in `src/devops_cli/k8s/cluster_job.py`, which the Service calls through `ClusterJobs.create` in `run_implement_round`. The policy exists too: `k8s/devops/roadmap-service/admissionpolicy.yaml` (#2696). Only the setting `roadmap.implement.max_memory_limit` is missing, and the change adds it. +- The template sets 2 CPU request and limit, 4Gi memory request, 8Gi memory limit and `PYTEST_XDIST_AUTO_NUM_WORKERS=2`, and the gate check `check_the_runner_bounds_the_workers_of_the_test_runner_to_its_cpu_limit` holds the last equal to the CPU limit (`k8s/devops/cronjob-runner.yaml`, `tests/gate/k8s_checks/runner.py`). +- The measured peaks are in the archived change `2806-runner-memory-and-command-log` and in the comment of the template: 1.24 GB at most over the 10 Jobs that did not run out of memory, and 4.13 GB for the Job that the kernel killed at its 4 Gi cap. 2Gi covers the first, and 6Gi covers the second. The memory limit stays 8Gi, which fits the smallest node (15.5 Gi allocatable, measured then with `kubectl get nodes`). +- The Service has the plan at the moment it creates the Job. `tasks.md` is on `origin/` for a Planned item and on `origin/` for a Staged item, and the judge of the round has read the plan already. The count needs no model call. +- The policy runs standard CEL. `check_the_expressions_use_only_standard_cel` compiles each expression with `cel_expr_python`, so the new rule is tested with the same engine as the other rules. The API server stores `1`, `4`, `2Gi` and `6Gi` unchanged, because they are in canonical form. +- Command output on the base: `uv run devops ci test tests/roadmap/test_roadmap_implement_submit.py tests/k8s/test_k8s_cluster_job_api.py` passes. +- The premise holds. The issue asks for a measured table, and the repository holds two measured points, so the table has two rows. + +## Existing Tool Considered + +The alternatives check of 2026-11-05 found no tool. VPA and KRR set requests from observed usage after pods ran. They cannot size a Job from its plan before the first run, set `PYTEST_XDIST_AUTO_NUM_WORKERS`, or write the admission policy. The change builds a two-row table and passes it to the existing Job builder. Written cost: about 60 000 tokens and 3 hours to build; about 4 000 tokens each month to keep it and to move the table when a new peak is measured. It deletes no code. diff --git a/openspec/changes/3193-size-the-runner-job-resources/specs/roadmap-implement-job/spec.md b/openspec/changes/3193-size-the-runner-job-resources/specs/roadmap-implement-job/spec.md new file mode 100644 index 0000000000..9434738d77 --- /dev/null +++ b/openspec/changes/3193-size-the-runner-job-resources/specs/roadmap-implement-job/spec.md @@ -0,0 +1,57 @@ +## MODIFIED Requirements + +### Requirement: The memory limit of a runner Job stays 8 Gi +The runner Job that the Service creates SHALL have the memory limit of the setting `roadmap.implement.max_memory_limit`, whose default is 8Gi, whatever the deadline settings and the size of the plan are. + +#### Scenario: The memory limit +- **WHEN** a round creates a Job and the setting is not set +- **THEN** the memory limit of its container is 8Gi + +#### Scenario: A raised limit +- **WHEN** the setting is 12Gi and a round creates a Job +- **THEN** the memory limit of its container is 12Gi + +## ADDED Requirements + +### Requirement: The Service sizes the runner Job from the plan +The Service SHALL choose the CPU request, the CPU limit and the memory request of a runner Job from the table `RUNNER_SIZES` by the number of files that the plan names: the small row (CPU 1, memory 2Gi) for at most 10 files, and the large row (CPU 4, memory 6Gi) for more. The other values of the template SHALL stay. + +#### Scenario: A plan with few files and a plan with many +- **WHEN** a round creates a Job for a plan whose tasks name 3 files, and another round creates a Job for a plan whose tasks name 12 files +- **THEN** the first Job requests 1 CPU and 2Gi, the second requests 4 CPU and 6Gi, and each keeps the `ephemeral-storage` of the template + +### Requirement: The files of a plan are the paths in its tasks +The Service SHALL count the distinct file paths in the code spans of `tasks.md`, read at the revision that holds the plan: `origin/` for a Planned item and `origin/` for a Staged item. A change that is archived at that revision SHALL count zero files. + +#### Scenario: Paths are counted once +- **WHEN** the tasks name the same file in several tasks, and name commands and settings in code spans +- **THEN** the count holds each file path once and holds no command and no setting + +#### Scenario: A Planned item +- **WHEN** the plan of a Planned item is on the default branch and names 11 files +- **THEN** the Job of the item has the large row + +### Requirement: The worker count of a runner Job equals its CPU limit +The Service SHALL set `PYTEST_XDIST_AUTO_NUM_WORKERS` of the Job to the CPU limit of the same Job, and the CPU request SHALL equal the CPU limit. + +#### Scenario: Every row +- **WHEN** a test reads each row of the table and the Job that the Service creates for it +- **THEN** the CPU request, the CPU limit and the value of `PYTEST_XDIST_AUTO_NUM_WORKERS` are equal + +### Requirement: The size table cites its measurements +Each row of `RUNNER_SIZES` SHALL name the measured Job sample and its peak memory, and the memory request of the row SHALL be above that peak. + +#### Scenario: The rows +- **WHEN** a test reads the table +- **THEN** each row has a sample name and a peak, and its memory request is above the peak + +### Requirement: The memory limit is a setting that holds the largest request +The setting `roadmap.implement.max_memory_limit` SHALL have the default 8Gi and the variable `DEVOPS_CLI_ROADMAP_IMPLEMENT_MAX_MEMORY_LIMIT`. It SHALL be a whole number of Gi, and the configuration SHALL refuse a value below the largest memory request of the table. + +#### Scenario: The default +- **WHEN** the configuration is loaded with no value +- **THEN** the setting is 8Gi + +#### Scenario: A value below the largest request or in another form +- **WHEN** the setting is 5Gi, 8G or 8192Mi +- **THEN** the configuration is refused diff --git a/openspec/changes/3193-size-the-runner-job-resources/specs/roadmap-implement-runner/spec.md b/openspec/changes/3193-size-the-runner-job-resources/specs/roadmap-implement-runner/spec.md new file mode 100644 index 0000000000..3a4d7cec92 --- /dev/null +++ b/openspec/changes/3193-size-the-runner-job-resources/specs/roadmap-implement-runner/spec.md @@ -0,0 +1,20 @@ +## ADDED Requirements + +### Requirement: The policy admits only the sizes in the table +The policy SHALL refuse a Job of the Service unless the CPU request of its container equals the CPU limit, the pair of the CPU and the memory request is a row of `RUNNER_SIZES`, the container has a memory limit, and the value of `PYTEST_XDIST_AUTO_NUM_WORKERS` equals the CPU limit. It SHALL not pin the memory limit. + +#### Scenario: A Job of each row +- **WHEN** a test builds the Job that the Service makes for each row of the table and evaluates the policy for the Service user +- **THEN** the policy admits the Job + +#### Scenario: A size outside the table +- **WHEN** a test tries each pair of CPU and memory request from a grid that holds the rows and values near them +- **THEN** the policy admits exactly the pairs of the table + +#### Scenario: A worker count that differs +- **WHEN** the Job sets `PYTEST_XDIST_AUTO_NUM_WORKERS` to a value other than its CPU limit, or sets a CPU request other than its CPU limit +- **THEN** the policy refuses the Job + +#### Scenario: A raised memory limit +- **WHEN** the Job of a row sets a memory limit of 12Gi +- **THEN** the policy admits the Job diff --git a/openspec/changes/3193-size-the-runner-job-resources/tasks.md b/openspec/changes/3193-size-the-runner-job-resources/tasks.md new file mode 100644 index 0000000000..7f8e1b3ad3 --- /dev/null +++ b/openspec/changes/3193-size-the-runner-job-resources/tasks.md @@ -0,0 +1,49 @@ +# Tasks + +## 1. The size table and the memory limit setting + +Kind: behavior + +- [x] 1.1 Write failing tests in `tests/roadmap/test_roadmap_implement_size.py` for the scenarios of "The Service sizes the runner Job from the plan" (the count and the rows), "The worker count of a runner Job equals its CPU limit", "The size table cites its measurements" and "The memory limit is a setting that holds the largest request" + - Verification: `uv run devops ci test tests/roadmap/test_roadmap_implement_size.py` +- [x] 1.2 Write `src/devops_cli/roadmap/implement_size.py`, the setting `roadmap.implement.max_memory_limit` with its default, and the entry in `tests/security/test_config_declarations.py` + - Verification: `uv run devops ci test tests/roadmap/test_roadmap_implement_size.py tests/security/test_config_declarations.py tests/roadmap/test_roadmap_limit_classes.py` + +## 2. The resources in the Job builder + +Kind: behavior + +- [x] 2.1 Write failing tests in `tests/k8s/test_k8s_cluster_job_api.py` for a Job made with `resources`, and for a Job made with none + - Verification: `uv run devops ci test tests/k8s/test_k8s_cluster_job_api.py` +- [x] 2.2 Add `resources` to `build_job` and `ClusterJobs.create` + - Verification: `uv run devops ci test tests/k8s/test_k8s_cluster_job_api.py` + +## 3. The size in the round + +Kind: behavior + +- [x] 3.1 Write failing tests in `tests/roadmap/test_roadmap_implement_submit.py` for the scenarios of a small and a large plan, a Planned item, the storage of the template and the raised memory limit + - Verification: `uv run devops ci test tests/roadmap/test_roadmap_implement_submit.py` +- [x] 3.2 Add `tasks_at` to `src/devops_cli/roadmap/plan_read.py`, and size the Job in `run_implement_round` of `src/devops_cli/roadmap/implement_submit.py` + - Verification: `uv run devops ci test tests/roadmap/test_roadmap_implement_submit.py tests/roadmap/test_roadmap_implement_deadline.py` + +## 4. The admission policy + +Kind: manifests + +- [x] 4.1 Update the checks in `tests/gate/k8s_checks/job_admission_policy.py` for the Job of each row, the grid of sizes, the worker count and the Job with the size of the template, then add the rule to `k8s/devops/roadmap-service/admissionpolicy.yaml` + - Verification: `uv run devops ci --check --no-cache --only k8s` + +## 5. The documents + +Kind: documents + +- [x] 5.1 Update the runner sections of `k8s/README.md` and `docs/ROUTINE_TASKS.md`, and regenerate the generated documents + - Verification: `uv run devops docs generate --sync-readme` and `uv run devops docs check` +- [x] 5.2 Archive the change + - Verification: `uv run devops openspec archive 3193-size-the-runner-job-resources` + +## Workflow follow-up + +- Pending a person: let Argo CD sync the policy `roadmap-service-jobs` with the new Service image. A Service that still runs the old image creates a Job with the size of the template, which the new rule refuses, and the round tries again when the new image runs. +- Pending a person: review the diff in tuicr (tuicr -r ..HEAD). diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index 5de39645c3..546fdb41d7 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -815,6 +815,10 @@ DEFAULT_ROADMAP_IMPLEMENT_DEADLINE_STALL_SECONDS: int = 4200 DEFAULT_ROADMAP_IMPLEMENT_DEADLINE_EXTENSION_SECONDS: int = 5400 DEFAULT_ROADMAP_IMPLEMENT_DEADLINE_CEILING_SECONDS: int = 14400 +# The memory limit of every runner Job that the Service creates (#3193): twice the 4.13 GB that the +# killed Job had reached, and below the 15 Gi that the smallest node can allocate (#2806). The +# memory request follows the plan (`devops_cli.roadmap.implement_size`). +DEFAULT_ROADMAP_IMPLEMENT_MAX_MEMORY_LIMIT: str = "8Gi" # The labels of the items the stage job takes when no setting and no option names others: every # Ready item, of any type, priority, value and effort (#2906). DEFAULT_ROADMAP_STAGE_FILTER: Final[tuple[str, ...]] = ("status=ready",) diff --git a/src/devops_cli/config/settings.py b/src/devops_cli/config/settings.py index 0e45cec152..56bfb52643 100644 --- a/src/devops_cli/config/settings.py +++ b/src/devops_cli/config/settings.py @@ -107,6 +107,7 @@ DEFAULT_ROADMAP_IMPLEMENT_ITEM_TIME_LIMIT_SECONDS, DEFAULT_ROADMAP_IMPLEMENT_ITEM_TOKEN_BUDGET, DEFAULT_ROADMAP_IMPLEMENT_LADDER_TIERS, + DEFAULT_ROADMAP_IMPLEMENT_MAX_MEMORY_LIMIT, DEFAULT_ROADMAP_IMPLEMENT_MONITOR_TIMEOUT_SECONDS, DEFAULT_ROADMAP_IMPLEMENT_REPAIR_ROUNDS, DEFAULT_ROADMAP_IMPLEMENT_REQUEST_TIMEOUT_SECONDS, @@ -151,6 +152,7 @@ from devops_cli.core.untrusted_trees import reads_untrusted_trees from devops_cli.exceptions import ConfigurationError from devops_cli.lang import ERRORS +from devops_cli.roadmap.implement_size import MIN_MEMORY_LIMIT_GI from devops_cli.roadmap.stage_filter import split_filter_entry from devops_cli.valkey.endpoint import ValkeyEndpoint, parse_valkey_url @@ -1025,6 +1027,19 @@ class RoadmapImplementConfig(BaseModel): ge=1, le=CONST_ROADMAP_IMPLEMENT_DEADLINE_CAP_SECONDS, ) + max_memory_limit: Annotated[str, Variable()] = Field( + description="The memory limit of every runner Job that the Service creates, as a whole number of Gi such as `8Gi`. The memory request follows the size of the plan (2Gi or 6Gi), and this limit is the burst class above it. It must not be below the largest request, 6Gi, and it must fit the smallest node of the cluster: a Job that bursts past the node memory starves the other pods", + default=DEFAULT_ROADMAP_IMPLEMENT_MAX_MEMORY_LIMIT, + pattern=r"^[1-9][0-9]*Gi$", + ) + + @field_validator("max_memory_limit") + @classmethod + def _check_max_memory_limit(cls, value: str) -> str: + """The limit is not below the largest memory request of the size table.""" + if int(value.removesuffix("Gi")) < MIN_MEMORY_LIMIT_GI: + raise ValueError(f"max_memory_limit must not be below {MIN_MEMORY_LIMIT_GI}Gi") + return value @field_validator("ladder", mode="before") @classmethod diff --git a/src/devops_cli/k8s/cluster_job.py b/src/devops_cli/k8s/cluster_job.py index b7d6341c9a..ce02682787 100644 --- a/src/devops_cli/k8s/cluster_job.py +++ b/src/devops_cli/k8s/cluster_job.py @@ -86,6 +86,17 @@ def _with_env(container: dict[str, Any], env: Mapping[str, str] | None) -> None: container["env"] = [*kept, *({"name": name, "value": value} for name, value in env.items())] +def _with_resources( + container: dict[str, Any], resources: Mapping[str, Mapping[str, str]] | None +) -> None: + """Replace the request and limit values that `resources` names; the other values stay.""" + if not resources: + return + held = container.setdefault("resources", {}) + for kind, values in resources.items(): + held[kind] = {**held.get(kind, {}), **values} + + def template_container(pod_spec: dict[str, Any], template: JobTemplate) -> dict[str, Any]: """The container of `pod_spec` that the template names. Raises ClusterJobError when the pod spec has none.""" @@ -118,13 +129,15 @@ def build_job( labels: Mapping[str, str] | None = None, deadline: int | None = None, annotations: Mapping[str, str] | None = None, + resources: Mapping[str, Mapping[str, str]] | None = None, ) -> dict[str, Any]: - """The Job the CronJob's template makes, with only args, name, labels, `env`, the deadline - and the annotations changed. + """The Job the CronJob's template makes, with only args, name, labels, `env`, the deadline, + the annotations and the `resources` changed. The labels go on the Job and on its pods, so `-l app.kubernetes.io/name=devops-cli-job` finds both. The annotations go on the Job only. `deadline` replaces the - `activeDeadlineSeconds` of the template. + `activeDeadlineSeconds` of the template. `resources` maps `requests` and `limits` to the values + that replace those of the container, such as `{"requests": {"memory": "2Gi"}}`. """ job_template = cronjob["spec"]["jobTemplate"] spec = copy.deepcopy(job_template["spec"]) @@ -133,6 +146,7 @@ def build_job( container = template_container(pod_template["spec"], template) container["args"] = list(args) _with_env(container, env) + _with_resources(container, resources) metadata = _labelled(job_template.get("metadata"), labels) metadata.update(name=name, namespace=JOB_NAMESPACE) if annotations: diff --git a/src/devops_cli/k8s/cluster_job_api.py b/src/devops_cli/k8s/cluster_job_api.py index 8b53eb3b23..4cfb711c01 100644 --- a/src/devops_cli/k8s/cluster_job_api.py +++ b/src/devops_cli/k8s/cluster_job_api.py @@ -97,10 +97,11 @@ def create( cronjob: dict[str, Any] | None = None, deadline: int | None = None, annotations: Mapping[str, str] | None = None, + resources: Mapping[str, Mapping[str, str]] | None = None, ) -> str: """Create a Job from the template's CronJob and return its name: `name`, else a new one. - `deadline` replaces the `activeDeadlineSeconds` of the template, and `annotations` go on - the Job. + `deadline` replaces the `activeDeadlineSeconds` of the template, `annotations` go on + the Job, and `resources` replaces the named request and limit values of its container. A caller that records the Job before it creates it chooses the name with `job_name`. A caller that records the digest of the image passes the `cronjob` that it read with `cronjob()`, so the record and the Job come from one read. @@ -118,6 +119,7 @@ def create( labels=labels, deadline=deadline, annotations=annotations, + resources=resources, ) try: self._service.custom_objects_api().create_namespaced_custom_object( diff --git a/src/devops_cli/roadmap/implement_size.py b/src/devops_cli/roadmap/implement_size.py new file mode 100644 index 0000000000..b6f46a3435 --- /dev/null +++ b/src/devops_cli/roadmap/implement_size.py @@ -0,0 +1,91 @@ +"""The size of a runner Job, chosen from its plan (#3193). + +A Job that implements a small item does not need the memory and the CPU of a Job that changes forty +files. The Service counts the files that `tasks.md` of the plan names, and takes the row of +`RUNNER_SIZES` for that count. The CPU of a row is the request, the limit and the worker count of +`pytest-xdist`, which counts the CPUs of the node and not of the pod (#2806). The memory limit is +not in the table: it is the setting `roadmap.implement.max_memory_limit`, so one limit protects the +node for every row. + +The admission policy `roadmap-service-jobs` admits the rows of this table and no other size +(`k8s/devops/roadmap-service/admissionpolicy.yaml`). A gate check holds the two equal. A person who +changes a row changes the policy in the same pull request. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Final + +# The Job variable that bounds the workers of the test runner to the CPU limit of the pod. +WORKERS_VARIABLE: Final[str] = "PYTEST_XDIST_AUTO_NUM_WORKERS" +# A plan of at most this many files takes the small row; a larger plan takes the large row. +SMALL_PLAN_MAX_FILES: Final[int] = 10 + +_GB: Final[int] = 10**9 +# A path in a code span: a name with a `/`, or a file at the root with a suffix that the plans use. +# A command has a space, and a setting or a module has dots and no `/`, so neither matches. +_PATH: Final[re.Pattern[str]] = re.compile( + r"[\w.-]+(?:/[\w.-]+)+|[\w-]+\.(?:md|py|yaml|yml|toml|json|txt|cfg|ini|sh|lock)" +) +_CODE_SPAN: Final[re.Pattern[str]] = re.compile(r"`([^`\n]+)`") + + +@dataclass(frozen=True) +class RunnerSize: + """One row of the table: the CPU (request and limit) and the memory request of a Job, and the + measurement that sets the memory request. The memory request is above `peak_bytes`.""" + + max_files: int | None + cpu: str + memory: str + sample: str + peak_bytes: int + + @property + def env(self) -> dict[str, str]: + """The worker count of the test runner: the CPU limit of the same Job.""" + return {WORKERS_VARIABLE: self.cpu} + + def resources(self, memory_limit: str) -> dict[str, dict[str, str]]: + """The requests and limits that replace those of the template. The CPU request equals the + CPU limit, and the memory limit is `memory_limit`.""" + return { + "requests": {"cpu": self.cpu, "memory": self.memory}, + "limits": {"cpu": self.cpu, "memory": memory_limit}, + } + + +# The peaks are the measured ones of the runner Jobs (#2806): the normal peak of the 10 Jobs that +# did not run out of memory, and the peak that the Job reached before the kernel killed it at its +# 4 Gi cap, which was still growing. A third row needs a third measurement. +RUNNER_SIZES: Final[tuple[RunnerSize, ...]] = ( + RunnerSize( + max_files=SMALL_PLAN_MAX_FILES, + cpu="1", + memory="2Gi", + sample="the 10 runner Jobs of #2806 that did not run out of memory", + peak_bytes=int(1.24 * _GB), + ), + RunnerSize( + max_files=None, + cpu="4", + memory="6Gi", + sample="the runner Job of #2806 that the kernel killed at its 4 Gi cap", + peak_bytes=int(4.13 * _GB), + ), +) + +# The memory limit may not be below the largest request, or the API refuses the Job. +MIN_MEMORY_LIMIT_GI: Final[int] = max(int(row.memory.removesuffix("Gi")) for row in RUNNER_SIZES) + + +def plan_file_count(tasks_md: str) -> int: + """The distinct file paths that the code spans of `tasks_md` name.""" + return len({span for span in _CODE_SPAN.findall(tasks_md) if _PATH.fullmatch(span)}) + + +def runner_size(files: int) -> RunnerSize: + """The row of the table for a plan that names `files` files.""" + return next(row for row in RUNNER_SIZES if row.max_files is None or files <= row.max_files) diff --git a/src/devops_cli/roadmap/implement_submit.py b/src/devops_cli/roadmap/implement_submit.py index bc3ff37b5d..117978ffb4 100644 --- a/src/devops_cli/roadmap/implement_submit.py +++ b/src/devops_cli/roadmap/implement_submit.py @@ -1,8 +1,8 @@ """The Service's submission of the implement Job (#2667). -The Service never runs a step: its image holds no dev tool, and the step needs 2 CPU and an hour. -A round of its `implement` row asks the Kubernetes API for the runner Jobs of the repository, in -three moves. +The Service never runs a step: its image holds no dev tool, and the step needs CPU, memory and an +hour. A round of its `implement` row asks the Kubernetes API for the runner Jobs of the repository, +in three moves. **Report.** An item whose record holds `implement.job` and no `implement.job_state` has a Job that no round reported. When the Job has ended, the round comments the state and the tail of the @@ -26,7 +26,9 @@ **Submit.** Else the round plans the Staged and Planned items that the default filter names and creates one Job for the first of them, from CronJob `devops-cli-runner`, with the item's arguments and a token for the one repository (`service.github_app.token_repository`). The record -of the item then names the Job. +of the item then names the Job. The Job has the CPU and the memory request of the row of the size +table that fits the number of files in the tasks of the plan, and the memory limit of the setting +`roadmap.implement.max_memory_limit` (`implement_size.py`, #3193). **Clear.** After the report, the round clears the stop of each item that the Service set Blocked when a person asked for a retry, when the stop is `job` and a continuation is left (#3721), or when @@ -93,7 +95,9 @@ plan_implement, ) from devops_cli.roadmap.implement_deadline import manage_deadlines -from devops_cli.roadmap.planned import read_planned_changes +from devops_cli.roadmap.implement_size import RunnerSize, plan_file_count, runner_size +from devops_cli.roadmap.plan_read import tasks_at +from devops_cli.roadmap.planned import PlannedChanges, read_planned_changes from devops_cli.roadmap.stage import StageFailure from devops_cli.roadmap.status_sync import StatusFacts, derive_status, sync_statuses from devops_cli.roadmap.stop_clear import clear_stops @@ -282,8 +286,22 @@ def _report_ended( return tuple(reported) +def _size_of(source: Path | str, planned: PlannedChanges, target: ImplementTarget) -> RunnerSize: + """The row of the size table for the plan of `target`. The plan is on the default branch for a + Planned item and on the branch of the item for a Staged one. Raises `GitOperationError` when + git cannot read it.""" + rev = f"origin/{planned.default if target.planned else target.branch}" + tasks = tasks_at(Path(source), rev, target.item.number, operation=GIT_OPERATION) + return runner_size(plan_file_count(tasks)) + + def _create( - store: RoadmapStore, jobs: ClusterJobs, repo: str, target: ImplementTarget, label: str + store: RoadmapStore, + jobs: ClusterJobs, + repo: str, + target: ImplementTarget, + label: str, + size: RunnerSize, ) -> str | None: """Claim the item and record the Job on it, then create the Job. The record comes first: a record that fails after the create would leave a Job that no item names, and a Job that dies @@ -292,6 +310,7 @@ def _create( not exist, which the next round reports as gone and stops the item for. The name of the Job, or None, with nothing written, when an agent or a person claimed the item since the plan.""" number = target.item.number + settings = load_settings().roadmap.implement name = job_name(template=RUNNER_TEMPLATE) cronjob = jobs.cronjob(RUNNER_TEMPLATE) marks = { @@ -305,11 +324,12 @@ def _create( jobs.create( ["roadmap", "implement", "--repo", repo, "--item", str(number), "--confirm"], template=RUNNER_TEMPLATE, - env={setting_variables()[CONST_GITHUB_APP_TOKEN_REPOSITORY_SETTING]: repo}, + env={setting_variables()[CONST_GITHUB_APP_TOKEN_REPOSITORY_SETTING]: repo, **size.env}, + resources=size.resources(settings.max_memory_limit), labels={CONST_ROADMAP_IMPLEMENT_JOB_LABEL: label}, name=name, cronjob=cronjob, - deadline=load_settings().roadmap.implement.deadline_extension_seconds, + deadline=settings.deadline_extension_seconds, annotations={ CONST_ROADMAP_IMPLEMENT_ANNOTATION_PROGRESS_AT: str( int(datetime.now(UTC).timestamp()) @@ -367,7 +387,8 @@ def run_implement_round( reported=reported, waiting=True, status_failed=failed, cleared=stops.cleared ) number = plan.selected[0].item.number - created = _create(store, api, repo, plan.selected[0], label) + size = _size_of(source, planned, plan.selected[0]) + created = _create(store, api, repo, plan.selected[0], label, size) failed = (*stops.failed, *sync_statuses(store, repo=repo, planned=planned).failed) return SubmitResult( reported=reported, diff --git a/src/devops_cli/roadmap/plan_read.py b/src/devops_cli/roadmap/plan_read.py index 5982ed7494..53f2ce22c7 100644 --- a/src/devops_cli/roadmap/plan_read.py +++ b/src/devops_cli/roadmap/plan_read.py @@ -546,6 +546,17 @@ def merged_recorded_tests(source: Path, rev: str, issue: int, *, operation: str) return recorded_tests(weakened_checks(text)) +def tasks_at(source: Path, rev: str, issue: int, *, operation: str) -> str: + """The text of `tasks.md` of the active change of `issue` at commit `rev`. A commit with no + active change of `issue`, such as one that holds the change archived, gives an empty text.""" + files = tree_files(source, rev, operation=operation) + root, _ = change_root(files, issue) + path = f"{root}/{_TASKS}" + if root is None or path not in files: + return "" + return files_at(source, rev, [path], operation=operation)[path] + + def specs_at( source: Path, rev: str, *, operation: str, files: Sequence[str] | None = None ) -> tuple[frozenset[str], dict[str, tuple[str, ...]]]: diff --git a/tests/gate/k8s_checks/job_admission_policy.py b/tests/gate/k8s_checks/job_admission_policy.py index b8a8412996..1689a5a371 100644 --- a/tests/gate/k8s_checks/job_admission_policy.py +++ b/tests/gate/k8s_checks/job_admission_policy.py @@ -12,6 +12,7 @@ from devops_cli.config.constants import CONST_ROADMAP_IMPLEMENT_DEADLINE_CAP_SECONDS from devops_cli.k8s.cluster_job import RUNNER_TEMPLATE, build_job +from devops_cli.roadmap.implement_size import RUNNER_SIZES, WORKERS_VARIABLE, RunnerSize from tests.gate.k8s_render import applied_documents from tests.support.paths import REPO_ROOT @@ -72,22 +73,30 @@ def _refusals(job: dict[str, Any], user: str | None = None) -> list[str]: return [rule["message"] for rule in spec["validations"] if not _holds(rule["expression"], data)] -@functools.cache -def _template_job() -> dict[str, Any]: +def _job_of_size(size: RunnerSize | None, memory_limit: str = "8Gi") -> dict[str, Any]: + """The Job the Service makes for a row of the size table, or the Job of the bare template.""" cronjob = _object("CronJob", "devops-cli-runner") return build_job( cronjob, ["roadmap", "implement", "--repo", "example/project", "--item", "7", "--confirm"], "devops-cli-runner-20261030-120000-ab12", template=RUNNER_TEMPLATE, - env=SERVICE_ENV, + env={**SERVICE_ENV, **(size.env if size else {})}, labels=SERVICE_LABELS, + resources=size.resources(memory_limit) if size else None, ) -def _changed(mutate: Mutation) -> dict[str, Any]: +@functools.cache +def _template_job() -> dict[str, Any]: + """The Job of the Service for the small row.""" + return _job_of_size(RUNNER_SIZES[0]) + + +def _changed(*mutations: Mutation) -> dict[str, Any]: job = copy.deepcopy(_template_job()) - mutate(job) + for mutate in mutations: + mutate(job) return job @@ -131,6 +140,46 @@ def _drop_pod_labels(job: dict[str, Any]) -> None: del job["spec"]["template"]["metadata"]["labels"] +def _set_resources( + *, cpu: str | None = None, memory: str | None = None, limit: str | None = None +) -> Mutation: + """Replace the CPU of the request and the limit, the memory request or the memory limit.""" + + def mutate(job: dict[str, Any]) -> None: + resources = _container(job)["resources"] + if cpu is not None: + resources["requests"]["cpu"] = cpu + resources["limits"]["cpu"] = cpu + if memory is not None: + resources["requests"]["memory"] = memory + if limit is not None: + resources["limits"]["memory"] = limit + + return mutate + + +def _set_workers(value: str) -> Mutation: + def mutate(job: dict[str, Any]) -> None: + for entry in _container(job)["env"]: + if entry["name"] == WORKERS_VARIABLE: + entry["value"] = value + + return mutate + + +def _drop_workers(job: dict[str, Any]) -> None: + container = _container(job) + container["env"] = [e for e in container["env"] if e["name"] != WORKERS_VARIABLE] + + +def _drop_memory_limit(job: dict[str, Any]) -> None: + del _container(job)["resources"]["limits"]["memory"] + + +def _drop_resources(job: dict[str, Any]) -> None: + del _container(job)["resources"] + + def _set_container(**fields: object) -> Mutation: return lambda job: _container(job).update(fields) @@ -217,6 +266,14 @@ def check_the_job_from_the_runner_template_passes_in_every_image_form() -> None: pytest.param(_set_spec(backoffLimit=1), "backoffLimit", id="retry"), pytest.param(_drop_spec_field("backoffLimit"), "backoffLimit", id="retry-not-set"), pytest.param(_drop_spec_field("activeDeadlineSeconds"), "deadline", id="no-deadline"), + pytest.param(_set_resources(cpu="3"), "size table", id="cpu-off-the-table"), + pytest.param(_set_resources(memory="7Gi"), "size table", id="memory-off-the-table"), + pytest.param(_set_resources(memory="6Gi"), "size table", id="large-memory-small-cpu"), + pytest.param(_set_resources(cpu="4"), "size table", id="large-cpu-small-memory"), + pytest.param(_set_workers("2"), "size table", id="workers-differ-from-cpu"), + pytest.param(_drop_workers, "size table", id="no-worker-count"), + pytest.param(_drop_memory_limit, "size table", id="no-memory-limit"), + pytest.param(_drop_resources, "size table", id="no-resources"), ], ) def check_a_job_that_breaks_one_rule_is_refused_by_that_rule(mutate: Mutation, rule: str) -> None: @@ -226,6 +283,34 @@ def check_a_job_that_breaks_one_rule_is_refused_by_that_rule(mutate: Mutation, r assert rule in refused[0] +def check_the_job_of_every_row_of_the_size_table_passes_also_with_a_raised_memory_limit() -> None: + jobs = [_job_of_size(row, limit) for row in RUNNER_SIZES for limit in ("8Gi", "12Gi")] + + assert [_refusals(job) for job in jobs] == [[]] * len(jobs) + + +def check_the_policy_admits_exactly_the_cpu_and_memory_pairs_of_the_size_table() -> None: + """Each pair from a grid that holds the rows and the values near them: only the table passes.""" + cpus = sorted({row.cpu for row in RUNNER_SIZES} | {"0.5", "2", "3", "5", "8"}) + memories = sorted({row.memory for row in RUNNER_SIZES} | {"1Gi", "4Gi", "5Gi", "7Gi", "8Gi"}) + + admitted = { + (cpu, memory) + for cpu in cpus + for memory in memories + if not _refusals(_changed(_set_resources(cpu=cpu, memory=memory), _set_workers(cpu))) + } + + assert admitted == {(row.cpu, row.memory) for row in RUNNER_SIZES} + + +def check_a_job_with_the_size_of_the_template_is_refused() -> None: + refused = _refusals(_job_of_size(None)) + + assert len(refused) == 1 + assert "size table" in refused[0] + + def check_a_job_that_names_the_default_values_passes() -> None: explicit = _changed(_set_spec(completions=1, parallelism=1, manualSelector=False)) diff --git a/tests/k8s/test_k8s_cluster_job_api.py b/tests/k8s/test_k8s_cluster_job_api.py index 229f303b9b..c6e8dd8fe4 100644 --- a/tests/k8s/test_k8s_cluster_job_api.py +++ b/tests/k8s/test_k8s_cluster_job_api.py @@ -284,6 +284,44 @@ def test_a_job_is_created_with_the_deadline_and_the_annotations_given(kube: Fake ) == (3600, {"roadmap.devops-cli/progress-at": "1700000000"}) +def test_a_job_is_created_with_the_resources_given_and_keeps_the_other_values_of_the_template( + kube: FakeCluster, +) -> None: + ClusterJobs().create( + ["roadmap"], + template=RUNNER_TEMPLATE, + resources={ + "requests": {"cpu": "1", "memory": "2Gi"}, + "limits": {"cpu": "1", "memory": "12Gi"}, + }, + env={"PYTEST_XDIST_AUTO_NUM_WORKERS": "1"}, + ) + + (job,) = kube.custom_objects.objects[JOBS] + (container,) = job["spec"]["template"]["spec"]["containers"] + env = {entry["name"]: entry["value"] for entry in container["env"]} + assert (container["resources"], env["PYTEST_XDIST_AUTO_NUM_WORKERS"]) == ( + { + "requests": {"cpu": "1", "memory": "2Gi", "ephemeral-storage": "2Gi"}, + "limits": {"cpu": "1", "memory": "12Gi", "ephemeral-storage": "6Gi"}, + }, + "1", + ) + + +def test_a_job_keeps_the_resources_of_the_template_when_the_caller_gives_none( + kube: FakeCluster, +) -> None: + ClusterJobs().create(["roadmap"], template=RUNNER_TEMPLATE) + + (job,) = kube.custom_objects.objects[JOBS] + (container,) = job["spec"]["template"]["spec"]["containers"] + assert container["resources"] == { + "requests": {"cpu": "2", "memory": "4Gi", "ephemeral-storage": "2Gi"}, + "limits": {"cpu": "2", "memory": "8Gi", "ephemeral-storage": "6Gi"}, + } + + def test_a_job_keeps_the_deadline_of_the_template_when_the_caller_gives_none( kube: FakeCluster, ) -> None: diff --git a/tests/roadmap/test_roadmap_implement_size.py b/tests/roadmap/test_roadmap_implement_size.py new file mode 100644 index 0000000000..c2f105f918 --- /dev/null +++ b/tests/roadmap/test_roadmap_implement_size.py @@ -0,0 +1,140 @@ +"""The size of a runner Job follows the plan (#3193): the table of sizes, the count of the files +of a plan, the worker count that equals the CPU limit, and the setting of the memory limit.""" + +from __future__ import annotations + +from collections.abc import Callable +from pathlib import Path + +import pytest + +from devops_cli.config import settings +from devops_cli.exceptions import ConfigurationError +from devops_cli.roadmap.implement_size import ( + RUNNER_SIZES, + SMALL_PLAN_MAX_FILES, + WORKERS_VARIABLE, + plan_file_count, + runner_size, +) + +VARIABLE = "DEVOPS_CLI_ROADMAP_IMPLEMENT_MAX_MEMORY_LIMIT" +GIB = 1024**3 + + +def _gibibytes(quantity: str) -> int: + assert quantity.endswith("Gi") + return int(quantity.removesuffix("Gi")) * GIB + + +def _tasks(*paths: str) -> str: + """A `tasks.md` that names each path in a task of its own.""" + lines = ["# Tasks", "", "## 1. The work", "", "Kind: behavior", ""] + lines += [f"- [ ] 1.{number} Change `{path}`" for number, path in enumerate(paths, start=1)] + return "\n".join(lines) + "\n" + + +def test_a_plan_with_few_files_gets_a_smaller_request_than_a_plan_with_many() -> None: + few = runner_size(plan_file_count(_tasks(*(f"src/a{n}.py" for n in range(3))))) + many = runner_size(plan_file_count(_tasks(*(f"src/a{n}.py" for n in range(12))))) + + assert (few.cpu, few.memory, many.cpu, many.memory) == ("1", "2Gi", "4", "6Gi") + + +@pytest.mark.parametrize( + ("files", "row"), + [(0, 0), (1, 0), (SMALL_PLAN_MAX_FILES, 0), (SMALL_PLAN_MAX_FILES + 1, 1), (60, 1)], +) +def test_the_small_row_holds_up_to_ten_files_and_the_large_row_the_rest( + files: int, row: int +) -> None: + assert (SMALL_PLAN_MAX_FILES, runner_size(files)) == (10, RUNNER_SIZES[row]) + + +def test_a_file_is_counted_once_and_a_command_or_a_setting_is_no_file() -> None: + tasks = ( + "# Tasks\n\n## 1. The work\n\n" + "- [ ] 1.1 Change `src/devops_cli/a.py` and `tests/test_a.py`\n" + " - Verification: `uv run devops ci test tests/test_a.py`\n" + "- [ ] 1.2 Change `src/devops_cli/a.py` again, set `roadmap.implement.max_memory_limit`, " + "read `PYTEST_XDIST_AUTO_NUM_WORKERS` and `devops_cli.roadmap.implement_size`\n" + "- [ ] 1.3 Document it in `k8s/README.md` and `CONTEXT.md`\n" + ) + + assert plan_file_count(tasks) == 4 + + +def test_a_plan_that_names_no_file_has_zero_files() -> None: + assert plan_file_count("# Tasks\n") == 0 + + +def test_the_worker_count_of_each_row_is_its_cpu_limit() -> None: + for row in RUNNER_SIZES: + resources = row.resources("8Gi") + assert ( + row.env, + resources["requests"]["cpu"], + resources["limits"]["cpu"], + ) == ({WORKERS_VARIABLE: row.cpu}, row.cpu, row.cpu) + + +def test_the_memory_limit_is_the_argument_and_the_request_is_the_row() -> None: + resources = RUNNER_SIZES[0].resources("12Gi") + + assert resources == { + "requests": {"cpu": "1", "memory": "2Gi"}, + "limits": {"cpu": "1", "memory": "12Gi"}, + } + + +def test_each_row_cites_its_measured_sample_and_its_request_is_above_the_peak() -> None: + for row in RUNNER_SIZES: + assert (bool(row.sample), row.peak_bytes < _gibibytes(row.memory)) == (True, True) + + +def test_the_table_has_more_cpu_and_memory_in_each_row_than_in_the_one_before() -> None: + cpus = [int(row.cpu) for row in RUNNER_SIZES] + memory = [_gibibytes(row.memory) for row in RUNNER_SIZES] + + assert (cpus, memory) == (sorted(set(cpus)), sorted(set(memory))) + + +@pytest.fixture +def clean_setting(config: Callable[..., Path], monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv(VARIABLE, raising=False) + config() + + +def _limit() -> str: + settings.reset_settings_cache() + return settings.load_settings().roadmap.implement.max_memory_limit + + +@pytest.mark.usefixtures("clean_setting") +def test_the_memory_limit_is_8gi_when_the_setting_is_not_set() -> None: + assert _limit() == "8Gi" + + +@pytest.mark.usefixtures("clean_setting") +def test_a_variable_raises_the_memory_limit(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv(VARIABLE, "12Gi") + + assert _limit() == "12Gi" + + +@pytest.mark.usefixtures("clean_setting") +def test_the_largest_request_is_a_valid_limit(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv(VARIABLE, RUNNER_SIZES[-1].memory) + + assert _limit() == RUNNER_SIZES[-1].memory + + +@pytest.mark.usefixtures("clean_setting") +@pytest.mark.parametrize("value", ["5Gi", "8G", "8192Mi", "8", "0Gi", "08Gi", "8.5Gi", "eight"]) +def test_a_limit_below_the_largest_request_or_in_another_form_is_refused( + value: str, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv(VARIABLE, value) + + with pytest.raises(ConfigurationError, match="max_memory_limit"): + _limit() diff --git a/tests/roadmap/test_roadmap_implement_submit.py b/tests/roadmap/test_roadmap_implement_submit.py index f6e0983486..dc0882093a 100644 --- a/tests/roadmap/test_roadmap_implement_submit.py +++ b/tests/roadmap/test_roadmap_implement_submit.py @@ -10,7 +10,9 @@ import copy import logging +from collections.abc import Callable from datetime import timedelta +from pathlib import Path from typing import Any import pytest @@ -33,6 +35,7 @@ from tests.support.paths import REPO_ROOT from tests.support.roadmap_implement import ( PULL, + TASKS, merge_plan, push_staged_branch, route_pull_status, @@ -201,6 +204,99 @@ def test_a_round_creates_one_job_for_a_planned_item_whose_branch_is_gone( assert _record(store, number)["implement.job"] == job["metadata"]["name"] +def _plan_of(pages: int) -> str: + """The `tasks.md` of the tests, with `pages` more new files in the changes of group 1. It names + 3 files without a page and 3 + `pages` with them.""" + extra = "".join(f", `docs/page{n}.md` (new)" for n in range(1, pages + 1)) + return TASKS.replace("`tests/test_shout.py` (new).", f"`tests/test_shout.py` (new){extra}.", 1) + + +def _sized(job: dict[str, Any]) -> tuple[Any, ...]: + """The CPU request, the CPU limit, the worker count, the memory request and the memory limit + of the Job's container.""" + (container,) = job["spec"]["template"]["spec"]["containers"] + env = {entry["name"]: entry.get("value") for entry in container["env"]} + resources = container["resources"] + return ( + resources["requests"]["cpu"], + resources["limits"]["cpu"], + env["PYTEST_XDIST_AUTO_NUM_WORKERS"], + resources["requests"]["memory"], + resources["limits"]["memory"], + ) + + +@pytest.mark.usefixtures("no_continuation") +def test_a_plan_with_few_files_gets_a_smaller_job_than_a_plan_with_many( + store: InMemoryRoadmapStore, stage_repo: StageRepo, api: GitHubApiFake, kube: FakeCluster +) -> None: + push_staged_branch(stage_repo, tasks=_plan_of(0)) + seed_staged(store) + _round(store, stage_repo) + _end(kube, "Complete") + push_staged_branch(stage_repo, tasks=_plan_of(9), number=2) + seed_staged(store, pull=SECOND_PULL) + + _round(store, stage_repo) + + small, large = (_sized(job) for job in _jobs(kube)) + assert (small, large) == ( + ("1", "1", "1", "2Gi", "8Gi"), + ("4", "4", "4", "6Gi", "8Gi"), + ) + + +def test_a_planned_item_is_sized_from_the_plan_on_the_default_branch( + store: InMemoryRoadmapStore, stage_repo: StageRepo, api: GitHubApiFake, kube: FakeCluster +) -> None: + number = seed_staged(store) + merge_plan(stage_repo, number, tasks=_plan_of(8)) + + _round(store, stage_repo) + + (job,) = _jobs(kube) + assert _sized(job) == ("4", "4", "4", "6Gi", "8Gi") + + +def test_the_job_keeps_the_storage_and_the_other_values_of_the_template( + store: InMemoryRoadmapStore, + staged_repo: StageRepo, + api: GitHubApiFake, + kube: FakeCluster, + template: dict[str, Any], +) -> None: + seed_staged(store) + + _round(store, staged_repo) + + (job,) = _jobs(kube) + (container,) = job["spec"]["template"]["spec"]["containers"] + (kept,) = template["spec"]["jobTemplate"]["spec"]["template"]["spec"]["containers"] + assert ( + container["resources"]["requests"]["ephemeral-storage"], + container["resources"]["limits"]["ephemeral-storage"], + ) == ( + kept["resources"]["requests"]["ephemeral-storage"], + kept["resources"]["limits"]["ephemeral-storage"], + ) + + +def test_the_setting_raises_the_memory_limit_of_the_job( + store: InMemoryRoadmapStore, + staged_repo: StageRepo, + api: GitHubApiFake, + kube: FakeCluster, + config: Callable[..., Path], +) -> None: + config(roadmap={"implement": {"max_memory_limit": "12Gi"}}) + seed_staged(store) + + _round(store, staged_repo) + + (job,) = _jobs(kube) + assert _sized(job)[4] == "12Gi" + + def test_no_second_job_is_created_while_the_first_runs_also_for_another_staged_item( store: InMemoryRoadmapStore, staged_repo: StageRepo, api: GitHubApiFake, kube: FakeCluster ) -> None: diff --git a/tests/security/test_config_declarations.py b/tests/security/test_config_declarations.py index 23a1e20aa5..70afd5e09c 100644 --- a/tests/security/test_config_declarations.py +++ b/tests/security/test_config_declarations.py @@ -163,6 +163,7 @@ "DEVOPS_CLI_ROADMAP_IMPLEMENT_DEADLINE_STALL_SECONDS", # #3063 "DEVOPS_CLI_ROADMAP_IMPLEMENT_DEADLINE_EXTENSION_SECONDS", # #3063 "DEVOPS_CLI_ROADMAP_IMPLEMENT_DEADLINE_CEILING_SECONDS", # #3063 + "DEVOPS_CLI_ROADMAP_IMPLEMENT_MAX_MEMORY_LIMIT", # #3193 "DEVOPS_CLI_ROADMAP_STAGE_FILTER", # #2659 "DEVOPS_CLI_ROADMAP_STAGE_LIMIT", # #2659 "DEVOPS_CLI_ROADMAP_STAGE_TOOLSET", # #3238 From 078c6efc2bf2b78f4e1293025f7207f6ff189098 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 6 Nov 2026 20:43:50 +0000 Subject: [PATCH 2/2] docs(openspec): archive 3193-size-the-runner-job-resources --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/roadmap-implement-job/spec.md | 0 .../specs/roadmap-implement-runner/spec.md | 0 .../tasks.md | 0 openspec/specs/roadmap-implement-job/spec.md | 53 +++++++++++++++++-- .../specs/roadmap-implement-runner/spec.md | 19 +++++++ 8 files changed, 69 insertions(+), 3 deletions(-) rename openspec/changes/{3193-size-the-runner-job-resources => archive/2026-11-06-3193-size-the-runner-job-resources}/.openspec.yaml (100%) rename openspec/changes/{3193-size-the-runner-job-resources => archive/2026-11-06-3193-size-the-runner-job-resources}/design.md (100%) rename openspec/changes/{3193-size-the-runner-job-resources => archive/2026-11-06-3193-size-the-runner-job-resources}/proposal.md (100%) rename openspec/changes/{3193-size-the-runner-job-resources => archive/2026-11-06-3193-size-the-runner-job-resources}/specs/roadmap-implement-job/spec.md (100%) rename openspec/changes/{3193-size-the-runner-job-resources => archive/2026-11-06-3193-size-the-runner-job-resources}/specs/roadmap-implement-runner/spec.md (100%) rename openspec/changes/{3193-size-the-runner-job-resources => archive/2026-11-06-3193-size-the-runner-job-resources}/tasks.md (100%) diff --git a/openspec/changes/3193-size-the-runner-job-resources/.openspec.yaml b/openspec/changes/archive/2026-11-06-3193-size-the-runner-job-resources/.openspec.yaml similarity index 100% rename from openspec/changes/3193-size-the-runner-job-resources/.openspec.yaml rename to openspec/changes/archive/2026-11-06-3193-size-the-runner-job-resources/.openspec.yaml diff --git a/openspec/changes/3193-size-the-runner-job-resources/design.md b/openspec/changes/archive/2026-11-06-3193-size-the-runner-job-resources/design.md similarity index 100% rename from openspec/changes/3193-size-the-runner-job-resources/design.md rename to openspec/changes/archive/2026-11-06-3193-size-the-runner-job-resources/design.md diff --git a/openspec/changes/3193-size-the-runner-job-resources/proposal.md b/openspec/changes/archive/2026-11-06-3193-size-the-runner-job-resources/proposal.md similarity index 100% rename from openspec/changes/3193-size-the-runner-job-resources/proposal.md rename to openspec/changes/archive/2026-11-06-3193-size-the-runner-job-resources/proposal.md diff --git a/openspec/changes/3193-size-the-runner-job-resources/specs/roadmap-implement-job/spec.md b/openspec/changes/archive/2026-11-06-3193-size-the-runner-job-resources/specs/roadmap-implement-job/spec.md similarity index 100% rename from openspec/changes/3193-size-the-runner-job-resources/specs/roadmap-implement-job/spec.md rename to openspec/changes/archive/2026-11-06-3193-size-the-runner-job-resources/specs/roadmap-implement-job/spec.md diff --git a/openspec/changes/3193-size-the-runner-job-resources/specs/roadmap-implement-runner/spec.md b/openspec/changes/archive/2026-11-06-3193-size-the-runner-job-resources/specs/roadmap-implement-runner/spec.md similarity index 100% rename from openspec/changes/3193-size-the-runner-job-resources/specs/roadmap-implement-runner/spec.md rename to openspec/changes/archive/2026-11-06-3193-size-the-runner-job-resources/specs/roadmap-implement-runner/spec.md diff --git a/openspec/changes/3193-size-the-runner-job-resources/tasks.md b/openspec/changes/archive/2026-11-06-3193-size-the-runner-job-resources/tasks.md similarity index 100% rename from openspec/changes/3193-size-the-runner-job-resources/tasks.md rename to openspec/changes/archive/2026-11-06-3193-size-the-runner-job-resources/tasks.md diff --git a/openspec/specs/roadmap-implement-job/spec.md b/openspec/specs/roadmap-implement-job/spec.md index 8cd2c51ab6..903f8adc72 100644 --- a/openspec/specs/roadmap-implement-job/spec.md +++ b/openspec/specs/roadmap-implement-job/spec.md @@ -761,11 +761,15 @@ The default stall SHALL be at least 600 seconds above the longest wait in which - **THEN** the default stall is at least the longest of the command timeout, the model call timeout and the monitor timeout plus 600 seconds, and the default extension is at least the stall plus the interval of the row and the tick of the Service ### Requirement: The memory limit of a runner Job stays 8 Gi -The runner Job SHALL have the memory limit of the CronJob template, 8 Gi, whatever the deadline settings are. +The runner Job that the Service creates SHALL have the memory limit of the setting `roadmap.implement.max_memory_limit`, whose default is 8Gi, whatever the deadline settings and the size of the plan are. #### Scenario: The memory limit -- **WHEN** a round creates a Job -- **THEN** the memory limit of its container is 8 Gi +- **WHEN** a round creates a Job and the setting is not set +- **THEN** the memory limit of its container is 8Gi + +#### Scenario: A raised limit +- **WHEN** the setting is 12Gi and a round creates a Job +- **THEN** the memory limit of its container is 12Gi ### Requirement: The stop comment names the failure class The stop comment of the job SHALL name the failure class, the action taken and the action left, before the reason. The job SHALL record the class in `implement.failure` with `implement.stopped`, and SHALL write one line with the class and the action left to its log. A retry of a person and a clear rule of the Service SHALL remove `implement.failure` with `implement.stopped`. @@ -1420,3 +1424,46 @@ The stage job and the implement job SHALL use the definition lookup of `src/devo #### Scenario: The check writes nothing - **WHEN** The implement job checks the tasks of a behavior group at the branch tip - **THEN** The check runs only read-only git commands and the worktree holds no change. + +### Requirement: The Service sizes the runner Job from the plan +The Service SHALL choose the CPU request, the CPU limit and the memory request of a runner Job from the table `RUNNER_SIZES` by the number of files that the plan names: the small row (CPU 1, memory 2Gi) for at most 10 files, and the large row (CPU 4, memory 6Gi) for more. The other values of the template SHALL stay. + +#### Scenario: A plan with few files and a plan with many +- **WHEN** a round creates a Job for a plan whose tasks name 3 files, and another round creates a Job for a plan whose tasks name 12 files +- **THEN** the first Job requests 1 CPU and 2Gi, the second requests 4 CPU and 6Gi, and each keeps the `ephemeral-storage` of the template + +### Requirement: The files of a plan are the paths in its tasks +The Service SHALL count the distinct file paths in the code spans of `tasks.md`, read at the revision that holds the plan: `origin/` for a Planned item and `origin/` for a Staged item. A change that is archived at that revision SHALL count zero files. + +#### Scenario: Paths are counted once +- **WHEN** the tasks name the same file in several tasks, and name commands and settings in code spans +- **THEN** the count holds each file path once and holds no command and no setting + +#### Scenario: A Planned item +- **WHEN** the plan of a Planned item is on the default branch and names 11 files +- **THEN** the Job of the item has the large row + +### Requirement: The worker count of a runner Job equals its CPU limit +The Service SHALL set `PYTEST_XDIST_AUTO_NUM_WORKERS` of the Job to the CPU limit of the same Job, and the CPU request SHALL equal the CPU limit. + +#### Scenario: Every row +- **WHEN** a test reads each row of the table and the Job that the Service creates for it +- **THEN** the CPU request, the CPU limit and the value of `PYTEST_XDIST_AUTO_NUM_WORKERS` are equal + +### Requirement: The size table cites its measurements +Each row of `RUNNER_SIZES` SHALL name the measured Job sample and its peak memory, and the memory request of the row SHALL be above that peak. + +#### Scenario: The rows +- **WHEN** a test reads the table +- **THEN** each row has a sample name and a peak, and its memory request is above the peak + +### Requirement: The memory limit is a setting that holds the largest request +The setting `roadmap.implement.max_memory_limit` SHALL have the default 8Gi and the variable `DEVOPS_CLI_ROADMAP_IMPLEMENT_MAX_MEMORY_LIMIT`. It SHALL be a whole number of Gi, and the configuration SHALL refuse a value below the largest memory request of the table. + +#### Scenario: The default +- **WHEN** the configuration is loaded with no value +- **THEN** the setting is 8Gi + +#### Scenario: A value below the largest request or in another form +- **WHEN** the setting is 5Gi, 8G or 8192Mi +- **THEN** the configuration is refused diff --git a/openspec/specs/roadmap-implement-runner/spec.md b/openspec/specs/roadmap-implement-runner/spec.md index 25436980d4..e6ba959205 100644 --- a/openspec/specs/roadmap-implement-runner/spec.md +++ b/openspec/specs/roadmap-implement-runner/spec.md @@ -233,3 +233,22 @@ The runner image SHALL pass the scan of `ci.yml` and `release.yml` (Trivy, `HIGH #### Scenario: The image is scanned - **WHEN** `trivy image --scanners vuln --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1` runs on the built `runner` target - **THEN** it exits 0 + +### Requirement: The policy admits only the sizes in the table +The policy SHALL refuse a Job of the Service unless the CPU request of its container equals the CPU limit, the pair of the CPU and the memory request is a row of `RUNNER_SIZES`, the container has a memory limit, and the value of `PYTEST_XDIST_AUTO_NUM_WORKERS` equals the CPU limit. It SHALL not pin the memory limit. + +#### Scenario: A Job of each row +- **WHEN** a test builds the Job that the Service makes for each row of the table and evaluates the policy for the Service user +- **THEN** the policy admits the Job + +#### Scenario: A size outside the table +- **WHEN** a test tries each pair of CPU and memory request from a grid that holds the rows and values near them +- **THEN** the policy admits exactly the pairs of the table + +#### Scenario: A worker count that differs +- **WHEN** the Job sets `PYTEST_XDIST_AUTO_NUM_WORKERS` to a value other than its CPU limit, or sets a CPU request other than its CPU limit +- **THEN** the policy refuses the Job + +#### Scenario: A raised memory limit +- **WHEN** the Job of a row sets a memory limit of 12Gi +- **THEN** the policy admits the Job