From 042e80e2a16da78782ae35db62cfe6e5b9bb1c49 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 30 Oct 2026 23:01:40 +0000 Subject: [PATCH 1/9] docs(openspec): plan the runner memory limit and the command in the tool log (#2806) --- .../.openspec.yaml | 2 + .../design.md | 22 ++++++ .../proposal.md | 46 +++++++++++++ .../specs/roadmap-implement-runner/spec.md | 23 +++++++ .../specs/roadmap-implement-step/spec.md | 67 +++++++++++++++++++ .../tasks.md | 32 +++++++++ 6 files changed, 192 insertions(+) create mode 100644 openspec/changes/2806-runner-memory-and-command-log/.openspec.yaml create mode 100644 openspec/changes/2806-runner-memory-and-command-log/design.md create mode 100644 openspec/changes/2806-runner-memory-and-command-log/proposal.md create mode 100644 openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-runner/spec.md create mode 100644 openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md create mode 100644 openspec/changes/2806-runner-memory-and-command-log/tasks.md diff --git a/openspec/changes/2806-runner-memory-and-command-log/.openspec.yaml b/openspec/changes/2806-runner-memory-and-command-log/.openspec.yaml new file mode 100644 index 0000000000..4bfa67093b --- /dev/null +++ b/openspec/changes/2806-runner-memory-and-command-log/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-30 diff --git a/openspec/changes/2806-runner-memory-and-command-log/design.md b/openspec/changes/2806-runner-memory-and-command-log/design.md new file mode 100644 index 0000000000..0fddef2af3 --- /dev/null +++ b/openspec/changes/2806-runner-memory-and-command-log/design.md @@ -0,0 +1,22 @@ +# Design + +## Decisions + +- **Raise the limit to 12 Gi and keep the request at 4 Gi.** The owner said to raise or remove the limits where needed. The measured peak of normal Jobs is 1.24 GB at most, so 4 Gi is right for the request: the scheduler needs only that. A limit of 12 Gi lets a step burst. A kill then needs a real runaway, and the node has room (64 GB, 43 percent requested). 12 Gi is below the cost of 48 test workers (about 13 GB, from 280 MB each), so the limit is not the fix of the cause. +- **Bound the test workers with the variable that xdist reads.** The cause is a worker count from the CPUs of the node. `PYTEST_XDIST_AUTO_NUM_WORKERS` is the documented setting of `pytest-xdist` for this, and `-n logical` honors it. Setting it to the CPU limit (2) cost no time in the measured run (23 s with 2 workers, 24 s with 16). The manifest holds the value, and a test checks that it equals the CPU limit, so the two cannot drift. +- **The shell takes the variable from the process, like `UV_PYTHON`.** The shell of a step gets only `PATH`, `HOME` and the locale of the process, plus `shell_environment`. So a variable on the pod does not reach `pytest` unless `shell_environment` passes it. The function passes it only when the process has it, so a developer machine keeps its own count. +- **A separate line before the call, not a change of the line after it.** The line after the call has the outcome, which a killed call never reaches. The new line needs only the command, so it can come first. The line after the call stays as it is, so the count of refused programs and the other readers of the line do not change. +- **The command line shows a bounded form.** The first word must be a known program (the rule of the line after the call). Any other first word shows as `other`, because a first word can be a password or a token that the model read from a file. For a known program the line shows at most `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS` words. The text is read to a fixed length, masked with `mask_secrets`, escaped with `unicode_escape` so that it is one line, and cut to `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS`. The mask runs before the cut, so a cut cannot split a secret. +- **Residual risk, accepted.** The mask finds a secret by its form. A password that the model read from a file and passes as the argument of an allowed program, such as `git commit -m `, has no form and stays in the log. The Job log is the only evidence of what the agent did, and a command with no argument cannot show a cause like `-n 48`. The issue asks for the arguments. The bound on words and characters and the allowlist of programs limit the harm. +- **CPU and storage limits stay.** See Feasibility in the proposal for the numbers. +- **The roadmap-service limits stay.** Its peak is 57 percent of its limit. + +## Rejected alternatives + +- **Raise the limit only.** The evidence shows 48 workers cost about 13 GB. A limit of 12 Gi would still kill the same run, and a limit of 16 Gi would leave a small node with no margin. It fixes the symptom of one run and not the cause. +- **Bound the workers only, keep 4 Gi.** The cause of this kill is not proven, as the log has no command. Another command, such as `mypy --strict` on a large file set, can also pass 4 Gi. The owner asked for a burst class, and the cost is a limit that the node can pay. +- **Remove the memory limit.** A pod with no limit has no cgroup cap, so a runaway command would make the kernel kill other pods on the node. The 12 Gi limit keeps a runaway inside its pod. +- **Detect the cgroup quota in the code and pick the worker count.** It is hand-rolled code for what a variable of the installed tool does. +- **Change `addopts` to `-n 2`.** It slows the full suite on a developer machine and in CI, where the CPUs are real. +- **Write the command in the line after the call.** A killed call never writes it, which is the case the issue is about. +- **Log the whole command.** A command can be long and can hold a secret. The words and characters are bounded. diff --git a/openspec/changes/2806-runner-memory-and-command-log/proposal.md b/openspec/changes/2806-runner-memory-and-command-log/proposal.md new file mode 100644 index 0000000000..b3240cbb4c --- /dev/null +++ b/openspec/changes/2806-runner-memory-and-command-log/proposal.md @@ -0,0 +1,46 @@ +# Proposal + +## Why + +Issue #2806. The implement Job `devops-cli-runner-20261030-202214-d182` for #2656 ended `Failed`. Its pod was `OOMKilled` at the 4 Gi limit, four minutes after it started. The work of the step was lost. The Job log ended after a `write_file` call and did not name the command that used the memory. + +Two faults show here. The pod has a memory limit that a runaway command reaches. And the tool log writes the line of a shell call only after the call ends, with no command in it, so a kill leaves no cause. + +## What Changes + +- Memory limit of the runner container: from 4 Gi to 12 Gi. The request stays at 4 Gi, so the scheduler places the pod as before and the pod can burst. The CPU limit (2) and the storage limits stay as they are. The numbers that justify this are in Feasibility. +- The pod sets `PYTEST_XDIST_AUTO_NUM_WORKERS` to `2`, the CPU limit. The shell of a step takes this variable from the process when it is set, as it takes `UV_PYTHON`. The project runs `pytest -n logical`, and `pytest-xdist` reads the CPU count of the node, not the CPU limit of the pod, so on the node `hog` a test run starts 48 workers in a pod that has 2 CPU. This is the likely cause of the kill. +- The tool log writes one more line for a call that has a `command`, before the call runs: `Tool call: shell, started: `. The command is the program and its first arguments, masked, on one line, and bounded. The line after the call stays. +- A consumer observes the manifest and the Job log, so the change carries a spec delta: it modifies one requirement of `roadmap-implement-runner` and one of `roadmap-implement-step`, and adds one requirement to each. +- This change fits one pull request. + +## Capabilities + +### Modified Capabilities + +- `roadmap-implement-runner`: the memory limit of the template and the worker bound of the test runner. +- `roadmap-implement-step`: the tool log line before a command and the variable that the shell takes. + +## Impact + +- `k8s/devops/cronjob-runner.yaml`, `k8s/README.md`, `docs/ROUTINE_TASKS.md`. +- `src/devops_cli/roadmap/implement_tool_log.py`, `src/devops_cli/roadmap/implement_step.py`, `src/devops_cli/lang/en/messages.py`, `src/devops_cli/config/constants.py`. +- `tests/test_k8s_runner.py`, `tests/test_roadmap_implement_tool_log.py`, `tests/test_roadmap_implement_step.py`. +- The admission policy `roadmap-service-jobs` needs no change (see Feasibility). + +## Feasibility + +- **The kill is real.** `kubectl -n devops get pods` shows pod `devops-cli-runner-20261030-202214-d182-d8rk7` as `OOMKilled` on node `hog`. Prometheus, `max_over_time(container_memory_working_set_bytes{namespace="devops",container="runner"}[30h])`, gives 4,133,457,920 bytes for it, at the 4 Gi limit (4,294,967,296 bytes). The log of that pod ends with eight tool lines, the last one `write_file, ok`. The next call was a shell call, and its line is written only after the call ends, so the command that used the memory is not in the log. The command is therefore not proven. The proposal states the most likely one below. +- **The other Jobs are small.** The 10 other runner pods peaked between 270,610,432 and 1,240,924,160 bytes (6 to 29 percent of 4 Gi). The OOM pod throttled 77 percent of its CPU periods (`container_cpu_cfs_throttled_periods_total` over `container_cpu_cfs_periods_total`). The other pods throttled between 9 and 40 percent. +- **The likely command and its cost, measured.** `pyproject.toml` sets `addopts = "-n logical ..."`. In the xdist source (`xdist/plugin.py`, `pytest_xdist_auto_num_workers`), the worker count is the variable `PYTEST_XDIST_AUTO_NUM_WORKERS` when it is set, else `psutil.cpu_count(logical=True)`. `psutil` reads the CPUs of the node, and a CPU limit of a pod does not change that number. Node `hog` has 48 CPUs (`kubectl describe node hog`). Measured on this host (16 CPUs), the sum of the PSS of the process tree for `pytest tests/test_roadmap_implement_step.py tests/test_k8s.py tests/test_roadmap_implement_tool_log.py` (263 tests): 766 MB with 2 workers in 23 s, 4,488 MB with 16 workers in 24 s. That is about 280 MB for each worker, and the run is not faster. 48 workers cost about 13 GB. So the limit alone does not fix the cause: 12 Gi is below that figure. The worker bound does. +- **The limit.** Hog has 64 GB. It has 43 percent of its memory requested and 24 percent as limits (`kubectl describe node hog`). The Service makes no second Job for a repository while one runs. A limit of 12 Gi with the request of 4 Gi is a burst class: a kill needs a real runaway. If the node comes under pressure, the kubelet evicts the pods that exceed their request first, and a runner is one of them. +- **CPU and storage do not bind.** A CPU limit only slows a process. The 10 completed Jobs ran between 2.5 and 11 minutes against a deadline of 7200 s, so the limit of 2 stays. No `container_fs_usage_bytes` series exists for the runner, there is no eviction event in the namespace, and the 10 other Jobs completed, so the storage limits stay. +- **The roadmap-service pod.** Its peak over 7 days is 611,205,120 bytes, 57 percent of its 1 Gi limit. That is a margin of 43 percent, so its limits stay. +- **The admission policy.** `k8s/devops/roadmap-service/admissionpolicy.yaml` does not pin the resources of a Job (its header says so), and no expression reads `resources`. `tests/test_k8s_job_admission_policy.py` runs every expression against the Job that the template makes, so it covers the new limit. This session cannot run `kubectl create --dry-run=server` as the Service account, so the live admission is reasoned from the CEL text and the test. +- **Not measured.** A Job on #2656 in a pod with the new settings. The cluster is read-only for this session. After the manifest syncs, a person or the next Job confirms the peak in Prometheus. + +## Existing Tool Considered + +`pytest-xdist` already has the setting: the environment variable `PYTEST_XDIST_AUTO_NUM_WORKERS`. The change builds no CPU detection. Kubernetes `resources` gives the limit. `mask_secrets` of `devops_cli.security.sanitizer` masks the command in the log, `shlex` splits it, and `str.encode("unicode_escape")` escapes control characters. The change builds only the choice of what the line shows. Cost, estimated: about 80 lines of code and tests, about 60k tokens of agent work and one hour of elapsed time. The upkeep is small. + +The change deletes no code. diff --git a/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-runner/spec.md b/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-runner/spec.md new file mode 100644 index 0000000000..38d0d196bd --- /dev/null +++ b/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-runner/spec.md @@ -0,0 +1,23 @@ +# Spec Delta + +## MODIFIED Requirements + +### Requirement: A suspended CronJob is the template of the runner Job +CronJob `devops-cli-runner` in namespace `devops` SHALL be suspended and SHALL never run on a schedule. Its Job template SHALL name the image `ghcr.io/dan-petty/devops-cli/runner` with no tag, request and limit 2 CPU, request 4 Gi and limit 12 Gi of memory, request 2 Gi and limit 6 Gi of `ephemeral-storage`, set `activeDeadlineSeconds` to 7200 and `backoffLimit` to 0, and use the `securityContext` of CronJob `devops-cli`. Its pod SHALL use ServiceAccount `devops-cli`, which mounts no token. + +#### Scenario: The manifest is read +- **WHEN** a test reads the rendered `k8s/devops` kustomization +- **THEN** CronJob `devops-cli-runner` holds the values above, its container is named `runner`, its pod mounts no ServiceAccount token, its root filesystem is read-only, and its capabilities drop `ALL` + +#### Scenario: The admission policy +- **WHEN** a test runs the expressions of policy `roadmap-service-jobs` against the Job that the template makes +- **THEN** no expression refuses it + +## ADDED Requirements + +### Requirement: The runner Job bounds the workers of the test runner to its CPU limit +The container of CronJob `devops-cli-runner` SHALL set `PYTEST_XDIST_AUTO_NUM_WORKERS` to the number of its CPU limit. `pytest-xdist` counts the CPUs of the node, not the CPU limit of the pod, so without the variable a test run starts one worker for each CPU of the node. + +#### Scenario: The variable +- **WHEN** a test reads the rendered `k8s/devops` kustomization +- **THEN** the variable of the runner container equals its CPU limit diff --git a/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md b/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md new file mode 100644 index 0000000000..43abacde06 --- /dev/null +++ b/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md @@ -0,0 +1,67 @@ +# Spec Delta + +## MODIFIED Requirements + +### Requirement: Every tool call of a step writes one line to the Job log +The agent of a step SHALL write one line to the standard error stream for each tool call, when the call ends. The line SHALL hold the name of the tool, the program of the `command` argument when the tool has one, and the outcome: `ok`, `refused`, `retry` or `failed`. The program SHALL be the first word of the command when it is a program of the allowlist or a program of `IMPLEMENT_SHELL_REPLACEMENTS`, else the word `other`. Before a call that has a `command` runs, the agent SHALL write the line `Tool call: , started: `. The command SHALL be the first word and the words after it, at most `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS` words, with secrets masked, control characters escaped, and cut to `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS` characters. When the first word is not a known program, the command SHALL be the word `other`. No line SHALL hold a path or a content of a call that has no `command`, or any output. + +#### Scenario: A refused program +- **WHEN** the model calls the shell tool with `pytest tests/test_sample.py`, and then ends its run +- **THEN** the standard error stream holds the lines "Tool call: shell, started: pytest tests/test_sample.py" and "Tool call: shell, program pytest, refused." + +#### Scenario: A program of the allowlist +- **WHEN** the model calls a tool with the command `git status` +- **THEN** the lines hold "started: git status" and "program git" + +#### Scenario: The line comes before the call +- **WHEN** the model calls the shell tool with `uv run pytest -n 48`, and the tool is still running +- **THEN** the standard error stream holds the line "Tool call: shell, started: uv run pytest -n 48" and no line with an outcome + +#### Scenario: A long command +- **WHEN** the command has more words than `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS`, or more characters than `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS` +- **THEN** the line holds the first words, cut, and ends with " ..." + +#### Scenario: A secret in an argument +- **WHEN** the command is `git remote add origin https://user:ghp_@example.com/x.git`, with a GitHub token in place of `` +- **THEN** the line holds no part of the token + +#### Scenario: A control character in an argument +- **WHEN** an argument holds a line break or an escape sequence +- **THEN** the line is one line, and it holds the escaped form of the character + +#### Scenario: A call that returns +- **WHEN** the model calls `write_file` with a path and a content, and then ends its run +- **THEN** the standard error stream holds the line "Tool call: write_file, ok." and holds neither the path nor the content + +#### Scenario: A call that fails validation +- **WHEN** the model calls `read_file` without its `path` argument +- **THEN** the standard error stream holds the line "Tool call: read_file, retry." + +#### Scenario: A first word that is no program +- **WHEN** the first word of a shell command is an assignment such as `API_KEY=hunter2`, a path, a word with a space or a quote, an escape sequence, or the command has an unclosed quote +- **THEN** the lines hold "started: other" and "program other" and hold no part of the command + +#### Scenario: A short bare word that is no known program +- **WHEN** the first word of a shell command is a short bare word such as `hunter2password` that the model read from a file +- **THEN** the lines and the reason of a stopped run hold "other" and not the word + +#### Scenario: A refused path +- **WHEN** the model calls `read_file` with a path outside the root +- **THEN** the standard error stream holds the line "Tool call: read_file, retry." + +#### Scenario: A call that the tool reports as failed +- **WHEN** a tool reports a failed call +- **THEN** the standard error stream holds the line "Tool call: , failed." + +## ADDED Requirements + +### Requirement: The shell of a step takes the worker bound of the process +The shell of a step SHALL get `PYTEST_XDIST_AUTO_NUM_WORKERS` with the value of the process when the process has it, and SHALL not set it otherwise. + +#### Scenario: The process has the variable +- **WHEN** the process sets `PYTEST_XDIST_AUTO_NUM_WORKERS` to `2` +- **THEN** the environment of the shell holds the same value + +#### Scenario: The process has no variable +- **WHEN** the process does not set it +- **THEN** the environment of the shell does not hold it diff --git a/openspec/changes/2806-runner-memory-and-command-log/tasks.md b/openspec/changes/2806-runner-memory-and-command-log/tasks.md new file mode 100644 index 0000000000..b861ecc640 --- /dev/null +++ b/openspec/changes/2806-runner-memory-and-command-log/tasks.md @@ -0,0 +1,32 @@ +# Tasks + +## 1. The memory limit and the worker bound of the runner Job + +- [ ] Write failing tests in `tests/test_k8s_runner.py`: the memory limit of the runner is 12 Gi and its request is 4 Gi; `PYTEST_XDIST_AUTO_NUM_WORKERS` equals the CPU limit; the Job that the template makes passes the admission policy. + - Verification: `uv run devops ci test tests/test_k8s_runner.py tests/test_k8s_job_admission_policy.py` +- [ ] Change `k8s/devops/cronjob-runner.yaml`: memory limit 12 Gi, the worker variable, and the comments. Change `k8s/README.md` and `docs/ROUTINE_TASKS.md` where they state the numbers. + - Verification: `uv run devops ci test tests/test_k8s_runner.py tests/test_k8s_job_admission_policy.py` + +## 2. The shell takes the worker bound + +- [ ] Write the failing tests in `tests/test_roadmap_implement_step.py`: the shell environment holds the variable of the process, and holds none when the process has none. + - Verification: `uv run devops ci test tests/test_roadmap_implement_step.py` +- [ ] Change `shell_environment` in `src/devops_cli/roadmap/implement_step.py`. + - Verification: `uv run devops ci test tests/test_roadmap_implement_step.py` + +## 3. The tool log names the command + +- [ ] Write the failing tests in `tests/test_roadmap_implement_tool_log.py`: the start line comes before the call runs; a long command is cut; a secret is masked; a control character stays on one line; an unknown first word shows as `other`; a call with no command writes no start line. Update the tests that read all lines. + - Verification: `uv run devops ci test tests/test_roadmap_implement_tool_log.py` +- [ ] Change `src/devops_cli/roadmap/implement_tool_log.py`, `src/devops_cli/lang/en/messages.py` and `src/devops_cli/config/constants.py`. + - Verification: `uv run devops ci test tests/test_roadmap_implement_tool_log.py tests/test_roadmap_implement_step.py` + +## 4. The documentation + +- [ ] Regenerate the documentation. + - Verification: `uv run devops docs generate --sync-readme` and `uv run devops docs check` + +## 5. Archive + +- [ ] Archive the change. + - Verification: `uv run devops openspec archive 2806-runner-memory-and-command-log` From f7e98177ad3df7f7575bef4aacc90010eff71355 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 30 Oct 2026 23:02:30 +0000 Subject: [PATCH 2/9] fix(k8s): the runner pod bursts to 12 Gi and bounds its test workers (#2806) --- docs/ROUTINE_TASKS.md | 2 +- k8s/README.md | 2 +- k8s/devops/cronjob-runner.yaml | 13 +++++++++++-- .../2806-runner-memory-and-command-log/tasks.md | 4 ++-- tests/test_k8s_runner.py | 11 ++++++++++- 5 files changed, 25 insertions(+), 7 deletions(-) diff --git a/docs/ROUTINE_TASKS.md b/docs/ROUTINE_TASKS.md index 03caff67d5..446facf2ef 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 10 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 and 7200 s; its pod has no Kubernetes token, and its shell gets none of the variables of the job. The Service's ServiceAccount has a Role that creates and reads 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 with no stop, stops the item (`implement.stopped` is `job`) until a person comments `implement: retry`. 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, 2 CPU, 4 Gi of memory (12 Gi at most) and 7200 s; its pod has no Kubernetes token, and its shell gets none of the variables of the job. The Service's ServiceAccount has a Role that creates and reads 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 with no stop, stops the item (`implement.stopped` is `job`) until a person comments `implement: retry`. 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 f6d9d4861f..295e9136f4 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -597,7 +597,7 @@ kubectl -n devops logs -f job/ The implement job runs tests, `ruff`, `mypy` and OpenSpec, which the Service image does not hold. Its steps run in a runner Job (#2667). `devops k8s run-job --template runner --repo -- roadmap implement --item --confirm` makes one by hand. `--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 and the dev dependencies of `uv.lock`. The release publishes it 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, 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. 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 12 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`. - **Role.** ServiceAccount `roadmap-service` is the account of the Service pod. Role `roadmap-service-jobs` in namespace `devops` allows `create`, `get` and `list` on `jobs`, `get` on CronJob `devops-cli-runner`, `list` on `pods` and `get` on `pods/log`, and nothing else. Kubernetes cannot limit `create` and `list` to a name, so those two cover the namespace. 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 7200 at most. 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. - **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. diff --git a/k8s/devops/cronjob-runner.yaml b/k8s/devops/cronjob-runner.yaml index 178a5bb772..45977c5a30 100644 --- a/k8s/devops/cronjob-runner.yaml +++ b/k8s/devops/cronjob-runner.yaml @@ -65,6 +65,12 @@ spec: # jobs. - name: OTEL_SERVICE_NAME value: devops-cli-job + # `pytest-xdist` starts one worker for each CPU of the node, not of the pod + # (`-n logical`, 280 MB each). On a node with 48 CPUs that is about 13 GB in a pod + # with 2 CPUs (#2806). The value equals the CPU limit; a test checks it. The shell + # of a step takes it from here. + - name: PYTEST_XDIST_AUTO_NUM_WORKERS + value: "2" volumeMounts: - name: tmp mountPath: /tmp @@ -77,14 +83,17 @@ spec: readOnly: true resources: # The storage limit covers both volumes below (4 Gi and 1 Gi) and the log, so a - # step cannot fill the disk of the node. + # step cannot fill the disk of the node. The memory request is the normal peak of + # a Job (1.24 GB at most over 11 Jobs). The memory limit is a burst class (#2806): + # a kill needs a real runaway, and the node has room. The CPU limit only slows a + # step, so it stays. requests: cpu: "2" memory: 4Gi ephemeral-storage: 2Gi limits: cpu: "2" - memory: 4Gi + memory: 12Gi ephemeral-storage: 6Gi volumes: - name: tmp diff --git a/openspec/changes/2806-runner-memory-and-command-log/tasks.md b/openspec/changes/2806-runner-memory-and-command-log/tasks.md index b861ecc640..432c7a230d 100644 --- a/openspec/changes/2806-runner-memory-and-command-log/tasks.md +++ b/openspec/changes/2806-runner-memory-and-command-log/tasks.md @@ -2,9 +2,9 @@ ## 1. The memory limit and the worker bound of the runner Job -- [ ] Write failing tests in `tests/test_k8s_runner.py`: the memory limit of the runner is 12 Gi and its request is 4 Gi; `PYTEST_XDIST_AUTO_NUM_WORKERS` equals the CPU limit; the Job that the template makes passes the admission policy. +- [x] Write failing tests in `tests/test_k8s_runner.py`: the memory limit of the runner is 12 Gi and its request is 4 Gi; `PYTEST_XDIST_AUTO_NUM_WORKERS` equals the CPU limit; the Job that the template makes passes the admission policy. - Verification: `uv run devops ci test tests/test_k8s_runner.py tests/test_k8s_job_admission_policy.py` -- [ ] Change `k8s/devops/cronjob-runner.yaml`: memory limit 12 Gi, the worker variable, and the comments. Change `k8s/README.md` and `docs/ROUTINE_TASKS.md` where they state the numbers. +- [x] Change `k8s/devops/cronjob-runner.yaml`: memory limit 12 Gi, the worker variable, and the comments. Change `k8s/README.md` and `docs/ROUTINE_TASKS.md` where they state the numbers. - Verification: `uv run devops ci test tests/test_k8s_runner.py tests/test_k8s_job_admission_policy.py` ## 2. The shell takes the worker bound diff --git a/tests/test_k8s_runner.py b/tests/test_k8s_runner.py index e7969d06e8..2602950e14 100644 --- a/tests/test_k8s_runner.py +++ b/tests/test_k8s_runner.py @@ -77,11 +77,20 @@ def test_the_runner_cronjob_is_a_suspended_template_that_never_retries() -> None "IfNotPresent", { "requests": {"cpu": "2", "memory": "4Gi", "ephemeral-storage": "2Gi"}, - "limits": {"cpu": "2", "memory": "4Gi", "ephemeral-storage": "6Gi"}, + "limits": {"cpu": "2", "memory": "12Gi", "ephemeral-storage": "6Gi"}, }, ) +def test_the_runner_bounds_the_workers_of_the_test_runner_to_its_cpu_limit() -> None: + """`pytest-xdist` counts the CPUs of the node, not the CPU limit of the pod. On a node with 48 + CPUs a test run started 48 workers of about 280 MB each in a pod with 2 CPUs (#2806).""" + container = _runner_container() + env = {entry["name"]: entry.get("value") for entry in container["env"]} + + assert env["PYTEST_XDIST_AUTO_NUM_WORKERS"] == container["resources"]["limits"]["cpu"] + + def test_the_runner_pod_is_restricted_and_mounts_no_token() -> None: pod = _cronjob_pod("devops-cli-runner") container = _runner_container() From 0aee42d3e818dfd49cf2f4444f956280477060be Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 30 Oct 2026 23:04:23 +0000 Subject: [PATCH 3/9] fix(roadmap): the shell of a step takes the test worker bound of the pod (#2806) --- .../2806-runner-memory-and-command-log/tasks.md | 4 ++-- src/devops_cli/roadmap/implement_step.py | 14 +++++++++----- tests/test_roadmap_implement_step.py | 13 +++++++++++++ 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/openspec/changes/2806-runner-memory-and-command-log/tasks.md b/openspec/changes/2806-runner-memory-and-command-log/tasks.md index 432c7a230d..6d887c110a 100644 --- a/openspec/changes/2806-runner-memory-and-command-log/tasks.md +++ b/openspec/changes/2806-runner-memory-and-command-log/tasks.md @@ -9,9 +9,9 @@ ## 2. The shell takes the worker bound -- [ ] Write the failing tests in `tests/test_roadmap_implement_step.py`: the shell environment holds the variable of the process, and holds none when the process has none. +- [x] Write the failing tests in `tests/test_roadmap_implement_step.py`: the shell environment holds the variable of the process, and holds none when the process has none. - Verification: `uv run devops ci test tests/test_roadmap_implement_step.py` -- [ ] Change `shell_environment` in `src/devops_cli/roadmap/implement_step.py`. +- [x] Change `shell_environment` in `src/devops_cli/roadmap/implement_step.py`. - Verification: `uv run devops ci test tests/test_roadmap_implement_step.py` ## 3. The tool log names the command diff --git a/src/devops_cli/roadmap/implement_step.py b/src/devops_cli/roadmap/implement_step.py index 5cf915a323..6a3a794e3b 100644 --- a/src/devops_cli/roadmap/implement_step.py +++ b/src/devops_cli/roadmap/implement_step.py @@ -475,13 +475,18 @@ class StepOutcome(BaseModel): # ── The agent ───────────────────────────────────────────────────────────────────────────── +_PASSED_VARIABLES = ("UV_PYTHON", "PYTEST_XDIST_AUTO_NUM_WORKERS") + + def shell_environment(home: Path) -> dict[str, str]: """The variables a shell command gets on top of the workspace's own: a scratch `home` in place of the user's, so that no git configuration, credential helper or key of the user reaches the agent, no system git configuration, no prompt for a password, and the cache of `uv` where the - user keeps it, so that `uv run` finds its packages. `UV_PYTHON` goes on when the process has - it: the runner image sets it, as it forbids a Python download and `uv run` finds no - interpreter without it.""" + user keeps it, so that `uv run` finds its packages. The variables in `_PASSED_VARIABLES` go on + when the process has them. `UV_PYTHON`: the runner image sets it, as it forbids a Python + download and `uv run` finds no interpreter without it. `PYTEST_XDIST_AUTO_NUM_WORKERS`: the + pod of the runner sets it to its CPU limit, as `pytest-xdist` counts the CPUs of the node and + a test run started one worker for each of them (#2806).""" env = { "HOME": str(home), "XDG_CONFIG_HOME": str(home / ".config"), @@ -489,8 +494,7 @@ def shell_environment(home: Path) -> dict[str, str]: "GIT_TERMINAL_PROMPT": "0", "UV_CACHE_DIR": os.environ.get("UV_CACHE_DIR") or user_cache_dir("uv"), } - if interpreter := os.environ.get("UV_PYTHON"): - env["UV_PYTHON"] = interpreter + env.update({name: os.environ[name] for name in _PASSED_VARIABLES if os.environ.get(name)}) return env diff --git a/tests/test_roadmap_implement_step.py b/tests/test_roadmap_implement_step.py index 60760d0748..b354247284 100644 --- a/tests/test_roadmap_implement_step.py +++ b/tests/test_roadmap_implement_step.py @@ -527,6 +527,7 @@ def test_the_shell_runs_with_a_scratch_home_and_the_cache_of_uv( """No git configuration, helper or key of the user's home reaches a shell command.""" monkeypatch.setenv("UV_CACHE_DIR", str(tmp_path / "uv-cache")) monkeypatch.delenv("UV_PYTHON", raising=False) + monkeypatch.delenv("PYTEST_XDIST_AUTO_NUM_WORKERS", raising=False) env = shell_environment(tmp_path / "home") @@ -551,6 +552,18 @@ def test_the_shell_gets_the_interpreter_that_uv_is_told_to_use( assert env["UV_PYTHON"] == "/usr/local/bin/python3" +def test_the_shell_gets_the_worker_bound_of_the_process( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """`pytest-xdist` counts the CPUs of the node. The pod of the runner sets the bound, and the + shell of a step gets no other variable of the job, so the bound must be passed on (#2806).""" + monkeypatch.setenv("PYTEST_XDIST_AUTO_NUM_WORKERS", "2") + + env = shell_environment(tmp_path / "home") + + assert env["PYTEST_XDIST_AUTO_NUM_WORKERS"] == "2" + + def test_the_agent_of_a_step_runs_its_shell_in_that_environment( tmp_path: Path, checkout: Path ) -> None: From e77fcc1f95d27db681e1b7dfad4ee6f117bcb367 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 30 Oct 2026 23:06:56 +0000 Subject: [PATCH 4/9] fix(roadmap): the Job log names the command before a shell call runs (#2806) --- .../tasks.md | 4 +- src/devops_cli/config/constants.py | 9 ++ src/devops_cli/lang/en/messages.py | 2 + src/devops_cli/roadmap/implement_tool_log.py | 53 +++++++++- tests/test_roadmap_implement_tool_log.py | 100 ++++++++++++++++-- 5 files changed, 154 insertions(+), 14 deletions(-) diff --git a/openspec/changes/2806-runner-memory-and-command-log/tasks.md b/openspec/changes/2806-runner-memory-and-command-log/tasks.md index 6d887c110a..b0340b5fef 100644 --- a/openspec/changes/2806-runner-memory-and-command-log/tasks.md +++ b/openspec/changes/2806-runner-memory-and-command-log/tasks.md @@ -16,9 +16,9 @@ ## 3. The tool log names the command -- [ ] Write the failing tests in `tests/test_roadmap_implement_tool_log.py`: the start line comes before the call runs; a long command is cut; a secret is masked; a control character stays on one line; an unknown first word shows as `other`; a call with no command writes no start line. Update the tests that read all lines. +- [x] Write the failing tests in `tests/test_roadmap_implement_tool_log.py`: the start line comes before the call runs; a long command is cut; a secret is masked; a control character stays on one line; an unknown first word shows as `other`; a call with no command writes no start line. Update the tests that read all lines. - Verification: `uv run devops ci test tests/test_roadmap_implement_tool_log.py` -- [ ] Change `src/devops_cli/roadmap/implement_tool_log.py`, `src/devops_cli/lang/en/messages.py` and `src/devops_cli/config/constants.py`. +- [x] Change `src/devops_cli/roadmap/implement_tool_log.py`, `src/devops_cli/lang/en/messages.py` and `src/devops_cli/config/constants.py`. - Verification: `uv run devops ci test tests/test_roadmap_implement_tool_log.py tests/test_roadmap_implement_step.py` ## 4. The documentation diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 96f252fbd7..c922a88b7e 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -3014,6 +3014,15 @@ class WebhookExposure(StrEnum): # The most programs that the reason of a stopped run lists in its count of refused commands # (#2773). The programs beyond that join the count of "other". CONST_ROADMAP_IMPLEMENT_REFUSED_PROGRAMS: Final[int] = 4 +# The most words and characters of the command that the Job log shows before a shell call runs +# (#2806). The log holds the program and its first arguments, so that a call the kernel kills +# leaves its cause. The masking reads `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_READ_CHARS` first, so +# that a cut cannot split a secret. +CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS: Final[int] = 6 +CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS: Final[int] = 160 +CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_READ_CHARS: Final[int] = ( + 4 * CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS +) CONST_ROADMAP_IMPLEMENT_MONITOR_TIMEOUT_SECONDS: Final[int] = 1800 # After a push, GitHub can still show the old head of the pull request. The job reads this many # times, `DEFAULT_ROADMAP_IMPLEMENT_POLL_SECONDS` apart, for the pushed commit as the head. diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index 6d431dc69a..f55e07b080 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -2042,6 +2042,8 @@ class RoadmapMessages: ) implement_tool_line: str = "Tool call: {tool}, {outcome}." implement_tool_line_program: str = "Tool call: {tool}, program {program}, {outcome}." + implement_tool_started: str = "Tool call: {tool}, started: {command}" + implement_tool_cut: str = " ..." implement_tick_turn: str = ( "The checks of your group passed, but `{path}` still holds these tasks of your group " "unticked:\n\n{tasks}\n\nChange `- [ ]` to `- [x]` in front of each task whose work is " diff --git a/src/devops_cli/roadmap/implement_tool_log.py b/src/devops_cli/roadmap/implement_tool_log.py index bd96762314..23308c7ecd 100644 --- a/src/devops_cli/roadmap/implement_tool_log.py +++ b/src/devops_cli/roadmap/implement_tool_log.py @@ -2,9 +2,12 @@ A step that stops discards its checkout, so the Job log is the only evidence of what the agent did. `ToolCallLog` is a pydantic-ai `Hooks` capability. It writes one line to the standard error -stream for each tool call: the tool name, the program of a shell command, and the outcome. A line -holds no other argument, no file content, no output and no text of a refusal, as an argument can -hold a path or a secret and the text of one refusal repeats the whole command. The program is the +stream for each tool call: the tool name, the program of a shell command, and the outcome. A call +that has a command writes one more line before it runs, with the program and its first arguments +(#2806), so a call that the kernel kills leaves its cause in the log. `logged_command` masks that +command, bounds it and escapes it to one line. The line after the call holds no argument, no file +content, no output and no text of a refusal, as an argument can hold a path or a secret and the +text of one refusal repeats the whole command. The program is the first word of the command, as the shell reads it, and only when it is a program that the project knows: a program of the allowlist, or a program of the table of replacements (#2773). Any other first word is written as "other", also a short bare word, as the model can read a password or a @@ -41,9 +44,15 @@ from pydantic_ai.tools import ToolDefinition from devops_cli.config.commands import IMPLEMENT_ALLOWED_PROGRAMS, IMPLEMENT_SHELL_REPLACEMENTS -from devops_cli.config.constants import CONST_ROADMAP_IMPLEMENT_REFUSED_PROGRAMS +from devops_cli.config.constants import ( + CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS, + CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_READ_CHARS, + CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS, + CONST_ROADMAP_IMPLEMENT_REFUSED_PROGRAMS, +) from devops_cli.lang import MESSAGES from devops_cli.output import print_muted +from devops_cli.security.sanitizer import mask_secrets # The first words that the log may show. They are fixed in the code, so no text of the model # reaches the log, and the count of the programs in the reason stays small by design. @@ -97,6 +106,34 @@ def logged_program(word: str | None) -> str: return MESSAGES.roadmap.implement_tool_other +def logged_command(args: ValidatedToolArgs) -> str: + """What the log shows of a command before the call runs (#2806): the first word and the words + after it, at most `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS`, with secrets masked, control + characters escaped and the text cut to `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS`. Empty when + the call has no command word. The word "other" when the first word is no known program: it can + be a password or a token, and the words after it mean nothing without it. The mask runs on a + fixed length of text before the cut, so that the cut cannot split a secret.""" + word = command_word(args) + if word is None: + return "" + if word not in _KNOWN_PROGRAMS: + return MESSAGES.roadmap.implement_tool_other + words = shlex.split(str(args["command"])) + shown = mask_secrets( + " ".join(words[:CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS])[ + :CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_READ_CHARS + ] + ) + escaped = shown.encode("unicode_escape").decode("ascii") + cut = ( + len(words) > CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS + or len(escaped) > CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS + ) + return escaped[:CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS] + ( + MESSAGES.roadmap.implement_tool_cut if cut else "" + ) + + @dataclass class ToolCallLog: """The counters of one step, and the hooks that fill them. `refused` counts the refused shell @@ -147,6 +184,14 @@ async def _execute( """Run the call, write its line, and pass on the result or the error. The call that exceeds the limit of retries reaches here as `UnexpectedModelBehavior`.""" program = logged_program(command_word(args)) + if command := logged_command(args): + print_muted( + MESSAGES.roadmap.implement_tool_started.format( + tool=call.tool_name, command=command + ), + to_stderr=True, + safe=True, + ) try: result = await handler(args) except (ToolRetryError, UnexpectedModelBehavior) as error: diff --git a/tests/test_roadmap_implement_tool_log.py b/tests/test_roadmap_implement_tool_log.py index a94c4593a0..597fb367d3 100644 --- a/tests/test_roadmap_implement_tool_log.py +++ b/tests/test_roadmap_implement_tool_log.py @@ -56,7 +56,7 @@ def _lines(capsys: pytest.CaptureFixture[str]) -> list[str]: return capsys.readouterr().err.splitlines() -def test_a_refused_bare_word_is_logged_by_name_with_no_argument( +def test_a_refused_program_is_logged_by_name_with_its_first_arguments( store: InMemoryRoadmapStore, checkout: Path, programs: ProcessFake, @@ -69,13 +69,14 @@ def test_a_refused_bare_word_is_logged_by_name_with_no_argument( _step(store, checkout, script) - err = capsys.readouterr().err - assert err.splitlines() == ["Tool call: shell, program pytest, refused."] - assert "sentinel-value" not in err + assert _lines(capsys) == [ + "Tool call: shell, started: pytest tests/test_sample.py --flag=sentinel-value", + "Tool call: shell, program pytest, refused.", + ] -def _program_line(command: str, capsys: pytest.CaptureFixture[str]) -> str: - """The line of one call of a tool that has a `command` argument and takes any command.""" +def _call_lines(command: str, capsys: pytest.CaptureFixture[str]) -> list[str]: + """The lines of one call of a tool that has a `command` argument and takes any command.""" def shell(command: str) -> str: return "the output" @@ -85,7 +86,12 @@ def shell(command: str) -> str: tools=[shell], capabilities=[ToolCallLog().hooks()], ).run_sync("go") - return capsys.readouterr().err.strip() + return _lines(capsys) + + +def _program_line(command: str, capsys: pytest.CaptureFixture[str]) -> str: + """The line of the outcome of one call. The line before the call is `_call_lines()[0]`.""" + return _call_lines(command, capsys)[-1] @pytest.mark.parametrize("program", ["git", "uv", "ruff", "mypy", "openspec", "devops"]) @@ -154,7 +160,10 @@ def test_a_secret_as_the_first_word_never_reaches_the_log_of_a_step( _step(store, checkout, script) - assert _lines(capsys) == ["Tool call: shell, program other, refused."] + assert _lines(capsys) == [ + "Tool call: shell, started: other", + "Tool call: shell, program other, refused.", + ] def test_a_call_that_returns_is_logged_with_neither_its_path_nor_its_content( @@ -244,8 +253,83 @@ def broken() -> str: "Tool call: broken, failed.", "Tool call: fine, ok.", "Tool call: forbidden, program cat, refused.", + "Tool call: forbidden, started: cat", "Tool call: outside, retry.", ], Counter(cat=1), 2, ) + + +@pytest.mark.parametrize( + ("command", "shown"), + [ + pytest.param("git status", "git status", id="short"), + pytest.param( + "uv run devops ci test tests/test_a.py", + "uv run devops ci test tests/test_a.py", + id="six-words", + ), + pytest.param( + "uv run pytest -n 48 'tests/a b.py'", "uv run pytest -n 48 tests/a b.py", id="q" + ), + pytest.param( + "git log --oneline -n 5 -- src tests docs", "git log --oneline -n 5 -- ...", id="words" + ), + pytest.param("git log " + "a" * 500, "git log " + "a" * 152 + " ...", id="chars"), + pytest.param("API_KEY=hunter2 uv run x", "other", id="assignment"), + pytest.param(PASSWORD, "other", id="password"), + pytest.param("'unclosed quote", "other", id="unclosed"), + ], +) +def test_the_command_of_a_call_is_logged_before_the_call_with_its_first_arguments( + capsys: pytest.CaptureFixture[str], command: str, shown: str +) -> None: + assert _call_lines(command, capsys)[0] == f"Tool call: shell, started: {shown}" + + +@pytest.mark.parametrize("command", ["", " "]) +def test_a_command_with_no_word_has_no_line_before_the_call( + capsys: pytest.CaptureFixture[str], command: str +) -> None: + assert _call_lines(command, capsys) == ["Tool call: shell, ok."] + + +def test_the_line_of_a_command_is_written_before_the_call_runs( + capsys: pytest.CaptureFixture[str], +) -> None: + """A call that the kernel kills never ends, so only a line written before it names the + cause (#2806).""" + seen: list[list[str]] = [] + + def shell(command: str) -> str: + seen.append(_lines(capsys)) + return "the output" + + Agent( + ModelScript(tool_call("shell", command="uv run pytest -n 48"), say("Done.")).model(), + tools=[shell], + capabilities=[ToolCallLog().hooks()], + ).run_sync("go") + + assert seen == [["Tool call: shell, started: uv run pytest -n 48"]] + + +def test_a_secret_in_an_argument_never_reaches_the_line_of_a_command( + capsys: pytest.CaptureFixture[str], +) -> None: + lines = _call_lines(f"git remote add origin https://user:{TOKEN}@example.com/x.git", capsys) + + assert [line for line in lines if TOKEN[:12] in line or TOKEN[-12:] in line] == [] + assert lines[0].startswith("Tool call: shell, started: git remote add origin ") + + +def test_a_line_break_or_an_escape_sequence_in_an_argument_stays_on_one_line( + capsys: pytest.CaptureFixture[str], +) -> None: + lines = _call_lines("git commit -m 'one\ntwo\x1b[31mred'", capsys) + + assert lines == [ + "Tool call: shell, started: git commit -m one\\ntwo\\x1b[31mred", + "Tool call: shell, program git, ok.", + ] From 056ddf58739ec7082cc44d99dad14854b10c586c Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 30 Oct 2026 23:25:21 +0000 Subject: [PATCH 5/9] fix(roadmap): the child of devops ci keeps the worker bound and the log hides values (#2806) The isolated child environment drops PYTEST_XDIST_AUTO_NUM_WORKERS, so the pytest of devops ci counted the CPUs of the node again. The variable joins the allowlist. The command line of the Job log hid a value only by its form. It now keeps the name of name=value and hides the value unless it is a number, and it hides free text. --- src/devops_cli/core/process.py | 4 ++ src/devops_cli/lang/en/messages.py | 1 + src/devops_cli/roadmap/implement_tool_log.py | 45 ++++++++++---- tests/test_roadmap_implement_tool_log.py | 63 +++++++++++++++++--- tests/test_subprocess_env_boundary.py | 11 ++++ 5 files changed, 107 insertions(+), 17 deletions(-) diff --git a/src/devops_cli/core/process.py b/src/devops_cli/core/process.py index 6ada6b4324..3afcb1cc49 100644 --- a/src/devops_cli/core/process.py +++ b/src/devops_cli/core/process.py @@ -99,6 +99,10 @@ "GIT_COMMITTER_EMAIL", "CI", "PYTEST_CURRENT_TEST", + # A number only. `pytest-xdist` counts the CPUs of the node, not of the pod, so a child that + # runs `pytest` (the gate of `devops ci`) must keep the bound that the runner pod sets + # (#2806). + "PYTEST_XDIST_AUTO_NUM_WORKERS", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", } diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index f55e07b080..78501bd8be 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -2044,6 +2044,7 @@ class RoadmapMessages: implement_tool_line_program: str = "Tool call: {tool}, program {program}, {outcome}." implement_tool_started: str = "Tool call: {tool}, started: {command}" implement_tool_cut: str = " ..." + implement_tool_masked: str = "" implement_tick_turn: str = ( "The checks of your group passed, but `{path}` still holds these tasks of your group " "unticked:\n\n{tasks}\n\nChange `- [ ]` to `- [x]` in front of each task whose work is " diff --git a/src/devops_cli/roadmap/implement_tool_log.py b/src/devops_cli/roadmap/implement_tool_log.py index 23308c7ecd..f571646729 100644 --- a/src/devops_cli/roadmap/implement_tool_log.py +++ b/src/devops_cli/roadmap/implement_tool_log.py @@ -52,7 +52,7 @@ ) from devops_cli.lang import MESSAGES from devops_cli.output import print_muted -from devops_cli.security.sanitizer import mask_secrets +from devops_cli.security.sanitizer import sanitize_command_args_for_display # The first words that the log may show. They are fixed in the code, so no text of the model # reaches the log, and the count of the programs in the reason stays small by design. @@ -106,25 +106,50 @@ def logged_program(word: str | None) -> str: return MESSAGES.roadmap.implement_tool_other +def _logged_word(word: str) -> str: + """What the log shows of one argument. The mask of secrets finds a secret by its form, and + the value of `name=value` has none, so the line keeps the name and hides the value, except for + a number such as `--numprocesses=48`. A word with a space is free text, such as a message of a + commit, and the line hides it (#2806).""" + name, separator, value = word.partition("=") + if any(char.isspace() for char in name): + return MESSAGES.roadmap.implement_tool_masked + if separator and name and value and not value.isdecimal(): + return f"{name}={MESSAGES.roadmap.implement_tool_masked}" + return word + + +def _logged_words(words: list[str]) -> list[str]: + """The words through `_logged_word`, then through the mask of secrets for the words that + `_logged_word` left as they were. The mask of secrets reads a flag and its next word, such as + `--password hunter2`, and it never rewrites the name of a word that `_logged_word` masked.""" + masked = sanitize_command_args_for_display(words) + return [ + shown if (shown := _logged_word(word)) != word else other + for word, other in zip(words, masked, strict=True) + ] + + def logged_command(args: ValidatedToolArgs) -> str: """What the log shows of a command before the call runs (#2806): the first word and the words - after it, at most `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS`, with secrets masked, control - characters escaped and the text cut to `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS`. Empty when - the call has no command word. The word "other" when the first word is no known program: it can - be a password or a token, and the words after it mean nothing without it. The mask runs on a - fixed length of text before the cut, so that the cut cannot split a secret.""" + after it, at most `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS`, through `_logged_words`, with + control characters escaped and the text cut to `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS`. + Empty when the call has no command word. The word "other" when the first word is no known + program: it can be a password or a token, and the words after it mean nothing without it. Each + word is read to a fixed length before the mask, so that the cut cannot split a secret.""" word = command_word(args) if word is None: return "" if word not in _KNOWN_PROGRAMS: return MESSAGES.roadmap.implement_tool_other words = shlex.split(str(args["command"])) - shown = mask_secrets( - " ".join(words[:CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS])[ - :CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_READ_CHARS + shown = _logged_words( + [ + argument[:CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_READ_CHARS] + for argument in words[:CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS] ] ) - escaped = shown.encode("unicode_escape").decode("ascii") + escaped = " ".join(shown).encode("unicode_escape").decode("ascii") cut = ( len(words) > CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS or len(escaped) > CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS diff --git a/tests/test_roadmap_implement_tool_log.py b/tests/test_roadmap_implement_tool_log.py index 597fb367d3..fabbba68ca 100644 --- a/tests/test_roadmap_implement_tool_log.py +++ b/tests/test_roadmap_implement_tool_log.py @@ -70,7 +70,7 @@ def test_a_refused_program_is_logged_by_name_with_its_first_arguments( _step(store, checkout, script) assert _lines(capsys) == [ - "Tool call: shell, started: pytest tests/test_sample.py --flag=sentinel-value", + "Tool call: shell, started: pytest tests/test_sample.py --flag=", "Tool call: shell, program pytest, refused.", ] @@ -270,9 +270,8 @@ def broken() -> str: "uv run devops ci test tests/test_a.py", id="six-words", ), - pytest.param( - "uv run pytest -n 48 'tests/a b.py'", "uv run pytest -n 48 tests/a b.py", id="q" - ), + pytest.param("uv run pytest -n 48 'tests/a b.py'", "uv run pytest -n 48 ", id="q"), + pytest.param("uv run pytest --numprocesses=48", "uv run pytest --numprocesses=48", id="n"), pytest.param( "git log --oneline -n 5 -- src tests docs", "git log --oneline -n 5 -- ...", id="words" ), @@ -324,12 +323,62 @@ def test_a_secret_in_an_argument_never_reaches_the_line_of_a_command( assert lines[0].startswith("Tool call: shell, started: git remote add origin ") -def test_a_line_break_or_an_escape_sequence_in_an_argument_stays_on_one_line( +def test_an_escape_sequence_in_an_argument_stays_on_one_line( capsys: pytest.CaptureFixture[str], ) -> None: - lines = _call_lines("git commit -m 'one\ntwo\x1b[31mred'", capsys) + lines = _call_lines("git log one\x1b[31mred\x07", capsys) assert lines == [ - "Tool call: shell, started: git commit -m one\\ntwo\\x1b[31mred", + "Tool call: shell, started: git log one\\x1b[31mred\\x07", "Tool call: shell, program git, ok.", ] + + +def test_a_line_break_in_an_argument_is_hidden_with_the_text_around_it( + capsys: pytest.CaptureFixture[str], +) -> None: + lines = _call_lines("git commit -m 'one\ntwo'", capsys) + + assert lines[0] == "Tool call: shell, started: git commit -m " + + +@pytest.mark.parametrize( + ("command", "shown"), + [ + pytest.param( + "git -c http.extraheader='AUTHORIZATION: basic dXNlcjpwYXNzd29yZDEyMw==' fetch", + "git -c http.extraheader= fetch", + id="header", + ), + pytest.param( + "uv run devops config set ai.api_key=supersecretvalue123", + "uv run devops config set ai.api_key=", + id="dotted-key", + ), + pytest.param( + "uv run devops x SECRET=abcdef1234567890abcdef", + "uv run devops x SECRET=", + id="upper-key", + ), + pytest.param( + "uv run devops x password=hunter2", "uv run devops x password=", id="p" + ), + pytest.param( + "git commit -m 'the password is hunter2'", "git commit -m ", id="text" + ), + pytest.param( + "uv run devops --api-key=abc123def456ghi789jkl012", + "uv run devops --api-key=", + id="hyphen", + ), + pytest.param( + "uv run devops --password hunter2", "uv run devops --password ", id="flag" + ), + ], +) +def test_an_argument_with_a_value_after_a_name_shows_its_name_and_not_its_value( + capsys: pytest.CaptureFixture[str], command: str, shown: str +) -> None: + """The mask of secrets finds a secret by its form, and a secret has no form in an argument + such as `name=value`. The line keeps the name and hides the value, except for a number (#2806).""" + assert _call_lines(command, capsys)[0] == f"Tool call: shell, started: {shown}" diff --git a/tests/test_subprocess_env_boundary.py b/tests/test_subprocess_env_boundary.py index 32abf80f8f..d8c42f8f66 100644 --- a/tests/test_subprocess_env_boundary.py +++ b/tests/test_subprocess_env_boundary.py @@ -424,6 +424,17 @@ def test_no_key_of_the_ambient_allowlist_is_refused_from_a_caller(key: str) -> N assert build_subprocess_env(env={key: "example"})[key] == "example" +def test_an_isolated_child_keeps_the_worker_bound_of_the_test_runner( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """`devops ci` starts `pytest` through an isolated child. `pytest-xdist` counts the CPUs of the + node, so the child must keep the bound that the runner pod sets, or the full gate starts one + worker for each CPU of the node (#2806).""" + monkeypatch.setenv("PYTEST_XDIST_AUTO_NUM_WORKERS", "2") + + assert build_subprocess_env()["PYTEST_XDIST_AUTO_NUM_WORKERS"] == "2" + + # Each of these keys makes a library of the child load a module that the caller chooses, or # makes Python start from a virtual environment of the caller (#2503). OpenSSL reads a # configuration from OPENSSL_CONF, included files from OPENSSL_CONF_INCLUDE, providers from From a154f1f3aaac9ffdf3dbbaa64645453bdc1b0cfa Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 30 Oct 2026 23:25:26 +0000 Subject: [PATCH 6/9] fix(k8s): the runner memory limit fits the smallest node (#2806) The limit is 8 Gi, twice the peak of the killed pod, so a pod on a node with 15.5 Gi cannot starve it. The docs name the worker bound as a variable of the shell. --- docs/ROUTINE_TASKS.md | 2 +- k8s/README.md | 4 ++-- k8s/devops/cronjob-runner.yaml | 9 +++++---- tests/test_k8s_runner.py | 2 +- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/ROUTINE_TASKS.md b/docs/ROUTINE_TASKS.md index 446facf2ef..7df4a784b3 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 10 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 (12 Gi at most) and 7200 s; its pod has no Kubernetes token, and its shell gets none of the variables of the job. The Service's ServiceAccount has a Role that creates and reads 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 with no stop, stops the item (`implement.stopped` is `job`) until a person comments `implement: retry`. 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, 2 CPU, 4 Gi of memory (8 Gi at most) and 7200 s; 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 and reads 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 with no stop, stops the item (`implement.stopped` is `job`) until a person comments `implement: retry`. 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 295e9136f4..fc57c3fa57 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -597,11 +597,11 @@ kubectl -n devops logs -f job/ The implement job runs tests, `ruff`, `mypy` and OpenSpec, which the Service image does not hold. Its steps run in a runner Job (#2667). `devops k8s run-job --template runner --repo -- roadmap implement --item --confirm` makes one by hand. `--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 and the dev dependencies of `uv.lock`. The release publishes it 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 12 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, 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`. - **Role.** ServiceAccount `roadmap-service` is the account of the Service pod. Role `roadmap-service-jobs` in namespace `devops` allows `create`, `get` and `list` on `jobs`, `get` on CronJob `devops-cli-runner`, `list` on `pods` and `get` on `pods/log`, and nothing else. Kubernetes cannot limit `create` and `list` to a name, so those two cover the namespace. 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 7200 at most. 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. - **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. -- **Guarantees.** The shell of a step has none of the variables of the job. 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 after 7200 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. A real sandbox for the shell is planned (see Person steps). A person merges every pull request. +- **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 after 7200 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. 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. #### Webhook route diff --git a/k8s/devops/cronjob-runner.yaml b/k8s/devops/cronjob-runner.yaml index 45977c5a30..2dfeea2919 100644 --- a/k8s/devops/cronjob-runner.yaml +++ b/k8s/devops/cronjob-runner.yaml @@ -84,16 +84,17 @@ spec: resources: # The storage limit covers both volumes below (4 Gi and 1 Gi) and the log, so a # step cannot fill the disk of the node. The memory request is the normal peak of - # a Job (1.24 GB at most over 11 Jobs). The memory limit is a burst class (#2806): - # a kill needs a real runaway, and the node has room. The CPU limit only slows a - # step, so it stays. + # a Job (1.24 GB at most over the 10 Jobs that did not run out of memory). The + # memory limit is a burst class (#2806): twice the 4.13 GB that the killed Job had + # reached, and below the 15 Gi that the smallest node can allocate, so a pod that + # lands on it cannot starve the node. The CPU limit only slows a step, so it stays. requests: cpu: "2" memory: 4Gi ephemeral-storage: 2Gi limits: cpu: "2" - memory: 12Gi + memory: 8Gi ephemeral-storage: 6Gi volumes: - name: tmp diff --git a/tests/test_k8s_runner.py b/tests/test_k8s_runner.py index 2602950e14..9a53ad7a0c 100644 --- a/tests/test_k8s_runner.py +++ b/tests/test_k8s_runner.py @@ -77,7 +77,7 @@ def test_the_runner_cronjob_is_a_suspended_template_that_never_retries() -> None "IfNotPresent", { "requests": {"cpu": "2", "memory": "4Gi", "ephemeral-storage": "2Gi"}, - "limits": {"cpu": "2", "memory": "12Gi", "ephemeral-storage": "6Gi"}, + "limits": {"cpu": "2", "memory": "8Gi", "ephemeral-storage": "6Gi"}, }, ) From 7a94c9a5782e6ca7d16691888d30bde08936e87d Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 30 Oct 2026 23:25:33 +0000 Subject: [PATCH 7/9] docs(openspec): fold the review findings into the plan (#2806) --- .../design.md | 11 +++++----- .../proposal.md | 22 +++++++++++-------- .../specs/roadmap-implement-job/spec.md | 14 ++++++++++++ .../specs/roadmap-implement-runner/spec.md | 2 +- .../specs/roadmap-implement-step/spec.md | 12 ++++++++-- .../specs/subprocess-environment/spec.md | 10 +++++++++ .../tasks.md | 19 ++++++++++++---- 7 files changed, 69 insertions(+), 21 deletions(-) create mode 100644 openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-job/spec.md create mode 100644 openspec/changes/2806-runner-memory-and-command-log/specs/subprocess-environment/spec.md diff --git a/openspec/changes/2806-runner-memory-and-command-log/design.md b/openspec/changes/2806-runner-memory-and-command-log/design.md index 0fddef2af3..3951146d09 100644 --- a/openspec/changes/2806-runner-memory-and-command-log/design.md +++ b/openspec/changes/2806-runner-memory-and-command-log/design.md @@ -2,20 +2,21 @@ ## Decisions -- **Raise the limit to 12 Gi and keep the request at 4 Gi.** The owner said to raise or remove the limits where needed. The measured peak of normal Jobs is 1.24 GB at most, so 4 Gi is right for the request: the scheduler needs only that. A limit of 12 Gi lets a step burst. A kill then needs a real runaway, and the node has room (64 GB, 43 percent requested). 12 Gi is below the cost of 48 test workers (about 13 GB, from 280 MB each), so the limit is not the fix of the cause. +- **Raise the limit to 8 Gi and keep the request at 4 Gi.** The measured peak of normal Jobs is 1.24 GB at most, so 4 Gi is right for the request: the scheduler needs only that. The killed pod had reached 4.13 GB at its cap, and 8 Gi is twice that. A step can burst, and a kill needs a real runaway. 8 Gi fits the smallest node (15.5 Gi allocatable), which matters because the pod has no node selector. Pinning the pod to the large nodes would need a role label and a second change, and the worker bound already removes the suspected cause, so the change takes the lower limit. - **Bound the test workers with the variable that xdist reads.** The cause is a worker count from the CPUs of the node. `PYTEST_XDIST_AUTO_NUM_WORKERS` is the documented setting of `pytest-xdist` for this, and `-n logical` honors it. Setting it to the CPU limit (2) cost no time in the measured run (23 s with 2 workers, 24 s with 16). The manifest holds the value, and a test checks that it equals the CPU limit, so the two cannot drift. +- **The isolated child keeps the variable too.** `devops ci` starts `pytest` through `run_subprocess`, and `build_subprocess_env` drops every variable that is not on its allowlist. So `PYTEST_XDIST_AUTO_NUM_WORKERS` joins `DEFAULT_ALLOWED_ENV_VARS`. It holds a number and matches no denied pattern. - **The shell takes the variable from the process, like `UV_PYTHON`.** The shell of a step gets only `PATH`, `HOME` and the locale of the process, plus `shell_environment`. So a variable on the pod does not reach `pytest` unless `shell_environment` passes it. The function passes it only when the process has it, so a developer machine keeps its own count. - **A separate line before the call, not a change of the line after it.** The line after the call has the outcome, which a killed call never reaches. The new line needs only the command, so it can come first. The line after the call stays as it is, so the count of refused programs and the other readers of the line do not change. -- **The command line shows a bounded form.** The first word must be a known program (the rule of the line after the call). Any other first word shows as `other`, because a first word can be a password or a token that the model read from a file. For a known program the line shows at most `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS` words. The text is read to a fixed length, masked with `mask_secrets`, escaped with `unicode_escape` so that it is one line, and cut to `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS`. The mask runs before the cut, so a cut cannot split a secret. -- **Residual risk, accepted.** The mask finds a secret by its form. A password that the model read from a file and passes as the argument of an allowed program, such as `git commit -m `, has no form and stays in the log. The Job log is the only evidence of what the agent did, and a command with no argument cannot show a cause like `-n 48`. The issue asks for the arguments. The bound on words and characters and the allowlist of programs limit the harm. +- **The command line shows a bounded form.** The first word must be a known program (the rule of the line after the call). Any other first word shows as `other`, because a first word can be a password or a token that the model read from a file. For a known program the line shows at most `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS` words. Each word is read to a fixed length first. An argument with a space is free text, and the line hides it. In `name=value`, the line keeps the name and hides the value unless it is a number, because a value has no form for a mask to find. `sanitize_command_args_for_display` masks the other words and the word after a flag such as `--password`. The text is then escaped with `unicode_escape` so that it is one line, and cut to `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS`. A word that the project masks keeps its name, so the line still shows the real flag. +- **Residual risk, accepted.** A secret as a bare word with no form, such as a password after `git commit -m` that has no space, or the word after a flag that the project does not know, stays in the line. The Job log is the only evidence of what the agent did, and a command with no argument cannot show a cause like `-n 48`. The issue asks for the arguments. The bound on words and characters and the allowlist of programs limit the harm. - **CPU and storage limits stay.** See Feasibility in the proposal for the numbers. - **The roadmap-service limits stay.** Its peak is 57 percent of its limit. ## Rejected alternatives -- **Raise the limit only.** The evidence shows 48 workers cost about 13 GB. A limit of 12 Gi would still kill the same run, and a limit of 16 Gi would leave a small node with no margin. It fixes the symptom of one run and not the cause. +- **Raise the limit only.** The evidence shows 48 workers cost about 13 GB. A limit that fits the smallest node would still kill the same run, and a limit that covers 48 workers would leave a small node with no margin. It fixes the symptom of one run and not the cause. - **Bound the workers only, keep 4 Gi.** The cause of this kill is not proven, as the log has no command. Another command, such as `mypy --strict` on a large file set, can also pass 4 Gi. The owner asked for a burst class, and the cost is a limit that the node can pay. -- **Remove the memory limit.** A pod with no limit has no cgroup cap, so a runaway command would make the kernel kill other pods on the node. The 12 Gi limit keeps a runaway inside its pod. +- **Remove the memory limit.** A pod with no limit has no cgroup cap, so a runaway command would make the kernel kill other pods on the node. The 8 Gi limit keeps a runaway inside its pod. - **Detect the cgroup quota in the code and pick the worker count.** It is hand-rolled code for what a variable of the installed tool does. - **Change `addopts` to `-n 2`.** It slows the full suite on a developer machine and in CI, where the CPUs are real. - **Write the command in the line after the call.** A killed call never writes it, which is the case the issue is about. diff --git a/openspec/changes/2806-runner-memory-and-command-log/proposal.md b/openspec/changes/2806-runner-memory-and-command-log/proposal.md index b3240cbb4c..62dd4db776 100644 --- a/openspec/changes/2806-runner-memory-and-command-log/proposal.md +++ b/openspec/changes/2806-runner-memory-and-command-log/proposal.md @@ -8,10 +8,10 @@ Two faults show here. The pod has a memory limit that a runaway command reaches. ## What Changes -- Memory limit of the runner container: from 4 Gi to 12 Gi. The request stays at 4 Gi, so the scheduler places the pod as before and the pod can burst. The CPU limit (2) and the storage limits stay as they are. The numbers that justify this are in Feasibility. -- The pod sets `PYTEST_XDIST_AUTO_NUM_WORKERS` to `2`, the CPU limit. The shell of a step takes this variable from the process when it is set, as it takes `UV_PYTHON`. The project runs `pytest -n logical`, and `pytest-xdist` reads the CPU count of the node, not the CPU limit of the pod, so on the node `hog` a test run starts 48 workers in a pod that has 2 CPU. This is the likely cause of the kill. -- The tool log writes one more line for a call that has a `command`, before the call runs: `Tool call: shell, started: `. The command is the program and its first arguments, masked, on one line, and bounded. The line after the call stays. -- A consumer observes the manifest and the Job log, so the change carries a spec delta: it modifies one requirement of `roadmap-implement-runner` and one of `roadmap-implement-step`, and adds one requirement to each. +- Memory limit of the runner container: from 4 Gi to 8 Gi. The request stays at 4 Gi, so the scheduler places the pod as before and the pod can burst. 8 Gi is twice the 4.13 GB that the killed pod had reached, and it fits the smallest node (see Feasibility). The CPU limit (2) and the storage limits stay as they are. The numbers that justify this are in Feasibility. +- The pod sets `PYTEST_XDIST_AUTO_NUM_WORKERS` to `2`, the CPU limit. The shell of a step takes this variable from the process when it is set, as it takes `UV_PYTHON`. The isolated child environment of `run_subprocess` keeps it too (`DEFAULT_ALLOWED_ENV_VARS`), so the `pytest` that `devops ci` starts gets the bound. The project runs `pytest -n logical`, and `pytest-xdist` reads the CPU count of the node, not the CPU limit of the pod, so on the node `hog` a test run starts 48 workers in a pod that has 2 CPU. This is the likely cause of the kill. +- The tool log writes one more line for a call that has a `command`, before the call runs: `Tool call: shell, started: `. The command is the program and its first arguments, on one line, and bounded. The line keeps the name of an argument `name=value` and hides a value that is not a number, and it hides an argument with a space. The mask of secrets runs on the rest. The line after the call stays. +- A consumer observes the manifest and the Job log, so the change carries a spec delta: it modifies one requirement of `roadmap-implement-runner`, one of `roadmap-implement-step` and one of `roadmap-implement-job` (the list of variables that the shell gets), and adds one requirement to `roadmap-implement-runner`, `roadmap-implement-step` and `subprocess-environment`. - This change fits one pull request. ## Capabilities @@ -20,24 +20,28 @@ Two faults show here. The pod has a memory limit that a runaway command reaches. - `roadmap-implement-runner`: the memory limit of the template and the worker bound of the test runner. - `roadmap-implement-step`: the tool log line before a command and the variable that the shell takes. +- `roadmap-implement-job`: the variables that the shell of a step gets. +- `subprocess-environment`: the isolated child keeps the worker bound. ## Impact - `k8s/devops/cronjob-runner.yaml`, `k8s/README.md`, `docs/ROUTINE_TASKS.md`. -- `src/devops_cli/roadmap/implement_tool_log.py`, `src/devops_cli/roadmap/implement_step.py`, `src/devops_cli/lang/en/messages.py`, `src/devops_cli/config/constants.py`. -- `tests/test_k8s_runner.py`, `tests/test_roadmap_implement_tool_log.py`, `tests/test_roadmap_implement_step.py`. +- `src/devops_cli/roadmap/implement_tool_log.py`, `src/devops_cli/roadmap/implement_step.py`, `src/devops_cli/core/process.py`, `src/devops_cli/lang/en/messages.py`, `src/devops_cli/config/constants.py`. +- `tests/test_k8s_runner.py`, `tests/test_roadmap_implement_tool_log.py`, `tests/test_roadmap_implement_step.py`, `tests/test_subprocess_env_boundary.py`. - The admission policy `roadmap-service-jobs` needs no change (see Feasibility). ## Feasibility - **The kill is real.** `kubectl -n devops get pods` shows pod `devops-cli-runner-20261030-202214-d182-d8rk7` as `OOMKilled` on node `hog`. Prometheus, `max_over_time(container_memory_working_set_bytes{namespace="devops",container="runner"}[30h])`, gives 4,133,457,920 bytes for it, at the 4 Gi limit (4,294,967,296 bytes). The log of that pod ends with eight tool lines, the last one `write_file, ok`. The next call was a shell call, and its line is written only after the call ends, so the command that used the memory is not in the log. The command is therefore not proven. The proposal states the most likely one below. - **The other Jobs are small.** The 10 other runner pods peaked between 270,610,432 and 1,240,924,160 bytes (6 to 29 percent of 4 Gi). The OOM pod throttled 77 percent of its CPU periods (`container_cpu_cfs_throttled_periods_total` over `container_cpu_cfs_periods_total`). The other pods throttled between 9 and 40 percent. -- **The likely command and its cost, measured.** `pyproject.toml` sets `addopts = "-n logical ..."`. In the xdist source (`xdist/plugin.py`, `pytest_xdist_auto_num_workers`), the worker count is the variable `PYTEST_XDIST_AUTO_NUM_WORKERS` when it is set, else `psutil.cpu_count(logical=True)`. `psutil` reads the CPUs of the node, and a CPU limit of a pod does not change that number. Node `hog` has 48 CPUs (`kubectl describe node hog`). Measured on this host (16 CPUs), the sum of the PSS of the process tree for `pytest tests/test_roadmap_implement_step.py tests/test_k8s.py tests/test_roadmap_implement_tool_log.py` (263 tests): 766 MB with 2 workers in 23 s, 4,488 MB with 16 workers in 24 s. That is about 280 MB for each worker, and the run is not faster. 48 workers cost about 13 GB. So the limit alone does not fix the cause: 12 Gi is below that figure. The worker bound does. -- **The limit.** Hog has 64 GB. It has 43 percent of its memory requested and 24 percent as limits (`kubectl describe node hog`). The Service makes no second Job for a repository while one runs. A limit of 12 Gi with the request of 4 Gi is a burst class: a kill needs a real runaway. If the node comes under pressure, the kubelet evicts the pods that exceed their request first, and a runner is one of them. +- **The likely command and its cost, measured.** `pyproject.toml` sets `addopts = "-n logical ..."`. In the xdist source (`xdist/plugin.py`, `pytest_xdist_auto_num_workers`), the worker count is the variable `PYTEST_XDIST_AUTO_NUM_WORKERS` when it is set, else `psutil.cpu_count(logical=True)`. `psutil` reads the CPUs of the node, and a CPU limit of a pod does not change that number. Node `hog` has 48 CPUs (`kubectl describe node hog`). Measured on this host (16 CPUs), the sum of the PSS of the process tree for `pytest tests/test_roadmap_implement_step.py tests/test_k8s.py tests/test_roadmap_implement_tool_log.py` (263 tests): 766 MB with 2 workers in 23 s, 4,488 MB with 16 workers in 24 s. That is about 280 MB for each worker, and the run is not faster. 48 workers cost about 13 GB. So the limit alone does not fix the cause: the worker bound does. Without the bound, 48 workers need more than 8 Gi, and the pod would be killed again. +- **The limit.** The killed pod had reached 4.13 GB at the 4 Gi cap and was still growing, so the real peak of that command is not known. 8 Gi is twice that figure. The worker bound removes the suspected cause, and the limit is the margin for a cause that the log does not show. The nodes allocate 15.5 Gi (two nodes) and 62.6 Gi (two nodes) of memory (`kubectl get nodes`), and the pod has no node selector. So the limit must fit the smallest node: on a node with 15.5 Gi, 8 Gi plus the 3.8 Gi in use stays below the allocatable memory, and 12 Gi would not. The Service makes no second Job for a repository while one runs. The request of 4 Gi stays, so the QoS class is Burstable. If a node comes under pressure, the kubelet evicts the pods that exceed their request first, and a runner is one of them. - **CPU and storage do not bind.** A CPU limit only slows a process. The 10 completed Jobs ran between 2.5 and 11 minutes against a deadline of 7200 s, so the limit of 2 stays. No `container_fs_usage_bytes` series exists for the runner, there is no eviction event in the namespace, and the 10 other Jobs completed, so the storage limits stay. - **The roadmap-service pod.** Its peak over 7 days is 611,205,120 bytes, 57 percent of its 1 Gi limit. That is a margin of 43 percent, so its limits stay. - **The admission policy.** `k8s/devops/roadmap-service/admissionpolicy.yaml` does not pin the resources of a Job (its header says so), and no expression reads `resources`. `tests/test_k8s_job_admission_policy.py` runs every expression against the Job that the template makes, so it covers the new limit. This session cannot run `kubectl create --dry-run=server` as the Service account, so the live admission is reasoned from the CEL text and the test. -- **Not measured.** A Job on #2656 in a pod with the new settings. The cluster is read-only for this session. After the manifest syncs, a person or the next Job confirms the peak in Prometheus. +- **Not proven.** The command that the killed pod ran is not proven: its log has no command. The full-suite run with `-n logical` is the likely cause, and the measure above shows its cost on a smaller host. Acceptance criteria 1 (the named command and its peak) and 2 (a Job that stays under the limit with margin) stay open. They need a Job on #2656 in a pod with the new settings, and the cluster is read-only for this session. After the manifest syncs, the tool log line of the next Job names the command, and Prometheus shows its peak. +- **The child of `devops ci`.** `build_subprocess_env` drops every variable that is not on its allowlist, so a `pytest` that `devops ci` starts through `run_subprocess` lost the bound. `PYTEST_XDIST_AUTO_NUM_WORKERS` holds a number only and no pattern of the denied keys matches it, so it joins `DEFAULT_ALLOWED_ENV_VARS`. A test checks it. +- **The log line and the secrets.** The mask of secrets finds a secret by its form. A value in `name=value` (a dotted configuration key, a header, an upper-case name) has no form, so the line hides each such value that is not a number. It also hides an argument with a space. The residual risk is a secret as a bare word with no form, such as `git commit -m` followed by a password with no space, or the next word of a flag that the project does not know. The Job log is the only evidence of a killed step, and the bound on words and characters limits the harm. ## Existing Tool Considered diff --git a/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-job/spec.md b/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-job/spec.md new file mode 100644 index 0000000000..d724d73bd8 --- /dev/null +++ b/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-job/spec.md @@ -0,0 +1,14 @@ +# Spec Delta + +## MODIFIED Requirements + +### Requirement: A runner process cannot be read by its own shell +Before the first step, the job in a runner SHALL clear the dumpable flag of its own process with `prctl(PR_SET_DUMPABLE, 0)`. A child of the job SHALL then not read `/proc//environ` of the job. A call that the kernel refuses SHALL make `apply_implement` raise `RoadmapImplementError`, and no step SHALL run. The step of the agent SHALL get none of the variables of the job, except the paths `UV_CACHE_DIR` and `UV_PYTHON` of uv and `PYTEST_XDIST_AUTO_NUM_WORKERS`, the worker bound of the test runner. + +#### Scenario: A child reads the environment of its parent +- **WHEN** a process sets the flag, holds a variable in its starting environment, and starts a child that opens `/proc//environ` +- **THEN** the child gets `PermissionError` + +#### Scenario: The refusal +- **WHEN** `prctl` returns -1 and `apply_implement` runs a plan +- **THEN** `apply_implement` raises `RoadmapImplementError` that names `PR_SET_DUMPABLE`, and no step, no model request and no program runs diff --git a/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-runner/spec.md b/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-runner/spec.md index 38d0d196bd..d88562193b 100644 --- a/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-runner/spec.md +++ b/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-runner/spec.md @@ -3,7 +3,7 @@ ## MODIFIED Requirements ### Requirement: A suspended CronJob is the template of the runner Job -CronJob `devops-cli-runner` in namespace `devops` SHALL be suspended and SHALL never run on a schedule. Its Job template SHALL name the image `ghcr.io/dan-petty/devops-cli/runner` with no tag, request and limit 2 CPU, request 4 Gi and limit 12 Gi of memory, request 2 Gi and limit 6 Gi of `ephemeral-storage`, set `activeDeadlineSeconds` to 7200 and `backoffLimit` to 0, and use the `securityContext` of CronJob `devops-cli`. Its pod SHALL use ServiceAccount `devops-cli`, which mounts no token. +CronJob `devops-cli-runner` in namespace `devops` SHALL be suspended and SHALL never run on a schedule. Its Job template SHALL name the image `ghcr.io/dan-petty/devops-cli/runner` with no tag, request and limit 2 CPU, request 4 Gi and limit 8 Gi of memory, request 2 Gi and limit 6 Gi of `ephemeral-storage`, set `activeDeadlineSeconds` to 7200 and `backoffLimit` to 0, and use the `securityContext` of CronJob `devops-cli`. Its pod SHALL use ServiceAccount `devops-cli`, which mounts no token. #### Scenario: The manifest is read - **WHEN** a test reads the rendered `k8s/devops` kustomization diff --git a/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md b/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md index 43abacde06..880472bd4a 100644 --- a/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md +++ b/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md @@ -3,7 +3,7 @@ ## MODIFIED Requirements ### Requirement: Every tool call of a step writes one line to the Job log -The agent of a step SHALL write one line to the standard error stream for each tool call, when the call ends. The line SHALL hold the name of the tool, the program of the `command` argument when the tool has one, and the outcome: `ok`, `refused`, `retry` or `failed`. The program SHALL be the first word of the command when it is a program of the allowlist or a program of `IMPLEMENT_SHELL_REPLACEMENTS`, else the word `other`. Before a call that has a `command` runs, the agent SHALL write the line `Tool call: , started: `. The command SHALL be the first word and the words after it, at most `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS` words, with secrets masked, control characters escaped, and cut to `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS` characters. When the first word is not a known program, the command SHALL be the word `other`. No line SHALL hold a path or a content of a call that has no `command`, or any output. +The agent of a step SHALL write one line to the standard error stream for each tool call, when the call ends. The line SHALL hold the name of the tool, the program of the `command` argument when the tool has one, and the outcome: `ok`, `refused`, `retry` or `failed`. The program SHALL be the first word of the command when it is a program of the allowlist or a program of `IMPLEMENT_SHELL_REPLACEMENTS`, else the word `other`. Before a call that has a `command` runs, the agent SHALL write the line `Tool call: , started: `. The command SHALL be the first word and the words after it, at most `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS` words, with the value of each `name=value` word that is not a number and each word with a space masked, other secrets masked, control characters escaped, and cut to `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS` characters. When the first word is not a known program, the command SHALL be the word `other`. No line SHALL hold a path or a content of a call that has no `command`, or any output. #### Scenario: A refused program - **WHEN** the model calls the shell tool with `pytest tests/test_sample.py`, and then ends its run @@ -25,8 +25,16 @@ The agent of a step SHALL write one line to the standard error stream for each t - **WHEN** the command is `git remote add origin https://user:ghp_@example.com/x.git`, with a GitHub token in place of `` - **THEN** the line holds no part of the token +#### Scenario: A value after a name +- **WHEN** an argument has the form `name=value` and the value is not a number, for example `ai.api_key=` or `http.extraheader=AUTHORIZATION: basic ` +- **THEN** the line holds the name and the word `` in place of the value, and an argument with a number as the value, such as `--numprocesses=48`, stays as it is + +#### Scenario: Free text in an argument +- **WHEN** an argument holds a space, as the message of a commit does +- **THEN** the line holds the word `` in place of the argument + #### Scenario: A control character in an argument -- **WHEN** an argument holds a line break or an escape sequence +- **WHEN** an argument holds an escape sequence or another control character that is no space - **THEN** the line is one line, and it holds the escaped form of the character #### Scenario: A call that returns diff --git a/openspec/changes/2806-runner-memory-and-command-log/specs/subprocess-environment/spec.md b/openspec/changes/2806-runner-memory-and-command-log/specs/subprocess-environment/spec.md new file mode 100644 index 0000000000..7e8d6e7609 --- /dev/null +++ b/openspec/changes/2806-runner-memory-and-command-log/specs/subprocess-environment/spec.md @@ -0,0 +1,10 @@ +# Spec Delta + +## ADDED Requirements + +### Requirement: An isolated child gets the worker bound of the test runner +With isolation on, `build_subprocess_env` SHALL keep `PYTEST_XDIST_AUTO_NUM_WORKERS` in the child environment when the process has it. `pytest-xdist` counts the CPUs of the node, not of the pod, so a child that runs `pytest`, such as the gate of `devops ci`, needs the bound that the runner pod sets. + +#### Scenario: The process has the variable +- **WHEN** the process sets `PYTEST_XDIST_AUTO_NUM_WORKERS` to `2` and a caller builds an isolated child environment +- **THEN** the child environment holds `PYTEST_XDIST_AUTO_NUM_WORKERS` with the value `2` diff --git a/openspec/changes/2806-runner-memory-and-command-log/tasks.md b/openspec/changes/2806-runner-memory-and-command-log/tasks.md index b0340b5fef..5e94c91904 100644 --- a/openspec/changes/2806-runner-memory-and-command-log/tasks.md +++ b/openspec/changes/2806-runner-memory-and-command-log/tasks.md @@ -2,9 +2,9 @@ ## 1. The memory limit and the worker bound of the runner Job -- [x] Write failing tests in `tests/test_k8s_runner.py`: the memory limit of the runner is 12 Gi and its request is 4 Gi; `PYTEST_XDIST_AUTO_NUM_WORKERS` equals the CPU limit; the Job that the template makes passes the admission policy. +- [x] Write failing tests in `tests/test_k8s_runner.py`: the memory limit of the runner is 8 Gi and its request is 4 Gi; `PYTEST_XDIST_AUTO_NUM_WORKERS` equals the CPU limit; the Job that the template makes passes the admission policy. - Verification: `uv run devops ci test tests/test_k8s_runner.py tests/test_k8s_job_admission_policy.py` -- [x] Change `k8s/devops/cronjob-runner.yaml`: memory limit 12 Gi, the worker variable, and the comments. Change `k8s/README.md` and `docs/ROUTINE_TASKS.md` where they state the numbers. +- [x] Change `k8s/devops/cronjob-runner.yaml`: memory limit 8 Gi, the worker variable, and the comments. Change `k8s/README.md` and `docs/ROUTINE_TASKS.md` where they state the numbers. - Verification: `uv run devops ci test tests/test_k8s_runner.py tests/test_k8s_job_admission_policy.py` ## 2. The shell takes the worker bound @@ -21,12 +21,23 @@ - [x] Change `src/devops_cli/roadmap/implement_tool_log.py`, `src/devops_cli/lang/en/messages.py` and `src/devops_cli/config/constants.py`. - Verification: `uv run devops ci test tests/test_roadmap_implement_tool_log.py tests/test_roadmap_implement_step.py` -## 4. The documentation +## 4. Review findings + +- [x] Write the failing test in `tests/test_subprocess_env_boundary.py` and add `PYTEST_XDIST_AUTO_NUM_WORKERS` to `DEFAULT_ALLOWED_ENV_VARS`, so that the `pytest` of `devops ci` gets the bound. + - Verification: `uv run devops ci test tests/test_subprocess_env_boundary.py` +- [x] Write the failing tests for `name=value`, free text and flag arguments in `tests/test_roadmap_implement_tool_log.py`, and mask them in `logged_command`. + - Verification: `uv run devops ci test tests/test_roadmap_implement_tool_log.py` +- [x] Lower the memory limit to 8 Gi so that it fits the smallest node, and name the unproven command in the proposal. + - Verification: `uv run devops ci test tests/test_k8s_runner.py tests/test_k8s_job_admission_policy.py` +- [x] Fix the statements about the variables of the shell in the spec of `roadmap-implement-job`, `k8s/README.md` and `docs/ROUTINE_TASKS.md`. + - Verification: `uv run devops openspec check` + +## 5. The documentation - [ ] Regenerate the documentation. - Verification: `uv run devops docs generate --sync-readme` and `uv run devops docs check` -## 5. Archive +## 6. Archive - [ ] Archive the change. - Verification: `uv run devops openspec archive 2806-runner-memory-and-command-log` From 9b0bd5e1d57812e586169fef48b04dd0fb448de6 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 30 Oct 2026 23:25:57 +0000 Subject: [PATCH 8/9] docs(openspec): tick the tasks of the change (#2806) --- openspec/changes/2806-runner-memory-and-command-log/tasks.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openspec/changes/2806-runner-memory-and-command-log/tasks.md b/openspec/changes/2806-runner-memory-and-command-log/tasks.md index 5e94c91904..b4be712a6f 100644 --- a/openspec/changes/2806-runner-memory-and-command-log/tasks.md +++ b/openspec/changes/2806-runner-memory-and-command-log/tasks.md @@ -34,10 +34,10 @@ ## 5. The documentation -- [ ] Regenerate the documentation. +- [x] Regenerate the documentation. - Verification: `uv run devops docs generate --sync-readme` and `uv run devops docs check` ## 6. Archive -- [ ] Archive the change. +- [x] Archive the change. - Verification: `uv run devops openspec archive 2806-runner-memory-and-command-log` From b460571cd3805e0d307068ae3b009013b401d619 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Fri, 30 Oct 2026 23:28:20 +0000 Subject: [PATCH 9/9] docs(openspec): archive the runner memory and command log change (#2806) --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 2 +- .../specs/roadmap-implement-job/spec.md | 2 +- .../specs/roadmap-implement-runner/spec.md | 0 .../specs/roadmap-implement-step/spec.md | 57 ++++++++++--------- .../specs/subprocess-environment/spec.md | 0 .../tasks.md | 0 openspec/specs/roadmap-implement-job/spec.md | 2 +- .../specs/roadmap-implement-runner/spec.md | 13 ++++- openspec/specs/roadmap-implement-step/spec.md | 56 +++++++++++++++--- openspec/specs/subprocess-environment/spec.md | 7 +++ 12 files changed, 99 insertions(+), 40 deletions(-) rename openspec/changes/{2806-runner-memory-and-command-log => archive/2026-10-30-2806-runner-memory-and-command-log}/.openspec.yaml (100%) rename openspec/changes/{2806-runner-memory-and-command-log => archive/2026-10-30-2806-runner-memory-and-command-log}/design.md (100%) rename openspec/changes/{2806-runner-memory-and-command-log => archive/2026-10-30-2806-runner-memory-and-command-log}/proposal.md (98%) rename openspec/changes/{2806-runner-memory-and-command-log => archive/2026-10-30-2806-runner-memory-and-command-log}/specs/roadmap-implement-job/spec.md (59%) rename openspec/changes/{2806-runner-memory-and-command-log => archive/2026-10-30-2806-runner-memory-and-command-log}/specs/roadmap-implement-runner/spec.md (100%) rename openspec/changes/{2806-runner-memory-and-command-log => archive/2026-10-30-2806-runner-memory-and-command-log}/specs/roadmap-implement-step/spec.md (77%) rename openspec/changes/{2806-runner-memory-and-command-log => archive/2026-10-30-2806-runner-memory-and-command-log}/specs/subprocess-environment/spec.md (100%) rename openspec/changes/{2806-runner-memory-and-command-log => archive/2026-10-30-2806-runner-memory-and-command-log}/tasks.md (100%) diff --git a/openspec/changes/2806-runner-memory-and-command-log/.openspec.yaml b/openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/.openspec.yaml similarity index 100% rename from openspec/changes/2806-runner-memory-and-command-log/.openspec.yaml rename to openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/.openspec.yaml diff --git a/openspec/changes/2806-runner-memory-and-command-log/design.md b/openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/design.md similarity index 100% rename from openspec/changes/2806-runner-memory-and-command-log/design.md rename to openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/design.md diff --git a/openspec/changes/2806-runner-memory-and-command-log/proposal.md b/openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/proposal.md similarity index 98% rename from openspec/changes/2806-runner-memory-and-command-log/proposal.md rename to openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/proposal.md index 62dd4db776..3f59d26d7c 100644 --- a/openspec/changes/2806-runner-memory-and-command-log/proposal.md +++ b/openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/proposal.md @@ -11,7 +11,7 @@ Two faults show here. The pod has a memory limit that a runaway command reaches. - Memory limit of the runner container: from 4 Gi to 8 Gi. The request stays at 4 Gi, so the scheduler places the pod as before and the pod can burst. 8 Gi is twice the 4.13 GB that the killed pod had reached, and it fits the smallest node (see Feasibility). The CPU limit (2) and the storage limits stay as they are. The numbers that justify this are in Feasibility. - The pod sets `PYTEST_XDIST_AUTO_NUM_WORKERS` to `2`, the CPU limit. The shell of a step takes this variable from the process when it is set, as it takes `UV_PYTHON`. The isolated child environment of `run_subprocess` keeps it too (`DEFAULT_ALLOWED_ENV_VARS`), so the `pytest` that `devops ci` starts gets the bound. The project runs `pytest -n logical`, and `pytest-xdist` reads the CPU count of the node, not the CPU limit of the pod, so on the node `hog` a test run starts 48 workers in a pod that has 2 CPU. This is the likely cause of the kill. - The tool log writes one more line for a call that has a `command`, before the call runs: `Tool call: shell, started: `. The command is the program and its first arguments, on one line, and bounded. The line keeps the name of an argument `name=value` and hides a value that is not a number, and it hides an argument with a space. The mask of secrets runs on the rest. The line after the call stays. -- A consumer observes the manifest and the Job log, so the change carries a spec delta: it modifies one requirement of `roadmap-implement-runner`, one of `roadmap-implement-step` and one of `roadmap-implement-job` (the list of variables that the shell gets), and adds one requirement to `roadmap-implement-runner`, `roadmap-implement-step` and `subprocess-environment`. +- A consumer observes the manifest and the Job log, so the change carries a spec delta: it modifies one requirement of `roadmap-implement-runner`, one of `roadmap-implement-step` and one of `roadmap-implement-job` (the list of variables that the shell gets), and adds requirements to `roadmap-implement-runner`, `roadmap-implement-step` and `subprocess-environment`. - This change fits one pull request. ## Capabilities diff --git a/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-job/spec.md b/openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/specs/roadmap-implement-job/spec.md similarity index 59% rename from openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-job/spec.md rename to openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/specs/roadmap-implement-job/spec.md index d724d73bd8..bfecaba9bb 100644 --- a/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-job/spec.md +++ b/openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/specs/roadmap-implement-job/spec.md @@ -3,7 +3,7 @@ ## MODIFIED Requirements ### Requirement: A runner process cannot be read by its own shell -Before the first step, the job in a runner SHALL clear the dumpable flag of its own process with `prctl(PR_SET_DUMPABLE, 0)`. A child of the job SHALL then not read `/proc//environ` of the job. A call that the kernel refuses SHALL make `apply_implement` raise `RoadmapImplementError`, and no step SHALL run. The step of the agent SHALL get none of the variables of the job, except the paths `UV_CACHE_DIR` and `UV_PYTHON` of uv and `PYTEST_XDIST_AUTO_NUM_WORKERS`, the worker bound of the test runner. +Before the first step, the job in a runner SHALL clear the dumpable flag of its own process with `prctl(PR_SET_DUMPABLE, 0)`, so that no child reads `/proc//environ` of the job. A call that the kernel refuses SHALL make `apply_implement` raise `RoadmapImplementError`, and no step SHALL run. The step of the agent SHALL get none of the variables of the job, except `UV_CACHE_DIR`, `UV_PYTHON` and `PYTEST_XDIST_AUTO_NUM_WORKERS`. #### Scenario: A child reads the environment of its parent - **WHEN** a process sets the flag, holds a variable in its starting environment, and starts a child that opens `/proc//environ` diff --git a/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-runner/spec.md b/openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/specs/roadmap-implement-runner/spec.md similarity index 100% rename from openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-runner/spec.md rename to openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/specs/roadmap-implement-runner/spec.md diff --git a/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md b/openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md similarity index 77% rename from openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md rename to openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md index 880472bd4a..73d6d412e7 100644 --- a/openspec/changes/2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md +++ b/openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/specs/roadmap-implement-step/spec.md @@ -3,16 +3,41 @@ ## MODIFIED Requirements ### Requirement: Every tool call of a step writes one line to the Job log -The agent of a step SHALL write one line to the standard error stream for each tool call, when the call ends. The line SHALL hold the name of the tool, the program of the `command` argument when the tool has one, and the outcome: `ok`, `refused`, `retry` or `failed`. The program SHALL be the first word of the command when it is a program of the allowlist or a program of `IMPLEMENT_SHELL_REPLACEMENTS`, else the word `other`. Before a call that has a `command` runs, the agent SHALL write the line `Tool call: , started: `. The command SHALL be the first word and the words after it, at most `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS` words, with the value of each `name=value` word that is not a number and each word with a space masked, other secrets masked, control characters escaped, and cut to `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS` characters. When the first word is not a known program, the command SHALL be the word `other`. No line SHALL hold a path or a content of a call that has no `command`, or any output. +The agent of a step SHALL write one line to the standard error stream for each tool call, when it ends. The line SHALL hold the name of the tool, the program of the `command` argument when the tool has one, and the outcome: `ok`, `refused`, `retry` or `failed`. The program SHALL be the first word of the command when it is a program of the allowlist or of `IMPLEMENT_SHELL_REPLACEMENTS`, else the word `other`. The line SHALL hold nothing else. + +#### Scenario: A program of the allowlist +- **WHEN** the model calls a tool with the command `git status` +- **THEN** the line holds "program git" + +#### Scenario: A call that returns +- **WHEN** the model calls `write_file` with a path and a content, and then ends its run +- **THEN** the standard error stream holds the line "Tool call: write_file, ok." and holds neither the path nor the content + +#### Scenario: A call that fails validation +- **WHEN** the model calls `read_file` without its `path` argument +- **THEN** the standard error stream holds the line "Tool call: read_file, retry." + +#### Scenario: A short bare word that is no known program +- **WHEN** the first word of a shell command is a short bare word such as `hunter2password` that the model read from a file +- **THEN** the line and the reason of a stopped run hold "other" and not the word + +#### Scenario: A refused path +- **WHEN** the model calls `read_file` with a path outside the root +- **THEN** the standard error stream holds the line "Tool call: read_file, retry." + +#### Scenario: A call that the tool reports as failed +- **WHEN** a tool reports a failed call +- **THEN** the standard error stream holds the line "Tool call: , failed." + +## ADDED Requirements + +### Requirement: A call with a command writes the command to the Job log before it runs +Before a call that has a `command` runs, the agent SHALL write the line `Tool call: , started: `. The command SHALL be the first word and at most `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS` words, escaped and cut to `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS` characters. The line SHALL hide each secret, the value of each `name=value` word that is not a number, and each word with a space. When the first word is no known program, the command SHALL be `other`. #### Scenario: A refused program - **WHEN** the model calls the shell tool with `pytest tests/test_sample.py`, and then ends its run - **THEN** the standard error stream holds the lines "Tool call: shell, started: pytest tests/test_sample.py" and "Tool call: shell, program pytest, refused." -#### Scenario: A program of the allowlist -- **WHEN** the model calls a tool with the command `git status` -- **THEN** the lines hold "started: git status" and "program git" - #### Scenario: The line comes before the call - **WHEN** the model calls the shell tool with `uv run pytest -n 48`, and the tool is still running - **THEN** the standard error stream holds the line "Tool call: shell, started: uv run pytest -n 48" and no line with an outcome @@ -37,32 +62,10 @@ The agent of a step SHALL write one line to the standard error stream for each t - **WHEN** an argument holds an escape sequence or another control character that is no space - **THEN** the line is one line, and it holds the escaped form of the character -#### Scenario: A call that returns -- **WHEN** the model calls `write_file` with a path and a content, and then ends its run -- **THEN** the standard error stream holds the line "Tool call: write_file, ok." and holds neither the path nor the content - -#### Scenario: A call that fails validation -- **WHEN** the model calls `read_file` without its `path` argument -- **THEN** the standard error stream holds the line "Tool call: read_file, retry." - #### Scenario: A first word that is no program - **WHEN** the first word of a shell command is an assignment such as `API_KEY=hunter2`, a path, a word with a space or a quote, an escape sequence, or the command has an unclosed quote - **THEN** the lines hold "started: other" and "program other" and hold no part of the command -#### Scenario: A short bare word that is no known program -- **WHEN** the first word of a shell command is a short bare word such as `hunter2password` that the model read from a file -- **THEN** the lines and the reason of a stopped run hold "other" and not the word - -#### Scenario: A refused path -- **WHEN** the model calls `read_file` with a path outside the root -- **THEN** the standard error stream holds the line "Tool call: read_file, retry." - -#### Scenario: A call that the tool reports as failed -- **WHEN** a tool reports a failed call -- **THEN** the standard error stream holds the line "Tool call: , failed." - -## ADDED Requirements - ### Requirement: The shell of a step takes the worker bound of the process The shell of a step SHALL get `PYTEST_XDIST_AUTO_NUM_WORKERS` with the value of the process when the process has it, and SHALL not set it otherwise. diff --git a/openspec/changes/2806-runner-memory-and-command-log/specs/subprocess-environment/spec.md b/openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/specs/subprocess-environment/spec.md similarity index 100% rename from openspec/changes/2806-runner-memory-and-command-log/specs/subprocess-environment/spec.md rename to openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/specs/subprocess-environment/spec.md diff --git a/openspec/changes/2806-runner-memory-and-command-log/tasks.md b/openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/tasks.md similarity index 100% rename from openspec/changes/2806-runner-memory-and-command-log/tasks.md rename to openspec/changes/archive/2026-10-30-2806-runner-memory-and-command-log/tasks.md diff --git a/openspec/specs/roadmap-implement-job/spec.md b/openspec/specs/roadmap-implement-job/spec.md index 1bc66fcf54..1200c4da47 100644 --- a/openspec/specs/roadmap-implement-job/spec.md +++ b/openspec/specs/roadmap-implement-job/spec.md @@ -210,7 +210,7 @@ When a reported Job leaves its item neither In Review nor stopped, the round SHA - **THEN** the item gets a comment with the state `failed` and the tail of the log, `implement.job_state` is `failed`, the Status is Ready, `implement.stopped` is `job`, and the next round creates no Job for the item ### Requirement: A runner process cannot be read by its own shell -Before the first step, the job in a runner SHALL clear the dumpable flag of its own process with `prctl(PR_SET_DUMPABLE, 0)`. A child of the job SHALL then not read `/proc//environ` of the job. A call that the kernel refuses SHALL make `apply_implement` raise `RoadmapImplementError`, and no step SHALL run. The step of the agent SHALL get none of the variables of the job, except the paths `UV_CACHE_DIR` and `UV_PYTHON` of uv. +Before the first step, the job in a runner SHALL clear the dumpable flag of its own process with `prctl(PR_SET_DUMPABLE, 0)`, so that no child reads `/proc//environ` of the job. A call that the kernel refuses SHALL make `apply_implement` raise `RoadmapImplementError`, and no step SHALL run. The step of the agent SHALL get none of the variables of the job, except `UV_CACHE_DIR`, `UV_PYTHON` and `PYTEST_XDIST_AUTO_NUM_WORKERS`. #### Scenario: A child reads the environment of its parent - **WHEN** a process sets the flag, holds a variable in its starting environment, and starts a child that opens `/proc//environ` diff --git a/openspec/specs/roadmap-implement-runner/spec.md b/openspec/specs/roadmap-implement-runner/spec.md index 40f8a255c7..e1c1a080e7 100644 --- a/openspec/specs/roadmap-implement-runner/spec.md +++ b/openspec/specs/roadmap-implement-runner/spec.md @@ -42,12 +42,16 @@ The `runner` stage SHALL delete npm, pip and the uv cache of root, because a Job - **THEN** a job builds `target: runner` with `push: false` and `load: true`, and each of its build steps runs only if the image content changed ### Requirement: A suspended CronJob is the template of the runner Job -CronJob `devops-cli-runner` in namespace `devops` SHALL be suspended and SHALL never run on a schedule. Its Job template SHALL name the image `ghcr.io/dan-petty/devops-cli/runner` with no tag, request and limit 2 CPU and 4 Gi, request 2 Gi and limit 6 Gi of `ephemeral-storage`, set `activeDeadlineSeconds` to 7200 and `backoffLimit` to 0, and use the `securityContext` of CronJob `devops-cli`. Its pod SHALL use ServiceAccount `devops-cli`, which mounts no token. +CronJob `devops-cli-runner` in namespace `devops` SHALL be suspended and SHALL never run on a schedule. Its Job template SHALL name the image `ghcr.io/dan-petty/devops-cli/runner` with no tag, request and limit 2 CPU, request 4 Gi and limit 8 Gi of memory, request 2 Gi and limit 6 Gi of `ephemeral-storage`, set `activeDeadlineSeconds` to 7200 and `backoffLimit` to 0, and use the `securityContext` of CronJob `devops-cli`. Its pod SHALL use ServiceAccount `devops-cli`, which mounts no token. #### Scenario: The manifest is read - **WHEN** a test reads the rendered `k8s/devops` kustomization - **THEN** CronJob `devops-cli-runner` holds the values above, its container is named `runner`, its pod mounts no ServiceAccount token, its root filesystem is read-only, and its capabilities drop `ALL` +#### Scenario: The admission policy +- **WHEN** a test runs the expressions of policy `roadmap-service-jobs` against the Job that the template makes +- **THEN** no expression refuses it + ### Requirement: The runner Job knows it is a runner and holds a home volume The container of CronJob `devops-cli-runner` SHALL set `DEVOPS_CLI_ROADMAP_IMPLEMENT_IN_RUNNER` to `true`, take Secret `devops-cli` through `envFrom`, mount ConfigMap `devops-cli-config`, and mount an `emptyDir` of 4 Gi as its home and an `emptyDir` of 1 Gi as `/tmp`. The other CronJob SHALL not set that variable. The `ephemeral-storage` limit SHALL cover both volumes. @@ -148,3 +152,10 @@ The policy SHALL refuse a Job unless it sets `backoffLimit: 0` and an `activeDea #### Scenario: A Job that runs too long or retries - **WHEN** the Job from the template sets a `backoffLimit` above 0, an `activeDeadlineSeconds` one above the template's, or no `activeDeadlineSeconds` - **THEN** the policy refuses the Job + +### Requirement: The runner Job bounds the workers of the test runner to its CPU limit +The container of CronJob `devops-cli-runner` SHALL set `PYTEST_XDIST_AUTO_NUM_WORKERS` to the number of its CPU limit. `pytest-xdist` counts the CPUs of the node, not the CPU limit of the pod, so without the variable a test run starts one worker for each CPU of the node. + +#### Scenario: The variable +- **WHEN** a test reads the rendered `k8s/devops` kustomization +- **THEN** the variable of the runner container equals its CPU limit diff --git a/openspec/specs/roadmap-implement-step/spec.md b/openspec/specs/roadmap-implement-step/spec.md index aae626c7a1..e84a6e153e 100644 --- a/openspec/specs/roadmap-implement-step/spec.md +++ b/openspec/specs/roadmap-implement-step/spec.md @@ -304,11 +304,7 @@ A step that stops on a pydantic-ai error SHALL count the tool calls that a tool - **THEN** the reason holds the message of the error and holds neither count ### Requirement: Every tool call of a step writes one line to the Job log -The agent of a step SHALL write one line to the standard error stream for each tool call. The line SHALL hold the name of the tool, the program of the `command` argument when the tool has one, and the outcome: `ok`, `refused`, `retry` or `failed`. The program SHALL be the first word of the command when it is a program of the allowlist or a program of `IMPLEMENT_SHELL_REPLACEMENTS`, else the word `other`. The line SHALL hold nothing else. - -#### Scenario: A refused program -- **WHEN** the model calls the shell tool with `pytest tests/test_sample.py --secret-flag=abc`, and then ends its run -- **THEN** the standard error stream holds the line "Tool call: shell, program pytest, refused." and holds no text of the arguments +The agent of a step SHALL write one line to the standard error stream for each tool call, when it ends. The line SHALL hold the name of the tool, the program of the `command` argument when the tool has one, and the outcome: `ok`, `refused`, `retry` or `failed`. The program SHALL be the first word of the command when it is a program of the allowlist or of `IMPLEMENT_SHELL_REPLACEMENTS`, else the word `other`. The line SHALL hold nothing else. #### Scenario: A program of the allowlist - **WHEN** the model calls a tool with the command `git status` @@ -322,10 +318,6 @@ The agent of a step SHALL write one line to the standard error stream for each t - **WHEN** the model calls `read_file` without its `path` argument - **THEN** the standard error stream holds the line "Tool call: read_file, retry." -#### Scenario: A first word that is no program -- **WHEN** the first word of a shell command is an assignment such as `API_KEY=hunter2`, a path, a word with a space or a quote, an escape sequence, or the command has an unclosed quote -- **THEN** the line holds "program other" and holds no part of the word - #### Scenario: A short bare word that is no known program - **WHEN** the first word of a shell command is a short bare word such as `hunter2password` that the model read from a file - **THEN** the line and the reason of a stopped run hold "other" and not the word @@ -338,6 +330,41 @@ The agent of a step SHALL write one line to the standard error stream for each t - **WHEN** a tool reports a failed call - **THEN** the standard error stream holds the line "Tool call: , failed." +### Requirement: A call with a command writes the command to the Job log before it runs +Before a call that has a `command` runs, the agent SHALL write the line `Tool call: , started: `. The command SHALL be the first word and at most `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS` words, escaped and cut to `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS` characters. The line SHALL hide each secret, the value of each `name=value` word that is not a number, and each word with a space. When the first word is no known program, the command SHALL be `other`. + +#### Scenario: A refused program +- **WHEN** the model calls the shell tool with `pytest tests/test_sample.py`, and then ends its run +- **THEN** the standard error stream holds the lines "Tool call: shell, started: pytest tests/test_sample.py" and "Tool call: shell, program pytest, refused." + +#### Scenario: The line comes before the call +- **WHEN** the model calls the shell tool with `uv run pytest -n 48`, and the tool is still running +- **THEN** the standard error stream holds the line "Tool call: shell, started: uv run pytest -n 48" and no line with an outcome + +#### Scenario: A long command +- **WHEN** the command has more words than `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_WORDS`, or more characters than `CONST_ROADMAP_IMPLEMENT_LOG_COMMAND_CHARS` +- **THEN** the line holds the first words, cut, and ends with " ..." + +#### Scenario: A secret in an argument +- **WHEN** the command is `git remote add origin https://user:ghp_@example.com/x.git`, with a GitHub token in place of `` +- **THEN** the line holds no part of the token + +#### Scenario: A value after a name +- **WHEN** an argument has the form `name=value` and the value is not a number, for example `ai.api_key=` or `http.extraheader=AUTHORIZATION: basic ` +- **THEN** the line holds the name and the word `` in place of the value, and an argument with a number as the value, such as `--numprocesses=48`, stays as it is + +#### Scenario: Free text in an argument +- **WHEN** an argument holds a space, as the message of a commit does +- **THEN** the line holds the word `` in place of the argument + +#### Scenario: A control character in an argument +- **WHEN** an argument holds an escape sequence or another control character that is no space +- **THEN** the line is one line, and it holds the escaped form of the character + +#### Scenario: A first word that is no program +- **WHEN** the first word of a shell command is an assignment such as `API_KEY=hunter2`, a path, a word with a space or a quote, an escape sequence, or the command has an unclosed quote +- **THEN** the lines hold "started: other" and "program other" and hold no part of the command + ### Requirement: The table of a stopped step shows the reason as text The table of `devops roadmap implement` SHALL print the reason and the last message as text. A bracket in either SHALL NOT be read as markup, and SHALL NOT raise an error. @@ -564,3 +591,14 @@ The turn for a failed static check SHALL change no file except `tasks.md` and th #### Scenario: The turn changes a file that the step changed - **WHEN** the model changes `src/sample.py` in the extra turn, and the step had changed it - **THEN** the step checks all exit checks again and does not stop for the change + +### Requirement: The shell of a step takes the worker bound of the process +The shell of a step SHALL get `PYTEST_XDIST_AUTO_NUM_WORKERS` with the value of the process when the process has it, and SHALL not set it otherwise. + +#### Scenario: The process has the variable +- **WHEN** the process sets `PYTEST_XDIST_AUTO_NUM_WORKERS` to `2` +- **THEN** the environment of the shell holds the same value + +#### Scenario: The process has no variable +- **WHEN** the process does not set it +- **THEN** the environment of the shell does not hold it diff --git a/openspec/specs/subprocess-environment/spec.md b/openspec/specs/subprocess-environment/spec.md index 13f35676a6..eea8e0b9ef 100644 --- a/openspec/specs/subprocess-environment/spec.md +++ b/openspec/specs/subprocess-environment/spec.md @@ -349,3 +349,10 @@ With isolation on, `build_subprocess_env` SHALL keep `SSLKEYLOGFILE`, `QLOGDIR`, #### Scenario: Keys with a similar name - **WHEN** a caller builds a child environment with the overrides `SSL_CERT_FILE`, `NODE_EXTRA_CA_CERTS`, `EXAMPLE_SSLKEYLOGFILE`, `QLOGDIR_EXAMPLE`, `BUILD_ID` and `OLD_LD_EXAMPLE` - **THEN** the child environment holds each of these keys with its value + +### Requirement: An isolated child gets the worker bound of the test runner +With isolation on, `build_subprocess_env` SHALL keep `PYTEST_XDIST_AUTO_NUM_WORKERS` in the child environment when the process has it. `pytest-xdist` counts the CPUs of the node, not of the pod, so a child that runs `pytest`, such as the gate of `devops ci`, needs the bound that the runner pod sets. + +#### Scenario: The process has the variable +- **WHEN** the process sets `PYTEST_XDIST_AUTO_NUM_WORKERS` to `2` and a caller builds an isolated child environment +- **THEN** the child environment holds `PYTEST_XDIST_AUTO_NUM_WORKERS` with the value `2`