Skip to content

Reduce agent telemetry hook overhead without reducing coverage - #20387

Merged
James Newton-King (JamesNK) merged 11 commits into
mainfrom
ievangelist-telemetry-performance-fix
Sep 25, 2026
Merged

James Newton-King (JamesNK) merged 11 commits into
mainfrom
ievangelist-telemetry-performance-fix

Conversation

@IEvangelist

@IEvangelist David Pine (IEvangelist) commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Description

Preserves wildcard agent-hook coverage and all currently eligible Aspire telemetry while removing shell startup and synchronous upload waits.

  • Both hook and uploader modes run through AgentTelemetryCommand and normal command dispatch. InitializeTelemetryOnStartup defaults to true; the agent command defers provider creation and enrichment until an eligible event exists. Existing first-run and generic invocation-span rules are preserved.
  • Skill names and reference paths come from the embedded bundle's skill-manifest.json, read in memory with the existing manifest types and source-generated serializer. The shipped inventory preserves all 7 skills and 33 references. MCP tool names still come from the embedded canonical hook because the manifest does not contain a tool inventory.
  • Hook environment-variable reads use injected IEnvironment; hook tests run in-process without changing global environment state. A documented setting bounds input before parsing.
  • Eligible telemetry is persisted through Azure Monitor Exporter's existing disk-backed storage. An independent CLI uploader keeps its existing batching/retry machinery alive until the backlog drains.
  • Legacy Aspire registrations migrate idempotently without removing unrelated user hooks. The latest main merge preserves shell completions and the v0.0.3 skills bundle.

Fixes #20329
Closes #20042

Coordinated OpenTelemetry upgrade

The committed upgrade supersedes closed draft #20042 and consistently uses the newest releases published at least seven days before September 23, 2026:

Packages Version NuGet publication date (UTC)
Console, InMemory, OTLP exporters; Extensions.Hosting 1.18.0 August 21
AspNetCore, Http, Runtime, SqlClient instrumentation 1.18.0 August 21
GrpcNetClient instrumentation 1.18.0-beta.1 August 21
Azure Monitor Exporter 1.9.0 September 5

The 1.19.x releases were too recent for that age requirement and are not the target. The GrpcNetClient approved-feed import succeeded in run 3085688, and full solution restore succeeded against configured feeds. No quarantine was bypassed. Existing Blazor playground-specific overrides from #20339 are unchanged. Seq's generated configuration schema was refreshed for the added OTLP properties.

Breaking changes

OpenTelemetry 1.18 reduces the default maximum serialized OTLP request from 128 MiB to 64 MiB. Oversized batches are dropped. Consumers relying on the previous limit can configure:

builder.Services.Configure<OpenTelemetry.Exporter.OtlpExporterOptions>(options =>
{
    options.MaxRequestSizeBytes = 128 * 1024 * 1024;
});

The default maximum OTLP response size is 4 MiB. Generated ServiceDefaults inherit updated versions; existing customer projects are not rewritten. Ordinary CLI shutdown behavior is explicitly preserved despite the Azure Monitor upgrade.

User-facing usage

After installing the updated CLI, refresh agent configuration:

aspire agent init

Claude retains matcher: "*"; Copilot retains unfiltered postToolUse. Both directly execute aspire agent telemetry --hook without PowerShell/Bash. Compatibility scripts are taken unchanged from the canonical bundle.

ASPIRE_AGENT_TELEMETRY_MAX_PAYLOAD_CHARACTERS configures the native input bound: default 65,536 UTF-16 characters, range 1–1,048,576. Oversized input is drained without retention; invalid values produce a diagnostic without breaking the agent.

Validation

  • Review refactor: 370 tests passed, one Linux-only skip, covering startup/completions, normal command routing, deferred provider/enrichment initialization, opt-out, all three event categories, and existing telemetry behavior.
  • Manifest change: 137 focused tests passed, including archive/JSON validation, canonical reporting-set parity, hook classification, and skills bundle regressions.
  • Final Windows x64 Native AOT publish passed after the manifest change.
  • The real cross-process lease-expiry recovery test is now marked [OuterloopTest]; fast persistence and uploader-lifecycle coverage remains in regular CI. The real recovery scenario passed before this scheduling-only change.
  • Coordinated dependency upgrade: full solution restore, Hosting/template builds, generated ServiceDefaults/MAUI version verification, and 21 Seq tests across .NET 8/9/10 passed. Seq stabilization packaging passed. Restore reported existing unrelated vulnerability advisories.
  • Real Copilot CLI 1.0.87-0, isolated COPILOT_HOME: postToolUse with exec/args ran its recorder after a view call.
  • Performance trade-off: normal command dispatch measured 145.4 ms median and 210.7 ms p95 for unrelated native hooks over 25 local Windows launches; the old PowerShell sample was approximately 337–460 ms. The earlier pre-host shortcut measured 52.3 ms median but was removed in response to review. These are direct-process samples, not a zero-cost guarantee.
  • Linux/macOS runtime performance was not tested locally.

