diff --git a/docs/adr/0006-github-session-requests-go-through-gidgethub.md b/docs/adr/0006-github-session-requests-go-through-gidgethub.md index cdfe44075f..089a349faa 100644 --- a/docs/adr/0006-github-session-requests-go-through-gidgethub.md +++ b/docs/adr/0006-github-session-requests-go-through-gidgethub.md @@ -9,7 +9,7 @@ The process's GitHub session (#767) sends its own REST requests through gidgethu - **Retries.** gidgethub's `handle_rate_limit_error` hook retries a rate limit (a 403 with no quota left, a 429, or a 403 with `retry-after`) up to `DEFAULT_GH_MAX_RETRIES` times, waiting what `run_gh` would: the Retry-After, else until the quota resets, else jittered backoff from the secondary-limit floor. A 5xx is retried only for a read, from `DEFAULT_GH_SERVER_ERROR_RETRY_FLOOR_SECONDS`, since GitHub may have applied a write it failed to answer. The session's `_request` sends a GET again when its connection is lost before its answer is read. The errors are `httpx2.RemoteProtocolError`, `httpx2.ReadError` and `httpx2.WriteError`. It sends the GET at most `DEFAULT_GH_MAX_RETRIES` more times, after the same ledger wait. It does not send a lost write again. Each gidgethub attempt keeps its own budget, so one GET sends at most nine requests (#3506). The session does not retry a refused connect, a connect or read timeout, or a refused origin. - **Errors.** `github/error_classifier.py` maps gidgethub's exceptions by type, status and headers, never by message text, onto `GitHubUnauthenticatedError` (401), `GitHubScopeError` (a 403 whose `x-accepted-oauth-scopes` the token holds none of), `GitHubRateLimitError`, `GitHubNotFoundError` (404) and `GitHubUnreadError` (no readable answer, an answer that does not decode, or a request a close stopped). Anything else is a plain `GitHubOperationError`. Each carries the status, as an int, and the request path. Only a `DevOpsCLIError` leaves `rest()`: one of these, or one raised on the way, such as the egress check's `SSRFBlockedError`, unchanged. - **Pagination.** `paginate(path, *, iterable_key=None)` reads a REST listing one page per portal call, as its consumer asks for items, and follows the `rel="next"` link gidgethub reads from each page's `Link` header, whether it names a page number or a cursor. Every page passes through the same pacing, retries, origin hook and error classes as `rest()`. It does not use gidgethub's `getiter`, which iterates whatever a page decodes to: a string's characters, or an object's keys when its key is missing. A page must be a JSON array, or an object holding one under `iterable_key`. Anything else raises `GitHubUnreadError` naming the endpoint and the page, so a listing never ends short without saying so (#1034's rule). An empty array, or a page without a next link, ends the listing. A listing still linking a next page after `DEFAULT_GH_MAX_PAGINATED_PAGES` pages, the cap every other paginated reader keeps, raises `GitHubUnreadError` naming the endpoint and the cap. -- **Conditional requests.** gidgethub's `cache=` holds each GET's answer with its ETag in a `cachetools.LRUCache` of `DEFAULT_GH_SESSION_ETAG_CACHE_SIZE` answers, in memory, built by each session's transport, so one identity's ETags are never sent as another's and a close drops them. The next GET of that URL carries `If-None-Match`, and a 304 gives back the stored answer as a copy, so no caller changes what a later 304 returns. Every attempt, a 304 too, is paced and charged, and the ledger takes the quota the 304 reports, which GitHub leaves unspent. A stored page passes the same page check as a fresh one. GitHub's ETag covers a page's body only and its 304 carries no `Link` header (checked 2026-10-19), so a full last page that gains a next page keeps its ETag. A page that links no next page is therefore read in full and not kept, which leaves the store to the pages that can answer 304. +- **Conditional requests.** gidgethub's `cache=` holds each GET's answer with its ETag in a `cachetools.LRUCache` of at most `DEFAULT_GH_SESSION_ETAG_CACHE_SIZE` answers and `DEFAULT_GH_SESSION_ETAG_CACHE_BYTES` bytes, in memory (#4116: a diff has no size bound, so the count alone did not bound the memory; an answer above the whole byte budget is returned and not stored), built by each session's transport, so one identity's ETags are never sent as another's and a close drops them. The next GET of that URL carries `If-None-Match`, and a 304 gives back the stored answer as a copy, so no caller changes what a later 304 returns. Every attempt, a 304 too, is paced and charged, and the ledger takes the quota the 304 reports, which GitHub leaves unspent. A stored page passes the same page check as a fresh one. GitHub's ETag covers a page's body only and its 304 carries no `Link` header (checked 2026-10-19), so a full last page that gains a next page keeps its ETag. A page that links no next page is therefore read in full and not kept, which leaves the store to the pages that can answer 304. - **Identity.** The requests carry `CONST_GITHUB_USER_AGENT` and `CONST_GITHUB_API_VERSION`. They never carry the login or an email. ## Considered Options diff --git a/k8s/README.md b/k8s/README.md index ade755df33..b7c41b50f1 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -504,7 +504,7 @@ Alertmanager runs from the prometheus chart (`alertmanager` in `monitoring/prome | `ResearchCriticalFindings` | The last `devops research sweep` of the last 7 days found a critical advisory that affects a pin of the project (#3899). The sweep sets zero for a severity with no finding, so a clean sweep ends the alert. A sweep with a lookup that got no answer sets no value | — | critical | Read the candidates that the sweep filed, or run `devops research advisories`, and update the pin. Run the sweep again. | | `RoadmapServiceIdentityRefused`, `RoadmapServiceGitHubThrottled` | GitHub refused the identity of the roadmap Service, or throttled its requests; see Roadmap service, Alerts | — | critical | | `RoadmapServiceJobsFailing` | All jobs of one row of a repository failed in 1 hour | 30m | warning | -| `RoadmapServiceLaneStalled`, `RoadmapServiceRestarted`, `RoadmapServiceUnavailable`, `RoadmapServiceGitHubRequestsHigh`, `RoadmapServiceModelRequestsHigh`, `RoadmapServiceStateUnkept` | The roadmap Service stalls, its pod restarts or is unavailable, its GitHub or model requests in an hour are high, or it could not write a state record; see Roadmap service, Alerts | 0–15m | warning | +| `RoadmapServiceLaneStalled`, `RoadmapServiceRestarted`, `RoadmapServiceMemoryNearLimit`, `RoadmapServiceUnavailable`, `RoadmapServiceGitHubRequestsHigh`, `RoadmapServiceModelRequestsHigh`, `RoadmapServiceStateUnkept` | The roadmap Service stalls, its pod restarts, uses almost all of its memory limit or is unavailable, its GitHub or model requests in an hour are high, or it could not write a state record; see Roadmap service, Alerts | 0–15m | warning | | `RoadmapServiceWebhooksRejected` | The webhook route of the roadmap Service rejected more than 20 deliveries in 15 minutes; see Roadmap service, Alerts | — | warning | | `ClusterMetricsMissing` | `kube_node_status_condition` is absent, so the node rules cannot fire | 10m | critical | | `PrometheusConfigReloadFailed`, `PrometheusRuleEvaluationFailures`, `PrometheusNotConnectedToAlertmanager`, `PrometheusDroppingAlerts`, `PrometheusCompactionsFailing` | Prometheus's own health | 0–15m | warning | @@ -736,6 +736,7 @@ The rule group `roadmap-service` in `monitoring/prometheus-values.yaml` watches | `RoadmapServiceJobsFailing` | All jobs of one row of a repository failed in 1 hour (increase in errors is greater than zero, and increase in successes is zero). A success of another row of the lane does not clear the alert. | 30m | warning | Read the errors of that repository in the Service log: `kubectl -n devops logs deployment/roadmap-service`. The log line of a failed round names its rows. Repair the cause, for example the repository's `.github/roadmap.toml`. | | `RoadmapServiceLaneStalled` | No job of a repository and lane started in 2 hours while the deployment has an available replica. In a new pod, the 2 hours start when the worker of the lane starts. | 10m | warning | Find in the Service log a pause of the rounds, a spent request budget, or a job that does not end. If a job does not end, restart the deployment. | | `RoadmapServiceRestarted` | The `service` container restarted in the last hour | — | warning | Read the log before the restart: `kubectl -n devops logs deployment/roadmap-service --previous`. | +| `RoadmapServiceMemoryNearLimit` | The working set of the `service` container is above 85% of its memory limit for 10 minutes (#4116). The kernel kills the container at 100%, and `RoadmapServiceRestarted` fires only after that. | 10m | warning | Read the working set: `kubectl -n devops top pod`. Search the Service log for `The OTel export queue is full`: it shows a collector that does not answer, and the tracer drops payloads then. Then read the Service log for the rounds of the last hours. A rise of the limit only delays the kill. | | `RoadmapServiceUnavailable` | The deployment has an unavailable replica. A rollout stops the old pod before it starts the new one, so the rule waits 10 minutes. | 10m | warning | Read the events: `kubectl -n devops describe deployment/roadmap-service` and `kubectl -n devops get events --sort-by=.lastTimestamp`. | | `RoadmapServiceGitHubRequestsHigh` | The Service sent more GitHub requests in 1 hour, not counting answers with status 304, than 90% of the budget it reports in `devops_cli_service_budget_limit_requests` (`service.github_requests_per_hour`, 500 by default) | — | warning | Set the variable `Job` of the `devops-cli Telemetry` dashboard to `roadmap-service`, read the GitHub Requests by Resource panel, and find the repository in the Service log. If the requests are expected, raise the budget with `devops config set service.github_requests_per_hour `. Otherwise, remove the repository from `service.repos`. Then run `devops k8s deploy-stack --stack devops`. | | `RoadmapServiceModelRequestsHigh` | The Service sent more than 352 model requests in 1 hour. A request that the cache answered does not count. | — | warning | Find the model on the `AI Spend & LLM Usage Telemetry` dashboard, and the repository in the Service log. Remove the repository from `service.repos` until the cause is known, then run `devops k8s deploy-stack --stack devops`. | diff --git a/k8s/monitoring/prometheus-values.yaml b/k8s/monitoring/prometheus-values.yaml index dd0888ea5c..4c3d93aafc 100644 --- a/k8s/monitoring/prometheus-values.yaml +++ b/k8s/monitoring/prometheus-values.yaml @@ -744,6 +744,21 @@ serverFiles: annotations: summary: "The roadmap Service container in {{ $labels.pod }} restarted" description: 'The restart count of container {{ $labels.container }} of pod {{ $labels.namespace }}/{{ $labels.pod }} increased by {{ printf "%.0f" $value }} in the last hour (k8s/README.md, Roadmap service).' + # The kernel kills the container at its memory limit, and RoadmapServiceRestarted fires + # only after that. The working set grew 100 to 150 MiB each hour before the kill (#4116). + # The two series come from the kubelet and kube-state-metrics, so max by drops their + # other labels and the division matches on namespace and pod. + - alert: RoadmapServiceMemoryNearLimit + expr: >- + max by (namespace, pod) (container_memory_working_set_bytes{namespace="devops", pod=~"roadmap-service-.+", container="service"}) + / max by (namespace, pod) (kube_pod_container_resource_limits{namespace="devops", pod=~"roadmap-service-.+", container="service", resource="memory"}) + > 0.85 + for: 10m + labels: + severity: warning + annotations: + summary: 'The roadmap Service container in {{ $labels.pod }} uses {{ $value | humanizePercentage }} of its memory limit' + description: 'The working set of container service of pod {{ $labels.namespace }}/{{ $labels.pod }} has been above 85% of its memory limit for 10 minutes, and the kernel kills the container at 100% (k8s/README.md, Roadmap service).' # The Recreate strategy stops the old pod before it starts the new one, so a rollout # has no available replica for a few minutes. - alert: RoadmapServiceUnavailable diff --git a/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/.openspec.yaml b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/.openspec.yaml new file mode 100644 index 0000000000..c0ad5ed4dd --- /dev/null +++ b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-08 diff --git a/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/design.md b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/design.md new file mode 100644 index 0000000000..b346ca2844 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/design.md @@ -0,0 +1,19 @@ +# Design + +## Context + +The Service runs one worker for each lane of each repository in one process. They share the one GitHub session (`get_github_session`) and the one tracer. The session stores GET answers in an `LRUCache` for its next conditional GET. The tracer sends each payload to two export threads. + +## Decisions + +- **The session store is bounded by bytes and by count.** `LRUCache(maxsize=DEFAULT_GH_SESSION_ETAG_CACHE_BYTES, getsizeof=)`, with the count bound kept. The size of an answer is the length of its text or bytes body, or of its encoded JSON for a decoded value. The size is counted once, when the answer is stored. An answer above the whole budget is returned and not stored, because `LRUCache` raises `ValueError` for it. The default budget is 64 MiB, a quarter of the memory request of the container. +- **The export queue is capped with a semaphore.** `_send_payload` takes a slot before it submits a payload, and the done callback of the future gives it back. When no slot is free, the payload is dropped and `export_dropped` grows by one. A drop is a counter and one warning log line at the first drop, and it is no error, because telemetry must not stop a command. +- **The alert reads cAdvisor and kube-state-metrics.** The expression is the one of the issue. It divides the working set by the limit for the container `service` of the pods of the roadmap Service, and it waits 10 minutes. +- **The test measures the heap with `MemoryProfiler`.** It compares the heap after round 10 with the heap after round 200 and names the allocation sites that grew. + +## Rejected Alternatives + +- **Raise the memory limit.** A rise of 100 to 150 MiB each hour reaches any limit. Rejected by the issue and by measure 1: the store has no bound by bytes. +- **Set `MALLOC_ARENA_MAX=2` in the Deployment.** Measure 4 kept the resident set flat with no setting, and it was higher with the setting. The change adds it only if a later measure of the pod shows fragmentation. +- **Drop the oldest payload when the export queue is full.** `ThreadPoolExecutor` has no API to remove a queued item, so this needs a home-grown queue. Dropping the newest payload needs one semaphore. +- **`pytest-memray`.** It bounds the peak of a test and does not compare two rounds. diff --git a/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/proposal.md b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/proposal.md new file mode 100644 index 0000000000..2fc2875d31 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/proposal.md @@ -0,0 +1,55 @@ +# Proposal + +## Why + +The pod of the roadmap Service was OOMKilled at its 1 GiB memory limit after 2 h 39 min (#4116). Its working set rises 100 to 150 MiB each hour from 370 to 460 MiB. Two structures of the Service have a bound by count and none by bytes: the GitHub session keeps 64 GET answers, and the tracer queues export payloads with no cap. No alert warns before the kill, because `RoadmapServiceRestarted` fires after it. + +## What Changes + +- Bound the answers that the GitHub session stores by bytes, with `DEFAULT_GH_SESSION_ETAG_CACHE_BYTES`, beside the count of `DEFAULT_GH_SESSION_ETAG_CACHE_SIZE`. An answer larger than the whole budget is returned and not stored. +- Cap the payloads that wait for export in the tracer with `DEFAULT_OTEL_EXPORT_QUEUE_MAX_PAYLOADS`, drop the payloads past the cap and count them in `export_dropped`. +- Add the alert `RoadmapServiceMemoryNearLimit` to the `roadmap-service` group of `k8s/monitoring/prometheus-values.yaml`: the working set of container `service` above 85% of its memory limit for 10 minutes. Add its step to the Roadmap service section of `k8s/README.md` and to the Alerting table. +- Add `tests/server/test_service_memory.py`, which runs the status lane's round 200 times over the real worker, session and tracer with the fakes of GitHub and of the collector, and measures the heap with `MemoryProfiler`. +- Record the byte budget in `docs/adr/0006-github-session-requests-go-through-gidgethub.md`. +- The change adds no Settings key and removes, renames or tightens none. The two new bounds are constants in `src/devops_cli/config/defaults.py`, so the example ConfigMap and the live ConfigMap load as before. +- The change does not raise the memory limit and does not set `MALLOC_ARENA_MAX`: the measure below does not prove an allocator cause. +- The change carries a spec delta, because the session, the exporter and the alerts are observable behavior. +- The change fits one pull request. + +## Capabilities + +### New Capabilities + +- `github-session-answers`: The byte budget of the answers the GitHub session stores + +### Modified Capabilities + +- `otlp-export`: The export queue is bounded and counts its drops +- `roadmap-service-alerts`: The memory alert + +## Impact + +- Code: `src/devops_cli/github/session_transport.py`, `src/devops_cli/telemetry/tracer.py`, `src/devops_cli/config/defaults.py` +- Manifests: `k8s/monitoring/prometheus-values.yaml` +- Documents: `k8s/README.md`, `docs/adr/0006-github-session-requests-go-through-gidgethub.md` +- Tests: `tests/server/test_service_memory.py`, `tests/github/test_github_session.py`, `tests/telemetry/test_export_queue.py`, `tests/prometheus/test_k8s_monitoring_alerting.py`, `tests/fixtures/prometheus_rules/roadmap_service_tests.yaml` + +## Feasibility + +- Live pod, read only, 2026-11-08: `kubectl top` showed 666 MiB at 04:26Z and 675 MiB at 04:32Z for a pod that started at 04:09Z with no restart. `/proc/1/status` showed RssAnon 667 MiB and RssFile 35 MiB, and the cgroup `memory.stat` showed anon 656 MiB and file 11 MiB. So the growth is process heap, and not page cache or git clones. +- Code read: `src/devops_cli/github/session_transport.py` builds `LRUCache(maxsize=DEFAULT_GH_SESSION_ETAG_CACHE_SIZE)` (64 answers) and `src/devops_cli/telemetry/tracer.py` builds `ContextPropagatingThreadPoolExecutor(max_workers=2)` with no queue cap. +- Measure 1, the session store: `uv run devops ci test tests/server/test_service_memory.py` runs 200 rounds of `RepoWorker` over the real session and tracer, one 1 MiB diff answer of a new URL in each round. On the base tree the heap grew 56.1 MiB between round 10 and round 200, and `gidgethub/sansio.py:64` held 64.00 MB of the allocations: 64 stored answers. The store grows to 64 times the largest answer and has no byte bound. A real page of issues (`state=all`, 100 items) is 793 KB as text and 1.25 MB decoded by `tracemalloc`, so 64 pages are about 80 MB. A pull request diff has no size bound. +- Measure 2, the export queue: `tests/telemetry/test_export_queue.py` blocks the exporter and sends 1000 payloads. On the base tree the collector takes all 1000 once it answers, and the client has no drop counter. So the queue has no bound. +- Measure 3, the rest of a round: the same test with answers of 1 KiB and 1000 rounds grew the heap 10.6 MiB. The largest sites were the span buffer (`tracer.py`, 1000 spans, bounded by count), the fakes' request records and the metric series. No other structure grows with the number of rounds. +- Measure 4, the allocator: a scratch run of 21 threads that parse and drop 8 pages of 100 issues in each round (1000 rounds) kept the resident set flat at 54 to 60 MiB with no `MALLOC_ARENA_MAX`, and 80 to 109 MiB with `MALLOC_ARENA_MAX=2`. This does not show fragmentation, so the change sets no arena limit. The 42 mappings of 64 MiB in the live pod (268 MiB resident) fit glibc arenas, but they also fit the stored answers. +- Open point: the two bounded structures give a plateau, and a plateau of 80 MB cannot alone explain a rise from 370 to 860 MiB. The size of the answers in the live pod is not measured. The fifth acceptance criterion of the issue (a flat working set over 6 hours) is read in Grafana after the roll out, and the pull request comment records it. If the working set still rises, the next step is a heap profile of the pod, and not a higher limit. +- Rollout: the change adds no Settings key. No key that the example ConfigMap or the live ConfigMap names changes. `tests/config` already loads the example ConfigMap into Settings, and group 4 runs it again. +- First checks: `uv run devops ci test tests/server/test_service_memory.py tests/github/test_github_session.py tests/telemetry/test_export_queue.py tests/prometheus/test_k8s_monitoring_alerting.py`, and `uv run devops ci fail-to-pass --base origin/main`. + +## Existing Tool Considered + +`cachetools` is already a dependency. Its `LRUCache` takes `getsizeof` with a `maxsize` in bytes, and it raises `ValueError` for one entry larger than `maxsize`, so the session uses it and adds the guard for an oversized answer. `tracemalloc` and `MemoryProfiler` measure the heap, and the change adds no new library. `concurrent.futures.ThreadPoolExecutor` has no queue cap, so the tracer counts the payloads that wait with a semaphore of the standard library. kube-state-metrics and cAdvisor already give `kube_pod_container_resource_limits` and `container_memory_working_set_bytes`, and the chart keeps both. `pytest-memray` was compared and rejected: it bounds the peak of one test, and it does not compare the heap at two rounds. The change deletes no internal code. + +## Dependencies + +None. diff --git a/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/specs/github-session-answers/spec.md b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/specs/github-session-answers/spec.md new file mode 100644 index 0000000000..7593d64eda --- /dev/null +++ b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/specs/github-session-answers/spec.md @@ -0,0 +1,23 @@ +## Purpose +The answers that the GitHub session stores for its next conditional GET, and the bound on their size in bytes, so the memory of a long-running process that shares one session does not grow with the answers it read. + +## ADDED Requirements + +### Requirement: Session answers are bounded by bytes +The GitHub session SHALL keep its stored GET answers within `DEFAULT_GH_SESSION_ETAG_CACHE_BYTES` bytes and `DEFAULT_GH_SESSION_ETAG_CACHE_SIZE` answers. When a new answer passes a bound, the answers read longest ago SHALL be dropped. + +#### Scenario: The stored answers pass the byte budget +- **WHEN** the session reads eight answers of 300 KiB, with the byte budget at 1 MiB +- **THEN** the stored answers hold at most 1 MiB in total, and the next GET of the first URL carries no `If-None-Match` +- **AND** the next GET of the last URL carries the ETag of its answer. + +#### Scenario: The heap after many rounds +- **WHEN** the status lane's round runs 200 times and each round reads one answer of a new URL +- **THEN** the heap after round 200 holds at most the slack of the rest of the process more than the heap after round 10. + +### Requirement: An oversized answer is not stored +The session MUST return an answer that is larger than the whole byte budget, and MUST NOT store it. + +#### Scenario: One answer is larger than the budget +- **WHEN** a GET returns an answer of 512 KiB, with the byte budget at 256 KiB +- **THEN** the call returns the whole answer with no error, and the next GET of that URL carries no `If-None-Match`. diff --git a/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/specs/otlp-export/spec.md b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/specs/otlp-export/spec.md new file mode 100644 index 0000000000..1985e4fbc4 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/specs/otlp-export/spec.md @@ -0,0 +1,8 @@ +## ADDED Requirements + +### Requirement: The export queue is bounded +The tracer SHALL keep at most `DEFAULT_OTEL_EXPORT_QUEUE_MAX_PAYLOADS` payloads that wait for export or are in export, and SHALL count each payload that it drops in `export_dropped`. + +#### Scenario: A collector that does not answer +- **WHEN** the exporter blocks and the tracer sends 1000 payloads, with the cap at 16 +- **THEN** the collector takes 16 payloads once it answers, and `export_dropped` is 984. diff --git a/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/specs/roadmap-service-alerts/spec.md b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/specs/roadmap-service-alerts/spec.md new file mode 100644 index 0000000000..4b4ec12200 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/specs/roadmap-service-alerts/spec.md @@ -0,0 +1,12 @@ +## ADDED Requirements + +### Requirement: The memory alert warns before the limit +The rule group `roadmap-service` SHALL hold the warning alert `RoadmapServiceMemoryNearLimit`. It SHALL fire after 10 minutes when the working set of container `service` of a pod `roadmap-service-.+` in namespace `devops` is above 85% of the memory limit of that container. Its description SHALL end with `(k8s/README.md, Roadmap service)`, and that section SHALL name the alert and say what to do. + +#### Scenario: The working set stays above 85% of the limit +- **WHEN** `promtool test rules` evaluates a working set at 90% of the limit for 20 minutes +- **THEN** `RoadmapServiceMemoryNearLimit` fires with the pod, and it does not fire at the 12th minute, before the wait ends. + +#### Scenario: Another namespace or container +- **WHEN** `promtool test rules` evaluates a working set at 99% of the limit for another container of the pod, or for a pod of another namespace +- **THEN** no alert fires for it. diff --git a/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/tasks.md b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/tasks.md new file mode 100644 index 0000000000..dd7bc20a1f --- /dev/null +++ b/openspec/changes/archive/2026-11-08-4116-roadmap-service-is-oomkilled-after/tasks.md @@ -0,0 +1,44 @@ +# Tasks + +## 1. Bound the answers the GitHub session stores by bytes + +Reads: `src/devops_cli/github/session_transport.py`, `src/devops_cli/config/defaults.py`, `tests/github/test_github_session.py`, `tests/server/test_service_memory.py`. Changes: `src/devops_cli/github/session_transport.py`, `src/devops_cli/config/defaults.py`. + +- [x] 1.1 Add the tests `test_the_session_keeps_the_answers_of_its_latest_reads_within_the_byte_budget` and `test_an_answer_larger_than_the_byte_budget_is_returned_and_not_stored` to `tests/github/test_github_session.py`, and `tests/server/test_service_memory.py`. Run them and see them fail on the base + - Verification: `$ uv run devops ci test tests/github/test_github_session.py tests/server/test_service_memory.py` fails on the base +- [x] 1.2 Add `DEFAULT_GH_SESSION_ETAG_CACHE_BYTES` (64 MiB) to `src/devops_cli/config/defaults.py` with a comment, and make the store of `SessionGitHubAPI` an `LRUCache` with `maxsize` in bytes and `getsizeof` for the size of a stored answer. Keep the count bound. Do not store an answer larger than the budget + - Verification: `$ uv run devops ci test tests/github/test_github_session.py tests/server/test_service_memory.py` passes + +## 2. Cap the export queue of the tracer + +Reads: `src/devops_cli/telemetry/tracer.py`, `src/devops_cli/config/defaults.py`, `tests/telemetry/test_export_queue.py`. Changes: `src/devops_cli/telemetry/tracer.py`, `src/devops_cli/config/defaults.py`. + +- [x] 2.1 Add `tests/telemetry/test_export_queue.py`. Run it and see it fail on the base + - Verification: `$ uv run devops ci test tests/telemetry/test_export_queue.py` fails on the base +- [x] 2.2 Add `DEFAULT_OTEL_EXPORT_QUEUE_MAX_PAYLOADS` (256) to `src/devops_cli/config/defaults.py`. In `OTelTelemetryClient`, take a slot of a semaphore in `_send_payload` before the submit, give it back in the done callback, and count a payload without a free slot in `export_dropped` + - Verification: `$ uv run devops ci test tests/telemetry/test_export_queue.py tests/telemetry/test_telemetry_shutdown_sync.py tests/telemetry/test_telemetry.py` passes + +## 3. Warn before the memory limit + +Reads: `k8s/monitoring/prometheus-values.yaml`, `k8s/README.md`, `tests/prometheus/test_k8s_monitoring_alerting.py`, `tests/fixtures/prometheus_rules/roadmap_service_tests.yaml`. Changes: `k8s/monitoring/prometheus-values.yaml`, `k8s/README.md`. + +- [x] 3.1 Update the expected rules in `tests/prometheus/test_k8s_monitoring_alerting.py` and add the promtool case to `tests/fixtures/prometheus_rules/roadmap_service_tests.yaml`. Run them and see them fail on the base + - Verification: `$ uv run devops ci test tests/prometheus/test_k8s_monitoring_alerting.py` fails on the base +- [x] 3.2 Add the rule `RoadmapServiceMemoryNearLimit` to the `roadmap-service` group after `RoadmapServiceRestarted`, its step in the Roadmap service section of `k8s/README.md` (read the working set with `kubectl -n devops top pod`, search the log for the first drop of a payload, then read the log) and its row in the Alerting table + - Verification: `$ uv run devops ci test tests/prometheus/test_k8s_monitoring_alerting.py` passes + +## 4. Documents and checks + +Reads: `docs/adr/0006-github-session-requests-go-through-gidgethub.md`, `config.example.yaml`. Changes: `docs/adr/0006-github-session-requests-go-through-gidgethub.md`. + +- [x] 4.1 Record in ADR 0006 that the session bounds its stored answers by bytes with `DEFAULT_GH_SESSION_ETAG_CACHE_BYTES` and by count, and that an answer above the budget is not stored + - Verification: `$ git grep -n DEFAULT_GH_SESSION_ETAG_CACHE_BYTES docs/adr/0006-github-session-requests-go-through-gidgethub.md` +- [x] 4.2 Prove that the example ConfigMap and the settings still load, because the change adds and renames no key + - Verification: `$ uv run devops ci docs` +- [x] 4.3 Run the memory tests together + - Verification: `$ uv run devops ci test tests/server/test_service_memory.py tests/github/test_github_session.py tests/telemetry/test_export_queue.py` + +## Workflow follow-up + +- Pending a person: read `container_memory_working_set_bytes` of container `service` in Grafana after 6 hours of the new pod, and record it in the pull request comment (the fifth acceptance criterion of #4116). +- Pending a person: review the diff in tuicr (tuicr -r ..HEAD). diff --git a/openspec/specs/github-session-answers/spec.md b/openspec/specs/github-session-answers/spec.md new file mode 100644 index 0000000000..dc96a430ff --- /dev/null +++ b/openspec/specs/github-session-answers/spec.md @@ -0,0 +1,25 @@ +# github-session-answers Specification + +## Purpose +The answers that the GitHub session stores for its next conditional GET, and the bound on their size in bytes, so the memory of a long-running process that shares one session does not grow with the answers it read. + +## Requirements + +### Requirement: Session answers are bounded by bytes +The GitHub session SHALL keep its stored GET answers within `DEFAULT_GH_SESSION_ETAG_CACHE_BYTES` bytes and `DEFAULT_GH_SESSION_ETAG_CACHE_SIZE` answers. When a new answer passes a bound, the answers read longest ago SHALL be dropped. + +#### Scenario: The stored answers pass the byte budget +- **WHEN** the session reads eight answers of 300 KiB, with the byte budget at 1 MiB +- **THEN** the stored answers hold at most 1 MiB in total, and the next GET of the first URL carries no `If-None-Match` +- **AND** the next GET of the last URL carries the ETag of its answer. + +#### Scenario: The heap after many rounds +- **WHEN** the status lane's round runs 200 times and each round reads one answer of a new URL +- **THEN** the heap after round 200 holds at most the slack of the rest of the process more than the heap after round 10. + +### Requirement: An oversized answer is not stored +The session MUST return an answer that is larger than the whole byte budget, and MUST NOT store it. + +#### Scenario: One answer is larger than the budget +- **WHEN** a GET returns an answer of 512 KiB, with the byte budget at 256 KiB +- **THEN** the call returns the whole answer with no error, and the next GET of that URL carries no `If-None-Match`. diff --git a/openspec/specs/otlp-export/spec.md b/openspec/specs/otlp-export/spec.md index 74acb5d018..218db7f7ef 100644 --- a/openspec/specs/otlp-export/spec.md +++ b/openspec/specs/otlp-export/spec.md @@ -54,3 +54,10 @@ The NetworkPolicy of the `devops` namespace SHALL allow egress to the `otel` nam #### Scenario: The devops egress rule to otel - **WHEN** `k8s/devops/networkpolicy.yaml` is read - **THEN** the egress rule whose peer is the `otel` namespace names the one port TCP 4318 + +### Requirement: The export queue is bounded +The tracer SHALL keep at most `DEFAULT_OTEL_EXPORT_QUEUE_MAX_PAYLOADS` payloads that wait for export or are in export, and SHALL count each payload that it drops in `export_dropped`. + +#### Scenario: A collector that does not answer +- **WHEN** the exporter blocks and the tracer sends 1000 payloads, with the cap at 16 +- **THEN** the collector takes 16 payloads once it answers, and `export_dropped` is 984. diff --git a/openspec/specs/roadmap-service-alerts/spec.md b/openspec/specs/roadmap-service-alerts/spec.md index 41b8b7678b..d3406edcd2 100644 --- a/openspec/specs/roadmap-service-alerts/spec.md +++ b/openspec/specs/roadmap-service-alerts/spec.md @@ -338,3 +338,14 @@ The rule group `roadmap-service-tools` in `k8s/monitoring/prometheus-values.yaml #### Scenario: A series of another job - **WHEN** `promtool test rules` evaluates the gauge with `job="devops-cli"` or `job="kubernetes-pods"` at 1 - **THEN** no alert counts it + +### Requirement: The memory alert warns before the limit +The rule group `roadmap-service` SHALL hold the warning alert `RoadmapServiceMemoryNearLimit`. It SHALL fire after 10 minutes when the working set of container `service` of a pod `roadmap-service-.+` in namespace `devops` is above 85% of the memory limit of that container. Its description SHALL end with `(k8s/README.md, Roadmap service)`, and that section SHALL name the alert and say what to do. + +#### Scenario: The working set stays above 85% of the limit +- **WHEN** `promtool test rules` evaluates a working set at 90% of the limit for 20 minutes +- **THEN** `RoadmapServiceMemoryNearLimit` fires with the pod, and it does not fire at the 12th minute, before the wait ends. + +#### Scenario: Another namespace or container +- **WHEN** `promtool test rules` evaluates a working set at 99% of the limit for another container of the pod, or for a pod of another namespace +- **THEN** no alert fires for it. diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index e3cc00ce4d..1ae49ed880 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -541,6 +541,10 @@ DEFAULT_OTEL_SHUTDOWN_TIMEOUT_MS: int = 50 # Longest a command's exit waits for telemetry exports still in flight. DEFAULT_OTEL_DRAIN_TIMEOUT_SECONDS: float = 1.0 +# The most export payloads that wait for the two export threads of one client (#4116). A collector +# that answers slowly for hours would else leave every payload in an unbounded queue. A payload +# past the cap is dropped and counted in `export_dropped`. +DEFAULT_OTEL_EXPORT_QUEUE_MAX_PAYLOADS: int = 256 # How often an interactive user is told, per endpoint, that telemetry exports fail. DEFAULT_OTEL_WARNING_INTERVAL_SECONDS: int = 86400 DEFAULT_TELEMETRY_TEST_NAME: str = "devops-cli.manual_test" @@ -769,6 +773,11 @@ # page that links none is not kept. A roadmap poll's listings and a PR monitor's reads fit well # inside it, and the URL read longest ago goes first. DEFAULT_GH_SESSION_ETAG_CACHE_SIZE: int = 64 +# The most bytes the same store holds (#4116). A diff has no size bound, so the count alone left +# the memory of the roadmap Service unbounded: the text of an answer, or of its encoded JSON, is +# counted once when it is stored. An answer above the whole budget is returned and not stored. A +# quarter of the memory request of the Service container. +DEFAULT_GH_SESSION_ETAG_CACHE_BYTES: int = 64 * 1024 * 1024 # Board reads page GraphQL's `ProjectV2.items` this many items at a time, its largest page (#1125). DEFAULT_GH_PROJECT_ITEM_PAGE_SIZE: int = 100 # A board read stops before a page, and refuses before it starts, while GraphQL reports fewer diff --git a/src/devops_cli/github/session_transport.py b/src/devops_cli/github/session_transport.py index 6d021f93bf..9effa7fba6 100644 --- a/src/devops_cli/github/session_transport.py +++ b/src/devops_cli/github/session_transport.py @@ -26,7 +26,8 @@ `github.error_classifier` names for it. A GET is conditional (#983): gidgethub keeps each GET's answer with its ETag in the transport's -bounded LRU store, `DEFAULT_GH_SESSION_ETAG_CACHE_SIZE` answers in memory, and sends the next GET +bounded LRU store, `DEFAULT_GH_SESSION_ETAG_CACHE_SIZE` answers and `DEFAULT_GH_SESSION_ETAG_CACHE_BYTES` +bytes in memory, and sends the next GET of that URL with `If-None-Match`; a 304 gives back the stored answer. Each attempt, a 304 too, is still paced and charged by `_request`, retried by the same hook and sent through the same origin hook, and a stored page is still checked by `listed_items`. Every GET's answer is handed out as a @@ -43,6 +44,7 @@ from __future__ import annotations import copy +import json import logging import weakref from collections.abc import Awaitable, Callable, Mapping @@ -75,6 +77,7 @@ DEFAULT_GH_MAX_RETRIES, DEFAULT_GH_SERVER_ERROR_RETRY_FLOOR_SECONDS, DEFAULT_GH_SESSION_CONNECT_TIMEOUT_SECONDS, + DEFAULT_GH_SESSION_ETAG_CACHE_BYTES, DEFAULT_GH_SESSION_ETAG_CACHE_SIZE, ) from devops_cli.core.process import GitHubIdentity @@ -124,6 +127,38 @@ type StoredAnswer = tuple[str | None, str | None, Any, str | None] +def _answer_bytes(answer: StoredAnswer) -> int: + """The size of one stored answer: the length of its text, or of its encoded JSON for a + decoded value (#4116). A diff has no size bound on GitHub's side, so the count of answers + alone does not bound the memory of the store.""" + body = answer[2] + if body is None: + return 0 + if isinstance(body, str): + return len(body) + return len(json.dumps(body, separators=(",", ":"))) + + +class _AnswerStore(LRUCache[str, StoredAnswer]): + """The LRU store of a session's answers, bounded by bytes and by count (#4116). + + Each answer counts at least `budget // DEFAULT_GH_SESSION_ETAG_CACHE_SIZE` bytes, so the count + bound holds too. The answer read longest ago goes first. An answer larger than the whole + budget is not stored: `LRUCache` refuses it with a `ValueError`, and the read that got it + must still return it. + """ + + def __init__(self, budget: int) -> None: + floor = budget // DEFAULT_GH_SESSION_ETAG_CACHE_SIZE + super().__init__(maxsize=budget, getsizeof=lambda answer: max(_answer_bytes(answer), floor)) + + def __setitem__(self, key: str, value: StoredAnswer) -> None: + try: + super().__setitem__(key, value) + except ValueError: + self.pop(key, None) + + def _origin_text(origin: httpx2.Origin) -> str: """An origin as `scheme://host:port`.""" return f"{origin.scheme}://{origin.host}:{origin.port}" @@ -269,9 +304,7 @@ class SessionGitHubAPI(GitHubAPI): with the identity's token.""" def __init__(self, client: httpx2.AsyncClient, identity: GitHubIdentity) -> None: - self._stored: LRUCache[str, StoredAnswer] = LRUCache( - maxsize=DEFAULT_GH_SESSION_ETAG_CACHE_SIZE - ) + self._stored = _AnswerStore(DEFAULT_GH_SESSION_ETAG_CACHE_BYTES) super().__init__( client, CONST_GITHUB_USER_AGENT, diff --git a/src/devops_cli/telemetry/tracer.py b/src/devops_cli/telemetry/tracer.py index 2099f9bcf0..ef28e1079a 100644 --- a/src/devops_cli/telemetry/tracer.py +++ b/src/devops_cli/telemetry/tracer.py @@ -34,6 +34,7 @@ DEFAULT_OTEL_COUNTER_AMOUNT, DEFAULT_OTEL_DRAIN_TIMEOUT_SECONDS, DEFAULT_OTEL_ENDPOINT, + DEFAULT_OTEL_EXPORT_QUEUE_MAX_PAYLOADS, DEFAULT_OTEL_SHUTDOWN_TIMEOUT_MS, DEFAULT_OTEL_TEST_TIMEOUT, DEFAULT_OTEL_WARNING_INTERVAL_SECONDS, @@ -857,6 +858,11 @@ def __init__( self._pending: set[Future[None]] = set() self.export_failures = 0 self.export_successes = 0 + # Payloads that wait for an export thread, or run in one, are capped: a collector that + # does not answer must not grow the queue without end (#4116). A payload without a free + # slot is dropped and counted here. + self._export_slots = threading.BoundedSemaphore(DEFAULT_OTEL_EXPORT_QUEUE_MAX_PAYLOADS) + self.export_dropped = 0 self.last_export_error = "" # Cache pre-computed resource attributes for zero-allocation reuse across all spans and metrics @@ -1323,13 +1329,29 @@ def _send_payload(self, path: str, payload: dict[str, Any]) -> None: if not self.enabled or in_dry_run_invocation(): return + if not self._export_slots.acquire(blocking=False): + self.export_dropped += 1 + if self.export_dropped == 1: + logger.warning( + "The OTel export queue is full: the collector at %s does not answer in time, " + "so payloads are dropped", + self.endpoint, + ) + return try: executor = self._get_executor() future = executor.submit(self._send_payload_sync, path, payload) - self._pending.add(future) - future.add_done_callback(self._pending.discard) except Exception as exc: + self._export_slots.release() logger.debug("Failed submitting OTel payload to executor: %s", exc) + return + self._pending.add(future) + future.add_done_callback(self._export_done) + + def _export_done(self, future: Future[None]) -> None: + """Forget an export that ended, and give its slot back.""" + self._pending.discard(future) + self._export_slots.release() def _flush_sdk_metrics(self) -> None: """Collect buffered SDK metrics and queue one OTLP /v1/metrics export.""" diff --git a/tests/fixtures/prometheus_rules/roadmap_service_tests.yaml b/tests/fixtures/prometheus_rules/roadmap_service_tests.yaml index bbd3504ffb..1420c53b35 100644 --- a/tests/fixtures/prometheus_rules/roadmap_service_tests.yaml +++ b/tests/fixtures/prometheus_rules/roadmap_service_tests.yaml @@ -247,6 +247,36 @@ tests: summary: "The roadmap Service container in roadmap-service-7d9f8b6c5-x2x4z restarted" description: "The restart count of container service of pod devops/roadmap-service-7d9f8b6c5-x2x4z increased by 1 in the last hour (k8s/README.md, Roadmap service)." + - name: The memory near the limit fires after 10 minutes; another namespace or container does not count + interval: 1m + input_series: + - series: 'container_memory_working_set_bytes{namespace="devops", pod="roadmap-service-7d9f8b6c5-x2x4z", container="service"}' + values: '800000000x5 900000000x30' + - series: 'kube_pod_container_resource_limits{namespace="devops", pod="roadmap-service-7d9f8b6c5-x2x4z", container="service", resource="memory"}' + values: '1000000000x40' + - series: 'container_memory_working_set_bytes{namespace="devops", pod="roadmap-service-7d9f8b6c5-x2x4z", container="sidecar"}' + values: '990000000x40' + - series: 'kube_pod_container_resource_limits{namespace="devops", pod="roadmap-service-7d9f8b6c5-x2x4z", container="sidecar", resource="memory"}' + values: '1000000000x40' + - series: 'container_memory_working_set_bytes{namespace="llm", pod="llm-gateway-5c9d7f8b6-q7w8e", container="service"}' + values: '990000000x40' + - series: 'kube_pod_container_resource_limits{namespace="llm", pod="llm-gateway-5c9d7f8b6-q7w8e", container="service", resource="memory"}' + values: '1000000000x40' + alert_rule_test: + - eval_time: 12m + alertname: RoadmapServiceMemoryNearLimit + exp_alerts: [] + - eval_time: 25m + alertname: RoadmapServiceMemoryNearLimit + exp_alerts: + - exp_labels: + severity: warning + namespace: devops + pod: roadmap-service-7d9f8b6c5-x2x4z + exp_annotations: + summary: "The roadmap Service container in roadmap-service-7d9f8b6c5-x2x4z uses 90% of its memory limit" + description: "The working set of container service of pod devops/roadmap-service-7d9f8b6c5-x2x4z has been above 85% of its memory limit for 10 minutes, and the kernel kills the container at 100% (k8s/README.md, Roadmap service)." + - name: An unavailable replica fires after 10 minutes; another deployment does not count interval: 1m input_series: diff --git a/tests/github/test_github_session.py b/tests/github/test_github_session.py index 9547b2b000..1e30f6712f 100644 --- a/tests/github/test_github_session.py +++ b/tests/github/test_github_session.py @@ -891,6 +891,55 @@ def test_the_session_keeps_the_etags_of_its_latest_reads_only( assert _conditions(github_api) == [None, None, None, _ETAG] +_KIB = 1024 + + +def _diff_answer(size: int, etag: str) -> httpx2.Response: + """A pull request's diff of `size` bytes, carrying `etag`.""" + return github_text("+" * size, media_type=CONST_GITHUB_DIFF_MEDIA_TYPE, headers={"etag": etag}) + + +def test_the_session_keeps_the_answers_of_its_latest_reads_within_the_byte_budget( + github_api: GitHubApiFake, monkeypatch: pytest.MonkeyPatch +) -> None: + """The store of answers is bounded by bytes as well as by count (#4116): past + `DEFAULT_GH_SESSION_ETAG_CACHE_BYTES`, the answers read longest ago are dropped and read in + full again, and the newest answer stays. + + Eight diffs of 300 KiB are 2.4 MiB; with a budget of 1 MiB the store holds the newest three + at most. `raising=False`: the base tree has no byte budget, so the replay of this test on + the base fails on the answers kept, not on the missing name. + """ + monkeypatch.setattr( + session_transport, "DEFAULT_GH_SESSION_ETAG_CACHE_BYTES", 1024 * _KIB, raising=False + ) + paths = [f"/repos/example-org/app/pulls/{number}" for number in range(8)] + for number, path in enumerate(paths): + github_api.route("GET", path, _diff_answer(300 * _KIB, f'"{number}"')) + session = get_github_session() + for path in (*paths, paths[0], paths[-1]): + session.rest("GET", path, accept=CONST_GITHUB_DIFF_MEDIA_TYPE) + sent = _conditions(github_api) + assert (sent[-2], sent[-1]) == (None, '"7"') + + +def test_an_answer_larger_than_the_byte_budget_is_returned_and_not_stored( + github_api: GitHubApiFake, monkeypatch: pytest.MonkeyPatch +) -> None: + """One answer past the whole budget comes back to the caller with no error, and the next GET + of its URL is not conditional (#4116). `raising=False` as in the test above.""" + monkeypatch.setattr( + session_transport, "DEFAULT_GH_SESSION_ETAG_CACHE_BYTES", 256 * _KIB, raising=False + ) + path = "/repos/example-org/app/pulls/1" + github_api.route("GET", path, _diff_answer(512 * _KIB, '"1"')) + session = get_github_session() + answers = [ + len(session.rest("GET", path, accept=CONST_GITHUB_DIFF_MEDIA_TYPE)) for _ in range(2) + ] + assert (answers, _conditions(github_api)) == ([512 * _KIB] * 2, [None, None]) + + def test_a_page_answered_from_its_etag_keeps_its_next_link_and_the_last_page_is_read_in_full( github_api: GitHubApiFake, ) -> None: diff --git a/tests/prometheus/test_k8s_monitoring_alerting.py b/tests/prometheus/test_k8s_monitoring_alerting.py index 8681c12589..84fc19033b 100644 --- a/tests/prometheus/test_k8s_monitoring_alerting.py +++ b/tests/prometheus/test_k8s_monitoring_alerting.py @@ -136,6 +136,9 @@ "kube_deployment_status_replicas_available", "kube_deployment_status_replicas_unavailable", "kube_pod_container_status_restarts_total", + # The memory limit and the working set of the roadmap Service's container (#4116). + "kube_pod_container_resource_limits", + "container_memory_working_set_bytes", # Not in the chart's default allow list: `metricsTuning.includeMetrics` keeps it (#1817). "kube_ingress_path", # The kubelet, scraped by k8s-monitoring (its default allow list), reports these only for @@ -347,6 +350,7 @@ def test_the_baseline_rule_set() -> None: ("RoadmapServiceItemStuck", "warning"), ("RoadmapServiceJobsFailing", "warning"), ("RoadmapServiceLaneStalled", "warning"), + ("RoadmapServiceMemoryNearLimit", "warning"), ("RoadmapServiceModelRequestsHigh", "warning"), ("RoadmapServiceRestarted", "warning"), ("RoadmapServiceSelfDeliveriesHigh", "warning"), @@ -923,6 +927,16 @@ def _window_count(series: str, window: str) -> str: "0m", "warning", ), + ( + "RoadmapServiceMemoryNearLimit", + "max by (namespace, pod) (container_memory_working_set_bytes" + '{namespace="devops", pod=~"roadmap-service-.+", container="service"})' + " / max by (namespace, pod) (kube_pod_container_resource_limits" + '{namespace="devops", pod=~"roadmap-service-.+", container="service", resource="memory"})' + " > 0.85", + "10m", + "warning", + ), ( "RoadmapServiceUnavailable", "max by (namespace, deployment) (kube_deployment_status_replicas_unavailable" @@ -1152,8 +1166,8 @@ def test_both_paths_name_the_roadmap_service_job() -> None: def test_the_roadmap_service_rules_read_kube_state_metrics_that_the_chart_keeps() -> None: - """The restart and replica series are in the chart's default allow list or in - `metricsTuning.includeMetrics`, so they reach Prometheus (#2472).""" + """The restart, replica and memory limit series are in the chart's default allow list or in + `metricsTuning.includeMetrics`, so they reach Prometheus (#2472, #4116).""" allow_list = yaml.safe_load(KUBE_STATE_METRICS_ALLOW_LIST.read_text(encoding="utf-8")) tuning = _yaml(K8S_MONITORING_VALUES)["clusterMetrics"]["kube-state-metrics"]["metricsTuning"] kept = re.compile("|".join([*allow_list["metrics"], *tuning["includeMetrics"]])) @@ -1163,7 +1177,7 @@ def test_the_roadmap_service_rules_read_kube_state_metrics_that_the_chart_keeps( for selector in selectors(rule["expr"]) if (selector.metric or "").startswith("kube_") } - assert (len(metrics), sorted(m for m in metrics if not kept.fullmatch(m))) == (3, []) + assert (len(metrics), sorted(m for m in metrics if not kept.fullmatch(m))) == (4, []) def test_the_otel_collector_rules_warn_after_15_minutes_and_name_no_node() -> None: diff --git a/tests/server/test_service_memory.py b/tests/server/test_service_memory.py new file mode 100644 index 0000000000..51af3eaf21 --- /dev/null +++ b/tests/server/test_service_memory.py @@ -0,0 +1,117 @@ +"""The roadmap Service holds no more memory after 200 rounds than its bounds allow (#4116). + +The pod of the Service was OOMKilled at its 1 GiB limit after hours. A round reads GitHub through +the process's one session, which keeps its GET answers for the next conditional GET, and it +exports spans and metrics through the tracer. This test runs the status lane's round 200 times +over the real worker, session and tracer, with the fakes of GitHub and of the collector, and +measures the heap with `MemoryProfiler` (`tracemalloc`). Each round reads one answer of a new URL, +so the session's store is the structure that can grow with the number of rounds. + +The base tree keeps 64 answers whatever their size, so the heap at round 200 holds 64 answers and +the heap at round 10 holds 10. With a byte budget, both hold the budget. +""" + +from __future__ import annotations + +import gc +import tracemalloc +from datetime import UTC, datetime + +import httpx2 +import pytest + +from devops_cli.config.constants import CONST_GITHUB_DIFF_MEDIA_TYPE, CONST_SERVICE_LANE_STATUS +from devops_cli.github import session_transport +from devops_cli.github.session import get_github_session +from devops_cli.server.service import RepoWorker, TriggerBatch +from devops_cli.telemetry.memory_profiler import MemoryProfiler +from tests.support.fakes.github import GitHubApiFake +from tests.support.fakes.otlp import FakeCollector +from tests.support.waits import THREAD_HANDOFF_BOUND_SECONDS + +REPO = "example-org/repo1" +ROUNDS = 200 +EARLY_ROUND = 10 +MIB = 1024 * 1024 +BUDGET_BYTES = 8 * MIB +"""The byte budget of the session's stored answers in this test; the default is larger.""" +ANSWER_BYTES = MIB +"""One answer: a pull request diff, which has no size bound on GitHub's side.""" +SLACK_BYTES = 6 * MIB +"""What the rest of the process may gain in 190 rounds: metric series, the span buffer and the +fakes' request records, which are small and bounded or grow by a few bytes for each round.""" + + +def _heap_bytes() -> int: + """The traced heap now, after a collection.""" + gc.collect() + return tracemalloc.get_traced_memory()[0] + + +def test_the_heap_at_round_200_is_within_the_byte_budget_of_the_heap_at_round_10( + github_api: GitHubApiFake, otlp: FakeCollector, monkeypatch: pytest.MonkeyPatch +) -> None: + """The growth between round 10 and round 200 is at most the session's byte budget less what + round 10 held, plus the slack of the rest of the process, and the failure names the + allocation sites that grew. + + `raising=False`: the base tree has no byte budget, so the replay of this test on the base + fails on the growth, not on the missing name. + """ + monkeypatch.setattr( + session_transport, "DEFAULT_GH_SESSION_ETAG_CACHE_BYTES", BUDGET_BYTES, raising=False + ) + body = ("+" * ANSWER_BYTES).encode() + """One buffer for every answer, so the fake holds the diff once, not once for each route.""" + served = 0 + + def round_job(batch: TriggerBatch) -> None: + get_github_session().rest( + "GET", f"/repos/{REPO}/pulls/{served}", accept=CONST_GITHUB_DIFF_MEDIA_TYPE + ) + + worker = RepoWorker( + repo=REPO, + lane=CONST_SERVICE_LANE_STATUS, + job_func=round_job, + clock=lambda: datetime.now(UTC), + ) + profiler = MemoryProfiler("service-rounds") + profiler.start() + worker.start() + heaps: dict[int, int] = {} + try: + for number in range(1, ROUNDS + 1): + served = number + github_api.route( + "GET", + f"/repos/{REPO}/pulls/{number}", + httpx2.Response( + 200, + headers={ + "content-type": f"{CONST_GITHUB_DIFF_MEDIA_TYPE}; charset=utf-8", + "etag": f'"{number}"', + }, + content=body, + ), + ) + worker.enqueue("webhook", "pull_request", "synchronize") + assert worker.wait_active(THREAD_HANDOFF_BOUND_SECONDS) + otlp.clear() # the fake collector keeps every export it gets; the Service does not + if number in (EARLY_ROUND, ROUNDS): + heaps[number] = _heap_bytes() + finally: + worker.stop() + assert worker.join(THREAD_HANDOFF_BOUND_SECONDS) + report = profiler.stop(top_n=6) + + growth = heaps[ROUNDS] - heaps[EARLY_ROUND] + sites = [ + f"{item.filename}:{item.line_number} {item.size_human}" for item in report.top_allocations + ] + assert len(github_api.sent) == ROUNDS + assert growth <= SLACK_BYTES, ( + f"The heap grew {growth / MIB:.1f} MiB between round {EARLY_ROUND} and round {ROUNDS}, " + f"past the {SLACK_BYTES / MIB:.0f} MiB the rest of the process may gain; " + f"the largest allocation sites: {sites}" + ) diff --git a/tests/telemetry/test_export_queue.py b/tests/telemetry/test_export_queue.py new file mode 100644 index 0000000000..2c2d3a67c2 --- /dev/null +++ b/tests/telemetry/test_export_queue.py @@ -0,0 +1,66 @@ +"""The tracer's queue of export payloads is bounded, and it counts what it drops (#4116). + +The tracer hands each span and metric payload to two export threads. A collector that answers +slowly for hours left every payload waiting in an unbounded queue of the Service. With a cap, the +tracer keeps the newest-first payloads that fit, drops the rest and counts them. +""" + +from __future__ import annotations + +import threading + +import pytest + +from devops_cli.telemetry import tracer as tracer_module +from devops_cli.telemetry.tracer import OTelTelemetryClient +from tests.support.waits import THREAD_HANDOFF_BOUND_SECONDS + +PAYLOADS = 1000 +CAP = 16 + + +class BlockedCollector: + """An exporter whose exports wait until the test opens it, as a collector that does not + answer.""" + + endpoint = "http://otlp.example.com:4318" + + def __init__(self) -> None: + self.opened = threading.Event() + self.taken = 0 + self._lock = threading.Lock() + + def export(self, signal: object, body: bytes, content_type: str) -> None: + self.opened.wait(timeout=THREAD_HANDOFF_BOUND_SECONDS) + with self._lock: + self.taken += 1 + + def probe(self, timeout: float) -> object: + raise NotImplementedError + + def close(self) -> None: + return None + + +def test_a_collector_that_does_not_answer_leaves_at_most_the_cap_of_payloads_waiting( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """With the exporter blocked and 1000 payloads sent, the collector gets at most the cap once + it answers, and the client counts every payload it dropped. + + `raising=False`: the base tree has no cap, so the replay of this test on the base fails on + the payloads kept, not on the missing name. + """ + monkeypatch.setattr(tracer_module, "DEFAULT_OTEL_EXPORT_QUEUE_MAX_PAYLOADS", CAP, raising=False) + collector = BlockedCollector() + client = OTelTelemetryClient(endpoint=collector.endpoint, enabled=True, exporter=collector) + try: + for number in range(PAYLOADS): + client._send_payload("/v1/traces", {"resourceSpans": [], "number": number}) + collector.opened.set() + client.flush() + finally: + collector.opened.set() + client.shutdown() + dropped = getattr(client, "export_dropped", None) + assert (collector.taken, dropped) == (CAP, PAYLOADS - CAP)