Skip to content

feat(telemetry): w3c traceparent propagation and distributed trace correlation (#109) - #178

Merged
dan-petty merged 2 commits into
release/v0.2.17from
feat/109-sandbox-traces-w3c-waterfall
Sep 12, 2026
Merged

dan-petty merged 2 commits into
release/v0.2.17from
feat/109-sandbox-traces-w3c-waterfall

Conversation

@dan-petty

Copy link
Copy Markdown
Owner

Summary

Closes #109.

Key Capabilities

  1. W3C Trace Context Propagation: Auto-inject standard traceparent headers (00-<trace_id>-<span_id>-01) into HTTP/REST and OpenAPI synthetic probes in src/devops_cli/sandbox/probe.py, capturing trace identifiers in EndpointProbeResult.details and SandboxProbeReport.trace_id.
  2. Distributed Trace Correlation Engine: Centralize terminal waterfall rendering and Jaeger REST API trace querying in src/devops_cli/telemetry/waterfall.py and src/devops_cli/sandbox/engine.py.
  3. Sandbox Traces CLI: Implement devops sandbox traces [identifier] command with Rich terminal Gantt visualizer, supporting options --trace-id, --last, --probe, --jaeger-url, --json, and --dry-run.
  4. Verification: 12 new tests in tests/test_sandbox_traces.py, expanded probe tests in tests/test_sandbox_probe.py, all 10 CI quality gates passing cleanly with >=90% test coverage and complexity <= 10.

@dan-petty dan-petty added this to the v0.2.17 milestone Sep 12, 2026
@dan-petty dan-petty added type/feature Type feature: a new function scope/telemetry OpenTelemetry tracing spans, Prometheus metrics, and Jaeger priority/p1-high Priority P1: high-impact work for the next planned milestone status/in-progress Status In Progress: an owner works on the item labels Sep 12, 2026
@dan-petty
dan-petty marked this pull request as ready for review September 12, 2026 19:59
Copilot AI lite review requested due to automatic review settings September 12, 2026 19:59
@dan-petty
dan-petty merged commit 0c05cfa into release/v0.2.17 Sep 12, 2026
5 checks passed
@dan-petty
dan-petty deleted the feat/109-sandbox-traces-w3c-waterfall branch September 12, 2026 20:01

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical syntax and security issues, plus unresolved trace propagation and correlation defects, block approval.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Adds W3C trace propagation, Jaeger-backed trace retrieval, and the devops sandbox traces waterfall CLI.

Changes:

  • Adds trace context generation, injection, extraction, and probe correlation.
  • Adds shared waterfall rendering and Jaeger query utilities.
  • Updates CLI support, tests, documentation, and task tracking.
File summaries
File Reviewed changes and final findings
tests/test_sandbox_traces.py Adds trace, Jaeger, rendering, and CLI tests. No review findings.
tests/test_sandbox_probe.py Adds probe propagation tests. No review findings.
src/devops_cli/telemetry/waterfall.py Critical (2 votes): Invalid exception syntax at line 117 causes import failure. Critical (2 votes): Caller-controlled Jaeger URLs bypass SSRF/egress validation. Moderate (1 vote): Omitting the URL ignores configured Jaeger settings. Moderate (1 vote): Local spans short-circuit Jaeger retrieval and omit downstream spans.
src/devops_cli/telemetry/tracer.py Refactors waterfall tree construction. No review findings.
src/devops_cli/telemetry/context.py Moderate (1 vote): Trace context validation accepts malformed or zero IDs. Moderate (1 vote): tracestate is not propagated by synthetic probes.
src/devops_cli/telemetry/__init__.py Exports telemetry APIs. No review findings.
src/devops_cli/sandbox/probe.py Moderate (1 vote): OpenAPI discovery does not send propagated headers, leaving that request outside the trace.
src/devops_cli/sandbox/models.py Adds report trace IDs. No review findings.
src/devops_cli/sandbox/engine.py Critical (2 votes): Invalid exception syntax at line 547 prevents import. Moderate (1 vote): Probe trace IDs are not persisted for identifier lookup.
src/devops_cli/lang/en/help.py Adds CLI help text. No review findings.
src/devops_cli/commands/telemetry.py Reuses shared waterfall utilities. No review findings.
src/devops_cli/commands/sandbox.py Critical (2 votes): Invalid exception syntax at line 719 prevents import. Moderate (2 votes): JSON output bypasses secret masking. Moderate (3 votes): --probe is ignored without an identifier (lines 790 and 793). Nit (2 votes): The command lacks telemetry spans and invocation metrics. Moderate (1 vote): External span names are not escaped for Rich markup. Moderate (1 vote): Jaeger URL credentials are rendered verbatim.
README.md Documents the new command. No review findings.
docs/commands/sandbox.md Documents sandbox traces usage. No review findings.
docs/CLI_REFERENCE.md Updates the CLI reference. No review findings.
docs/agent/tasks/task-109-sandbox-traces-w3c-waterfall.md Tracks implementation details. No review findings.
docs/agent/task.md Updates the task index. No review findings.
Review details

Suppressed comments (9)

src/devops_cli/commands/sandbox.py:793

  • The identifier is only retained for display here; when no trace ID is supplied, _resolve_spans_for_traces falls back to the globally most recent buffered trace. Because probe results are not persisted into the sandbox instance metadata, devops sandbox traces <identifier> can display an unrelated sandbox's trace instead of the requested instance's trace.
    active_id, spans = _resolve_spans_for_traces(resolved_trace_id, last, jaeger_url)

src/devops_cli/commands/sandbox.py:655

  • node.name can come from a Jaeger response or other external span data, but it is interpolated into Rich markup without escaping. An operation name containing Rich tags can alter the table rendering or break the output; escape untrusted span names before adding the intentional [bold] tags (and apply the same rule to other external values rendered in this view).
    for node, prefix in flattened:
        name_display = f"{prefix}[bold]{node.name}[/bold]"

src/devops_cli/commands/sandbox.py:682

  • The Jaeger URL is rendered verbatim in terminal output, so a value such as http://user:password@host supplied through --jaeger-url leaks credentials. Mask URI credentials before building the displayed Jaeger link, following the explicit masking used by sandbox metrics scraping.
    j_url = (jaeger_url or "http://localhost:16686").rstrip("/")

    print_info(
        f"[bold]Trace Summary:[/bold] {len(spans)} span(s), total duration {format_latency(total_dur_ms)} | "
        f"[dim]Jaeger: {j_url}/trace/{trace_id}[/dim]",

src/devops_cli/sandbox/engine.py:547

  • This lookup expects metadata["trace_id"], but WorkloadSandboxEngine.probe() only returns the report and never writes report.trace_id back to the registered SandboxInstance. Consequently traces(identifier=...) cannot find the association and falls back to the latest/unrelated trace; persist the report trace ID or use a dedicated trace index.
        target_trace_id = trace_id
        if not target_trace_id and identifier:
            try:
                instances = self.status(identifier=identifier)
                if instances:
                    target_trace_id = instances[0].metadata.get("trace_id")
            except SandboxError, OSError:

src/devops_cli/sandbox/probe.py:367

  • Although run_sandbox_probes now creates a parent span, OpenAPI discovery still performs a raw HTTP GET in _extract_safe_openapi_endpoints without the propagated headers; only the calls routed through probe_http are correlated. This leaves part of an OpenAPI probe outside the trace. Pass the generated or active propagation headers into the discovery request as well.
    with trace_span(
        "sandbox.probe",
        attributes={
            "sandbox.target": target_display,
            "sandbox.instance_id": str(instance_id or ""),
        },
    ):
        ctx = get_current_span_context()
        active_trace_id = ctx.get("trace_id") if ctx else None

        for host, port in target_endpoints:
            _dispatch_probes_for_port(
                host=host,
                port=port,
                protocols=selected_protocols,
                http_paths=http_paths or _DEFAULT_HTTP_PATHS,
                expected_statuses=expected_statuses,
                regex=regex,
                timeout=timeout,
                latency_budget_ms=latency_budget_ms,
                collector=all_results,
            )

src/devops_cli/telemetry/context.py:59

  • Only the field lengths are checked here, so values such as zz-<32 chars>-<16 chars>-gg and all-zero IDs are accepted as valid W3C context. That can cause malformed traceparents to be recorded or propagated. Validate the version, lowercase hexadecimal fields, flags, and non-zero trace/span IDs before returning.
    if len(parts) == 4 and len(parts[1]) == 32 and len(parts[2]) == 16:
        return {"trace_id": parts[1], "parent_span_id": parts[2], "trace_flags": parts[3]}

src/devops_cli/telemetry/context.py:48

  • The helper exposes tracestate only as an optional caller argument, but probe_http never supplies it and the active span context has no tracestate value. Synthetic probes therefore do not automatically propagate tracestate, despite issue #109's proposed W3C Trace Context changes. Carry tracestate through the active context or narrow the documented scope to traceparent only.
    if tracestate and "tracestate" not in result:
        result["tracestate"] = tracestate

src/devops_cli/telemetry/waterfall.py:110

  • When --jaeger-url is omitted, this passes None to the resolver, whose fallback is hard-coded to localhost. That ignores the configured settings.jaeger.url used by the existing telemetry commands, so installations with a non-default Jaeger endpoint cannot retrieve traces unless every invocation repeats the override.
    url = (jaeger_url or "http://localhost:16686").rstrip("/")
    api_url = f"{url}/api/traces/{trace_id}"

src/devops_cli/telemetry/waterfall.py:131

  • Because the local buffer is checked first and returned immediately, a trace from --probe stops here as soon as the local sandbox.probe span exists; the Jaeger fallback below is never queried. That omits downstream service spans and defeats the cross-service waterfall. For a supplied trace ID, query Jaeger as well and merge/deduplicate by span ID, falling back to local spans only when remote data is unavailable.
    spans = get_trace_spans(trace_id)
    if spans:
        resolved_id = str(spans[0].get("traceId", trace_id or "unknown"))
        return resolved_id, spans
  • Files reviewed: 17/17 changed files
  • Comments generated: 7
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

instances = engine.status(identifier=identifier)
if instances:
target_obj = instances[0]
except SandboxError, OSError:
instances = self.status(identifier=identifier)
if instances:
target_trace_id = instances[0].metadata.get("trace_id")
except SandboxError, OSError:
Comment on lines +109 to +113
url = (jaeger_url or "http://localhost:16686").rstrip("/")
api_url = f"{url}/api/traces/{trace_id}"
try:
with httpx2.Client(timeout=timeout) as client:
resp = client.get(api_url)
if resp.status_code != 200:
return []
return normalize_jaeger_spans(resp.json())
except httpx2.RequestError, ValueError, OSError:
"span_count": len(spans),
"waterfall": [n.to_dict() for n in tree],
}
typer.echo(json.dumps(payload, indent=2))
Comment on lines +790 to +791
if probe and identifier:
target_display, resolved_trace_id = _execute_sandbox_probe_before_trace(identifier)
Comment on lines +773 to +775
"""Visualize distributed trace waterfall and cross-service latency for sandbox workloads."""
set_dry_run(dry_run)
if is_dry_run():
dan-petty added a commit that referenced this pull request Sep 14, 2026
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority/p1-high Priority P1: high-impact work for the next planned milestone scope/telemetry OpenTelemetry tracing spans, Prometheus metrics, and Jaeger status/in-progress Status In Progress: an owner works on the item type/feature Type feature: a new function

Projects

No open projects

Development

Successfully merging this pull request may close these issues.

2 participants