Security considerations

The hook processes bounded untrusted JSON and launches an independent uploader. Catalog inputs come from embedded release-verified resources, not mutable user-installed skills/scripts. Only manifest-listed references/ files are reference events; evals and scripts are excluded. No new listener, ingestion endpoint, raw-payload storage, or telemetry category is introduced. Direct argument vectors avoid shell interpretation. Existing exporter storage and process-isolation helpers are reused. Security review should cover classification parity, configuration ownership, and detached-process lifetime.

Delivery remains subject to disk failures, exporter limits, retention, and permanent ingestion errors. Interrupted uploads may stay leased for several minutes; at-least-once delivery permits duplicates. Environment opt-out applies at process launch, not retroactively to running processes.

Checklist

  • Is this feature complete?
    • Yes. Ready to ship.
    • No. Follow-up changes expected.
  • Are you including unit tests for the changes and scenario tests if relevant?
    • Yes
    • No
  • Did you add public API?
    • Yes
      • If yes, did you have an API Review for it?
        • Yes
        • No
      • Did you add <remarks /> and <code /> elements on your triple slash comments?
        • Yes
        • No
    • No
  • Does the change make any security assumptions or guarantees?
    • Yes
      • If yes, have you done a threat model and had a security review?
        • Yes
        • No
    • No

@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 20387

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 20387"

@github-actions

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

The generated Copilot hook uses unsupported exec and args fields, preventing the hook from running.

Get a fresh assessment by requesting another Copilot review.

Review effort: Balanced
Findings: 1 High severity

Open (1)
What changed in this PR

Reduces agent telemetry hook latency while preserving Aspire event coverage and adding durable background uploads.

Changes:

  • Replaces shell-based hooks with native classification and execution.
  • Adds disk-backed telemetry persistence and an independent uploader.
  • Updates exporter dependencies and comprehensive regression tests.
File Description
tests/​Aspire.Cli.Tests/​Utils/​MockHttpMessageHandler.cs Adds asynchronous response support.
tests/​Aspire.Cli.Tests/​Telemetry/​AgentTelemetryUploaderTests.cs Tests uploader locking and cancellation.
tests/​Aspire.Cli.Tests/​Telemetry/​AgentTelemetryPersistenceTests.cs Tests persistence and recovery behavior.
tests/​Aspire.Cli.Tests/​Agents/​TelemetryHookScriptTests.cs Verifies native/script classification parity.
tests/​Aspire.Cli.Tests/​Agents/​TelemetryHookConfiguratorTests.cs Tests native hook configuration and migration.
tests/​Aspire.Cli.Tests/​Agents/​AgentTelemetryHookTests.cs Tests native hook parsing and opt-out behavior.
src/​Aspire.Cli/​Telemetry/​TelemetryManager.cs Configures exporter persistence.
src/​Aspire.Cli/​Telemetry/​AgentTelemetryUploader.cs Implements detached backlog draining.
src/​Aspire.Cli/​Program.cs Adds fast hook and uploader paths.
src/​Aspire.Cli/​Agents/​Hooks/​TelemetryHookConfigurator.cs Registers and migrates native hooks.
src/​Aspire.Cli/​Agents/​Hooks/​AgentTelemetryHook.cs Implements native event classification.
eng/​Versions.props Updates telemetry dependencies.
docs/​open-telemetry-architecture.md Documents agent telemetry persistence.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🔵 Needs a closer look

The coordinated dependency upgrade is incomplete, and a three-minute recovery test remains in the regular test suite.

Review effort: Balanced
Findings: None

Resolved since last review (1)
Previously missed (2)

In code that hasn't changed since last review

Medium severity OpenTelemetry packages remain on inconsistent mixed versions

eng/​Versions.props:57

The coordinated upgrade in the PR description targets OpenTelemetry.Extensions.Hosting 1.19.1 and the rest of the OpenTelemetry family at 1.19.x, but this line sets Hosting to 1.18.0 while the sibling properties remain at 1.17.0 (and the hard-coded Console/InMemory/GrpcNetClient packages are unchanged). This leaves the partial mixed-version upgrade that the PR says it will supersede; update the full family to the stated targets before merging.

Medium severity Mark three-minute blob lease expiry test as outerloop

tests/​Aspire.Cli.Tests/​Telemetry/​AgentTelemetryPersistenceTests.cs:32

This test intentionally waits for the exporter's three-minute blob lease to expire, so leaving it in the regular suite adds at least three minutes to every selected Aspire.Cli.Tests run. Long-running tests are marked OuterloopTest in this project (for example, Mcp/E2E/McpDocsE2ETests.cs:20 and Projects/JavaAppHostToolchainResolverTests.cs:371); mark this test outerloop or replace the wall-clock lease expiry with a deterministic hook.

