Repository navigation
feat(telemetry): cgroup v2 metrics collection and prometheus application scraping (#108) - #164
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved telemetry correctness, threshold rendering, instrumentation, and documentation issues block approval.
Get a fresh assessment by requesting another Copilot review.
Pull request overview
Adds cgroup v2 and Prometheus telemetry collection for sandbox workloads, with CLI output, threshold evaluation, tests, and documentation.
Changes:
- Adds telemetry models, parsers, Docker fallback, and engine integration.
- Adds
devops sandbox metricswith Rich, JSON, threshold, and dry-run support. - Adds tests, generated documentation, and task tracking.
File summaries
| File | Changes | Review findings |
|---|---|---|
tests/test_sandbox_metrics.py |
Adds telemetry, parser, engine, and CLI tests. | No final comments. |
src/devops_cli/sandbox/models.py |
Defines telemetry data models. | Moderate (2 votes): Open-FD telemetry is absent, and network RX/TX fields are not populated. |
src/devops_cli/sandbox/metrics.py |
Implements cgroup and Prometheus collection. | Critical (3 votes): Parsed sample timestamps are discarded. Moderate (1 vote): Prometheus label escapes are not decoded. Moderate (1 vote): Histogram-derived latency evaluation is missing. Moderate (2 votes): Zero memory usage is treated as unknown. Moderate (1 vote): Network RX/TX values are never populated. Moderate (1 vote): 5xx evaluation does not recognize the common status label. |
src/devops_cli/sandbox/engine.py |
Exposes sandbox metrics collection. | Moderate (1 vote): The metrics operation lacks lifecycle tracing and resource instrumentation. |
src/devops_cli/sandbox/__init__.py |
Exports telemetry APIs and models. | No final comments. |
src/devops_cli/lang/en/help.py |
Adds CLI help text. | Nit (1 vote): The metrics timeout reuses stop-command help describing graceful shutdown. |
src/devops_cli/commands/sandbox.py |
Implements the metrics command and rendering. | Moderate (3 votes): Rendering hardcodes CPU and memory thresholds instead of configured values. Nit (1 vote): The timeout option documents graceful stopping rather than Prometheus request timeout. |
README.md |
Updates the CLI command matrix. | No final comments. |
docs/commands/sandbox.md |
Documents the sandbox metrics command. | Nit (1 vote): The metrics timeout description incorrectly describes graceful shutdown. |
docs/CLI_REFERENCE.md |
Updates the generated CLI reference. | Nit (1 vote): The metrics timeout description incorrectly describes graceful shutdown. |
docs/agent/tasks/task-108-sandbox-metrics-cgroup-prom.md |
Tracks implementation progress and scope. | Nit (3 votes): Task metadata remains TBD/In Progress; update it and the active task index to reflect review status. |
Review details
Suppressed comments (14)
docs/CLI_REFERENCE.md:5825
- The generated reference repeats the wrong stop-command description for this metrics timeout. It should describe the HTTP Prometheus scrape timeout, not graceful shutdown before SIGKILL.
| `--timeout`, `-t` | `float` | `5.0` | Graceful stop timeout in seconds before SIGKILL. |
docs/commands/sandbox.md:156
- The generated option description is copied from the stop command and is incorrect for metrics: this timeout bounds the Prometheus scrape request, not graceful container shutdown or SIGKILL.
| `--timeout`, `-t` | `float` | `5.0` | Graceful stop timeout in seconds before SIGKILL. |
src/devops_cli/commands/sandbox.py:495
- The new metrics subcommand is not wrapped in an OpenTelemetry span and the collection path records no
GLOBAL_METRICScounters or histograms. This is a direct deviation from the repository's telemetry-by-default requirement inAGENTS.md:257, leaving the new telemetry operation itself unobservable.
@app.command("metrics")
def metrics(
src/devops_cli/commands/sandbox.py:506
- This option reuses
HELP.sandbox.timeout, whose text is “Graceful stop timeout in seconds before SIGKILL.” For metrics it controls the Prometheus HTTP request timeout, so the generated CLI help and both committed command references document the wrong behavior.
timeout: Annotated[float, typer.Option("--timeout", "-t", help=HELP.sandbox.timeout)] = 5.0,
src/devops_cli/lang/en/help.py:964
- The command reuses
HELP.sandbox.timeout, whose text describes the stop/kill timeout, for the Prometheus HTTP timeout. The generated command docs consequently say this metrics flag is a graceful stop timeout; add a metrics-specific help entry and use it here before regenerating the references.
metrics: str = "Capture real-time cgroup v2 metrics and scrape Prometheus application metrics."
metrics_endpoint: str = "Prometheus metrics scrape path (default /metrics)."
warn_memory_pct: str = "Warning threshold percentage for container memory consumption."
warn_cpu_pct: str = "Warning threshold percentage for container CPU utilization."
src/devops_cli/sandbox/engine.py:492
- This new public engine operation is not wrapped in the tracing/metrics instrumentation used by the sandbox lifecycle methods, so direct
WorkloadSandboxEngine.metrics()callers lose collection duration, failures, and resource telemetry from OpenTelemetry/GLOBAL_METRICS. Instrument the collection path rather than relying only on the top-level CLI span.
from devops_cli.sandbox.metrics import collect_sandbox_metrics
return collect_sandbox_metrics(
instance_or_target=inst,
prom_endpoint=prom_endpoint,
timeout=timeout,
memory_threshold_pct=memory_threshold_pct,
cpu_threshold_pct=cpu_threshold_pct,
)
src/devops_cli/sandbox/metrics.py:59
cpu.stat:usage_usecis a cumulative counter, but this converts it directly to a percentage and clamps it to 100 without a previous sample, elapsed interval, or CPU quota. A container that has accumulated more than 10 seconds of CPU time will appear permanently at 100%, so the advertised real-time CPU utilization and CPU alerts are incorrect; compute a delta over a sampling interval (or expose the counter instead).
cpu_usec = float(cpu_stats.get("usage_usec", 0))
cpu_percent = round(min(cpu_usec / 100000.0, 100.0), 2) if cpu_usec > 0 else 0.0
src/devops_cli/sandbox/metrics.py:289
- This raw URL path performs only a scheme check, so a caller can make the CLI request arbitrary loopback, RFC1918, link-local, or cloud-metadata addresses. Use
validate_url_egresswith an explicit, narrowly scoped exception for sandbox-local endpoints before issuing the request; scheme validation alone does not provide the repository's SSRF boundary.
parsed = urllib.parse.urlparse(metrics_url)
if parsed.scheme not in ("http", "https"):
return []
src/devops_cli/sandbox/metrics.py:298
- HTTP errors and request exceptions are collapsed into the same empty list returned for a valid endpoint with no samples.
collect_sandbox_metricsthen produces no warning andSandboxMetricsSnapshot.is_healthyreports the workload as healthy even when/metricsis unreachable or returns 500. Preserve scrape status/error information or add an explicit collection warning.
if resp.status_code != 200:
return []
return parse_prometheus_exposition(resp.text)
except httpx2.RequestError, OSError, ValueError:
return []
src/devops_cli/sandbox/metrics.py:264
- Label escape sequences are retained verbatim, although Prometheus exposition requires escapes such as
\\",\\\\, and\\nto be decoded. Valid labels therefore expose the wrong values and dimensional queries can fail; use an exposition-aware label parser/unescaper rather than returning the regex capture unchanged.
labels: dict[str, str] = {}
if labels_str:
for lbl_match in _LABEL_REGEX.finditer(labels_str):
labels[lbl_match.group(1)] = lbl_match.group(2)
src/devops_cli/sandbox/metrics.py:305
evaluate_threshold_warningsreceives only one snapshot and compares current memory to a limit; it has no prior samples, elapsed interval, or slope. A steadily growing workload that remains below the limit is therefore never identified as a memory leak, despite the PR and issue promising leak-trajectory detection.
def evaluate_threshold_warnings(
cgroup: CgroupV2Metrics | None,
prom_metrics: list[PrometheusMetric],
memory_threshold_pct: float = 80.0,
cpu_threshold_pct: float = 85.0,
src/devops_cli/sandbox/metrics.py:345
- The Prometheus evaluator only computes an HTTP 5xx ratio; it never derives latency from histogram buckets,
_sum, or_countsamples. Consequently the promised latency-histogram/latency-anomaly telemetry is only displayed as raw samples and cannot detect latency degradation.
def _evaluate_prom_thresholds(
prom_metrics: list[PrometheusMetric],
warnings: list[str],
) -> None:
"""Evaluate application error rates from scraped Prometheus metrics."""
src/devops_cli/sandbox/metrics.py:71
- The model exposes
network_rx_bytesandnetwork_tx_bytes, but this direct cgroup result does not populate them and_build_metrics_from_docker_dictalso omits them. Every reported network value therefore remains zero, despite the issue/task promising network throughput telemetry; collect the container network counters or remove these fields until they are supported.
return CgroupV2Metrics(
cpu_percent=cpu_percent,
memory_current_bytes=mem_current or 0,
memory_peak_bytes=mem_peak,
memory_limit_bytes=mem_limit,
memory_usage_percent=mem_pct,
page_faults_total=page_faults,
pids_current=pids_current,
io_read_bytes=io_bytes[0],
io_write_bytes=io_bytes[1],
)
src/devops_cli/sandbox/metrics.py:353
- The evaluator only recognizes a
codelabel, while Prometheus HTTP metrics commonly usestatus(and this repository's own queries usestatus=~"5.."). A metric such ashttp_requests_total{status="500"}is counted in the denominator but never as an error, so the promised 5xx warning is missed.
code = m.labels.get("code", "")
req_total += m.value
if code.startswith("5") or m.labels.get("error") == "true":
- Files reviewed: 11/11 changed files
- Comments generated: 5
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| return PrometheusMetric( | ||
| name=name, | ||
| metric_type=metric_type, | ||
| labels=labels, | ||
| value=val, | ||
| ) |
| cpu_badge = "[red]HIGH[/red]" if cgroup.cpu_percent > 85.0 else "[green]HEALTHY[/green]" | ||
| mem_lim_str = f"{cgroup.memory_limit_mb:.1f} MB" if cgroup.memory_limit_mb else "unbounded" | ||
| mem_pct = ( | ||
| f"{cgroup.memory_usage_percent:.1f}%" if cgroup.memory_usage_percent is not None else "-" | ||
| ) |
| mem_pct = ( | ||
| round((mem_current / mem_limit) * 100.0, 2) | ||
| if mem_current and mem_limit and mem_limit > 0 | ||
| else None | ||
| ) |
| pids_current: int = 0 | ||
| io_read_bytes: int = 0 | ||
| io_write_bytes: int = 0 | ||
| network_rx_bytes: int = 0 | ||
| network_tx_bytes: int = 0 |
| **Issue**: [#108](https://github.com/dan-petty/devops-cli/issues/108) | ||
| **PR**: TBD | ||
| **Status**: In Progress |
* feat(release): v0.2.17 * feat(sandbox): protocol-agnostic endpoint readiness and health probing subsystem (#107) Closes #107 * docs(agent): reconcile task 107 tracking to done (#107) * feat(telemetry): cgroup v2 metrics collection and prometheus application scraping (#108) Closes #108 * docs(agent): reconcile task 108 to done following PR #164 merge * docs(agent): require draft pull requests for in-progress work (#165) (#166) * docs(agent): require draft pull requests for in-progress work (#165) * docs(agent): align lifecycle definitions and update task index for PR #166 * fix(sandbox): resolve cpu delta sampling, ssrf boundaries, and cgroup fallback (#168) * fix(sandbox): remediate pr 164 review findings on sandbox metrics collection (#167) * test(sandbox): normalize whitespace in help assertion for variable terminal widths * test(sandbox): assert help option text without border wrapping sensitivity * fix(sandbox): address pr 168 review comments on url sanitization and telemetry contracts (#167) * fix(sandbox): resolve pr 168 review comments on cpu delta sampling, ssrf boundaries, and cgroup fallback (#167) * test(sandbox): remove redundant comment header in metrics tests * feat(pr): monitor pr checks, copilot reviews, and review threads (#170) (#171) * feat(github): automated pr monitoring and copilot review verification (#170) * fix(pr): resolve copilot review findings and enforce 5m/60s monitoring standards (#170) * feat(k8s): configurable k8s context setting and conditional minikube autostart (#172) (#174) * feat(k8s): configurable k8s context setting and conditional minikube autostart (#172) * docs(k8s): document minikube devcontainer lifecycle and external cluster configurations (#172) * fix(k8s): resolve copilot review findings for context validation and autostart (#172) * test(k8s): update qdrant secret lifecycle assertion for effective context flag (#172) * fix(github): project field options sync, complete pagination, generic owner resolution, and mock hostname standardization (#175) (#173) - Resolve automated GitHub Projects bot resetting status by auto-provisioning missing single-select options (e.g. 'In Review') - Implement complete pagination across projectsV2 items, issues, and PR endpoints - Resolve project owner dynamically via gh api user login without hardcoded usernames - Display draft PR warnings cleanly in monitor exit handler - Standardize all mock/dummy test values across all tests to example.com with no subdomain - Enforce complexity <= 10 and nesting <= 5 architectural invariants * fix(review): remediate devsecops findings and enhance review self-improvement loop (#176) (#177) * docs(agent): bootstrap task 176 for review findings remediation * fix(review): remediate DevSecOps findings and enhance review self-improvement loop (#176) * feat(telemetry): w3c traceparent propagation and distributed trace correlation (#109) (#178) * feat(telemetry): w3c traceparent propagation and distributed trace correlation (#109) * docs(agent): link draft PR 178 in task 109 tracking * fix(k8s): resolve helm ssa conflicts, loki validation, podsecurity, and qdrant permissions (#183) (#182) * fix(k8s): resolve helm ssa conflicts, loki validation, podsecurity, and qdrant permissions (#183) * docs(agent): link pull request #182 in task 183 tracking * feat(sandbox): streaming diagnostic log aggregator and panic detector (#110) (#179) * feat(sandbox): streaming diagnostic log aggregator and panic detector (#110) * docs(agent): link draft PR #179 in task-110 tracking * fix(sandbox): remediate review findings, demux streams, bound follow memory, and sanitize output (#110) * docs(agent): update task 110 status to In Review and record review thread resolutions * fix(github): gate pr merge readiness on required approvals, mergeable state, and reviewer feedback (#183) (#184) * fix(github): gate pr merge readiness on required approvals, mergeable state, and reviewer feedback (#183) * fix(github): remediate copilot review findings on pr merge readiness (#183) * fix(github): enforce review approval gate, exclude negative copilot headings, and forward tokens (#183) * fix(github): restrict copilot heading match, validate approval head sha, and support explicit env (#183) * fix(review): remediate DevSecOps findings and enhance review self-improvement loop (#185) (#186) * fix(github): gate pr merge readiness on required approvals, mergeable state, and reviewer feedback (#183) * fix(review): remediate session 20260913-060209 findings and enhance review self-improvement loop (#185) - sandbox probe: block metadata endpoints, bound regex len and search window, validate target URLs - telemetry waterfall: enforce hex trace ID validation and validate Jaeger endpoints against SSRF - telemetry context: add trace_flags parameter to generate_traceparent - sandbox logs: mask secrets in panic incidents and set 0o600 file / 0o700 dir permissions - sandbox metrics: reject cgroup path traversal and restrict parsing to valid cgroup hierarchies - sandbox models: truncate and mask probe result details and incident messages/stacktraces - sanitizer: mask secrets in non-flag arguments in sanitize_command_args_for_display - valkey client: correctly strip enclosing brackets from IPv6 hostnames - http client: validate timeout argument types - k8s stack lifecycle: mask non-localhost emails in bootstrap summary display - anti-hallucination dataset: calibrate false positives into common_hallucinations.json - documentation & prompts: update SELF_IMPROVEMENT.md, review.md, AGENTS.md, and task tracking * docs(agent): link pull request #186 in task 185 tracking * fix(review): address review feedback across sandbox, telemetry, k8s, and test fixtures (#185) - probe: canonicalize trailing dot and resolve host to block link-local/cloud metadata - waterfall: reject resolved metadata hosts and fix exception tuple in Jaeger trace query - k8s: mask short and malformed emails in bootstrap display and preserve PII in dry-run - pr monitor: exclude unknown mergeable_state from readiness and evaluate latest review per user - http client: raise HTTPTimeoutTypeError derived from ValidationError and TypeError - sandbox logs: unlink archive and raise SandboxError on incident chmod failure - sandbox metrics: enforce path-aware containment for cgroup v2 hierarchies - sandbox models: recursively sanitize nested details and reserve suffix length for truncation cap - telemetry context: raise TraceValidationError on invalid traceparent flags - conftest: detect and fail on unauthorized creation or deletion of workspace config.yaml - tasks: reconcile PR #184 mapping, update taxonomy to status/in-review, and re-sync index * fix(process): preserve GH_TOKEN and GITHUB_REPOSITORY for gh binary execution * fix(repo): prioritize git remote origin before GITHUB_REPOSITORY fallback * fix(security): pin vetted ip transports against dns rebinding and enforce clean merge state (#185) (#186) * feat(github): implement native devops cli functionality for gh operations and pr governance (#181) (#187) * feat(github): implement native devops cli functionality for gh operations and pr governance (#181) - Implement native devops pr ready, diff, and close subcommands - Implement native devops gh rate-limit and runs subcommands - Register FastMCP tools pr_ready, pr_diff, pr_close, gh_rate_limit, gh_runs_list, gh_run_view - Harden config discovery and add pytest safety barrier against workspace config mutations - Configure squid k8s deployment to use internal registry alias registry.local:5000 - Add comprehensive test coverage and documentation updates * feat(github): add REST fallbacks for pr view/checks, issues/pr edit, and resolve loki crashloop (#181) - Fall back to REST API in devops pr view and devops pr checks when GraphQL rate limits are exceeded - Add devops pr edit and devops gh issues edit subcommands - Register FastMCP tools pr_edit and gh_issue_edit - Disable loki-sc-rules sidecar in dev cluster k8s/logging/loki-values.yaml to eliminate k8s API watch crashloop - Add unit tests for pr/issue edit and REST fallbacks * docs(agent): link PR #187 in task 181 tracking * ci(workflows): gate pull request workflow on unresolved review threads and merge blockers (#188) - Update .github/workflows/ci.yml pull_request triggers to include ready_for_review - Add Verify PR Merge Readiness step to CI workflow calling devops pr check-readiness - Add devops pr check-readiness command and REST fallback for list_prs and list_threads - Add pr_check_readiness FastMCP tool and harden _run_mcp_cmd with mask_secrets - Sanitize output and validate formats in gh run view/list and pr view/checks/diff - Remediate and resolve 11 Copilot review findings across PR #187 * fix(process): preserve GH_TOKEN and GITHUB_REPOSITORY for gh binary execution * fix(repo): prioritize git remote origin before GITHUB_REPOSITORY fallback * fix(github): remediate review findings across pr readiness, sanitization, and rest fallbacks (#181) (#188) * fix(ci): support allow-blocked-state in pr check-readiness for github actions workflow * docs(agent): update task 181 checklist with passing ci checks and resolved review feedback * fix(github): add REST API fallback and rate limit handling for pr review threads (#180) (#189) (#191) * fix(github): add REST API fallback and rate limit handling for pr review threads (#180) (#189) * docs(agent): record PR #191 in task 180 tracking * docs(agent): require concise commit messages stating direct effect of change (#169) (#192) * fix(k8s): harden logging perimeter and scope fluent bit namespaces (#121) (#193) * chore(ci): align core dependencies and synchronize lockfile (#115) (#194) * feat(argo): implement automated gitops drift detection and watch command (#111) * feat(argo): implement automated gitops drift detection and watch command (#111) * fix(argo): address PR #195 review feedback on gitops webhook, secret masking, and baseline persistence * feat(github): declarative branch protection auditor and repository secret synchronization (#197) * feat(github): declarative branch protection auditor and repository secret synchronization * docs(agent): link PR #197 in task-114 tracking file * fix(github): lazily fetch public key during secret sync and isolate tests * chore(release): cut v0.2.17 and finalize release notes (#198) * feat(test): add deterministic async memory and connection pool profiler (#199) Implement deterministic async memory and connection pool profiler under devops test profile-memory (#199) Closes #199
Architectural Summary
Implements real-time container resource telemetry capturing cgroup v2 metrics and Prometheus application scraping on
/metricsendpoints to detect memory leaks, resource exhaustion, and latency anomalies under load for sandboxed workloads.Capabilities Delivered
/sys/fs/cgroup) with automated fallback to container engine inspection (docker inspect/docker stats)./metricsscraper usinghttpx2with URL scheme validation.--warn-memory-pct, default 80%), CPU utilization (--warn-cpu-pct, default 85%), and Prometheus HTTP 5xx error rates (>= 5%).devops sandbox metrics):--jsonexport and--dry-runvalidation.tests/test_sandbox_metrics.py(100% passing).Closes #108