@github-actions

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

Use OpenTelemetry 1.18.0 and GrpcNetClient 1.18.0-beta.1 while retaining Azure Monitor Exporter 1.9.0. Document OTLP request-size changes. GrpcNetClient approved-feed import tracked by run 3085688.

Co-authored-by: Copilot App <[email protected]>
@github-actions

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Package versions contradict the PR description, detached uploader startup lacks direct coverage, and a regular test adds a three-minute delay.

Get a fresh assessment by requesting another Copilot review.

Review effort: Balanced
Findings: 1 Low severity

Open (1)
Previously missed (2)

In code that hasn't changed since last review

Medium severity Missing EnsureRunningAsync launch and Unix path coverage

src/​Aspire.Cli/​Telemetry/​AgentTelemetryUploader.cs:63

No test exercises EnsureRunningAsync; the new tests invoke DrainAsync directly. As a result, the critical platform-specific path here—DCP resolution and lease handoff on Unix, detached process startup, command arguments, and environment filtering—can break while all added tests still pass. Add focused launch coverage (including the Unix path) that starts the uploader through EnsureRunningAsync and verifies the child drains persisted data after the producer exits.

Medium severity Test waits three minutes for real lease expiration

tests/​Aspire.Cli.Tests/​Telemetry/​AgentTelemetryPersistenceTests.cs:32

This regular test deliberately waits for Azure Monitor Exporter's three-minute blob lease to expire, so it adds at least three minutes to every Aspire.Cli.Tests run on each platform. That is a substantial CI regression for a single test. Move this scenario to the outer loop (or introduce a test seam that avoids real-time lease expiry).

Comment thread Directory.Packages.props Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

@IEvangelist David Pine (IEvangelist) added the breaking-change Issue or PR that represents a breaking API or functional change over a prerelease. label Sep 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

Include the new OTLP request and response size options for logs and traces so schema validation and dependent CI builds succeed.

Co-authored-by: Copilot App <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🔵 Needs a closer look

The detached uploader launch and parent-survival path lacks process-level regression coverage.

Review effort: Balanced
Findings: None

Resolved since last review (1)
Previously missed (1)

In code that hasn't changed since last review

Medium severity Add process-level test for EnsureRunningAsync detached uploader recovery

src/​Aspire.Cli/​Telemetry/​AgentTelemetryUploader.cs:23

The tests exercise DrainAsync directly, but none invokes EnsureRunningAsync; even the cross-process recovery test creates its own RemoteExecutor child. Therefore command construction, Windows detached launch, Unix DCP resolution/layout-lease handoff, and survival after the producer exits can all regress while the suite remains green. Add a process-level test that starts the uploader through this method and verifies the detached child drains persisted data after its producer exits.

@github-actions

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

Move standard input into ConsoleEnvironment and initialize providers only when the selected command needs them.

Co-authored-by: Copilot <[email protected]>
@github-actions

This comment has been minimized.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🔵 Needs a closer look

Cross-process telemetry persistence, detached process lifetime, and security-sensitive hook parsing warrant final human and security review.

Review effort: Balanced
Findings: None

@github-actions

Copy link
Copy Markdown
Contributor

Tests selector

Selects the full PR test matrix + all PR-gated jobs (ALL) — a rule matching 'Directory.Packages.props' selects ALL


Selection computed for commit 52be8e3.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🔵 Needs a closer look

The detached Unix uploader launch path lacks integration coverage, leaving a central delivery path unverified.

Review effort: Balanced
Findings: None

Previously missed (1)

In code that hasn't changed since last review

Medium severity Add Unix uploader end-to-end test for detached drain backlog clearing

src/​Aspire.Cli/​Telemetry/​AgentTelemetryUploader.cs:68

The new Unix uploader path (DCP resolution, layout-lease handoff, and detached child launch) is not exercised by the added tests: they call DrainAsync directly and never invoke EnsureRunningAsync. A regression here would leave every persisted event queued indefinitely on Linux/macOS even though the in-process drain tests pass. Add an integration/E2E test that persists an event, starts the uploader through this path, lets the producer exit, and verifies the detached --drain process clears the backlog.

@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

@JamesNK
James Newton-King (JamesNK) merged commit 9be381f into main Sep 25, 2026
833 of 837 checks passed
@microsoft-github-policy-service microsoft-github-policy-service Bot added this to the 14.0 milestone Sep 25, 2026
aspire-repo-bot Bot added a commit to microsoft/aspire.dev that referenced this pull request Sep 25, 2026
…hange

Documents user-facing changes from microsoft/aspire#20387:
- Native aspire agent telemetry --hook execution (no shell wrapper)
- ASPIRE_AGENT_TELEMETRY_MAX_PAYLOAD_CHARACTERS environment variable
- Breaking change: OpenTelemetry 1.18 default OTLP request size drops
  from 128 MiB to 64 MiB, with the OtlpExporterOptions workaround

Co-authored-by: Copilot <[email protected]>
@aspire-repo-bot

Copy link
Copy Markdown
Contributor

Pull request created: #1751

Generated by PR Documentation Check · copilot · auto · 121.2 AIC · ⌖ 10.5 AIC · ⊞ 18.7K

@aspire-repo-bot

Copy link
Copy Markdown
Contributor

📝 Documentation has been drafted in microsoft/aspire.dev#1751 targeting release/13.6.

Triggered signals (6): cli_command_file_changed (AgentCommand.cs, AgentTelemetryCommand.cs modified), cli_option_added (new hidden --hook Option in AgentTelemetryCommand.cs), pr_body_has_cli_flag_mention (aspire agent telemetry --hook), pr_body_has_user_facing_section (explicit 'User-facing usage' heading describing aspire agent init refresh, hook exec behavior, and ASPIRE_AGENT_TELEMETRY_MAX_PAYLOAD_CHARACTERS), pr_body_has_security_marker (Security considerations section), pr_label_breaking_change (breaking-change label + explicit Breaking changes section on OTLP MaxRequestSizeBytes default drop from 128 MiB to 64 MiB).

Documented in this draft:

  • src/frontend/src/content/docs/whats-new/aspire-13-6.mdx: new '#### Faster agent telemetry hook' subsection under CLI enhancements (native --hook exec instead of shell wrapper, unchanged wildcard coverage, aspire agent init refresh instructions, new env var), and a new '#### OpenTelemetry packages upgraded, smaller default OTLP request size' breaking-change subsection with the OtlpExporterOptions.MaxRequestSizeBytes workaround. Updated intro bullets and upgrade Aside to reference both changes.
  • src/frontend/src/content/docs/reference/cli/microsoft-collected-cli-telemetry.mdx: updated 'AI agent skill usage' section to describe the native-exec hook and the new max-payload environment variable.

Target branch resolution: candidate_source=pr_milestone (milestone 14.0) → candidate release/14.0 doesn't exist on aspire.dev; target_resolution=latest_release_fallback selected release/13.6, the latest available release branch.

Note

This draft PR needs human review before merging.

@IEvangelist

Copy link
Copy Markdown
Member Author

/backport to release/13.6

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to release/13.6 (link to workflow run)

@aspire-repo-bot

Copy link
Copy Markdown
Contributor

David Pine (@IEvangelist) backporting to release/13.6 failed, the patch most likely resulted in conflicts. Please backport manually!

git am output
$ git am --3way --empty=keep --ignore-whitespace --keep-non-patch changes.patch

Applying: Reduce agent telemetry hook overhead without reducing coverage
Using index info to reconstruct a base tree...
M	eng/Versions.props
M	src/Aspire.Cli/Agents/Hooks/TelemetryHookConfigurator.cs
M	src/Aspire.Cli/Program.cs
M	tests/Aspire.Cli.Tests/Agents/TelemetryHookScriptTests.cs
Falling back to patching base and 3-way merge...
Auto-merging eng/Versions.props
Auto-merging src/Aspire.Cli/Agents/Hooks/TelemetryHookConfigurator.cs
Auto-merging src/Aspire.Cli/Program.cs
Auto-merging tests/Aspire.Cli.Tests/Agents/TelemetryHookScriptTests.cs
Applying: Use canonical telemetry catalog and configure hook payload limits
Applying: Align OpenTelemetry packages on releases older than seven days
Applying: Regenerate Seq configuration schema for OpenTelemetry 1.18
Applying: Address agent telemetry review with command opt-in and manifest catalog
Using index info to reconstruct a base tree...
M	src/Aspire.Cli/Program.cs
M	tests/Aspire.Cli.Tests/Utils/CliTestHelper.cs
Falling back to patching base and 3-way merge...
Auto-merging src/Aspire.Cli/Program.cs
CONFLICT (content): Merge conflict in src/Aspire.Cli/Program.cs
Auto-merging tests/Aspire.Cli.Tests/Utils/CliTestHelper.cs
error: Failed to merge in the changes.
hint: Use 'git am --show-current-patch=diff' to see the failed patch
hint: When you have resolved this problem, run "git am --continue".
hint: If you prefer to skip this patch, run "git am --skip" instead.
hint: To restore the original branch and stop patching, run "git am --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Patch failed at 0005 Address agent telemetry review with command opt-in and manifest catalog
Error: The process '/usr/bin/git' failed with exit code 128

Link to workflow output

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-cli breaking-change Issue or PR that represents a breaking API or functional change over a prerelease.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Claude Code telemetry hook runs (blocking) on every tool call — register with a narrow matcher and async

4 participants