Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/workflows/build-samples.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ on:
- "dotnet-ai/agent-framework-incident-triage/**"
- "dotnet-ai/mcp-server-csharp-dotnet/**"
- "dotnet-ai/microsoft-extensions-ai-evaluation/**"
- "dotnet-ai/opentelemetry-ai-observability/**"
- "dotnet-aspire/orchestrate-distributed-system/**"
- "software-architecture/architecture-testing-dotnet/**"
- "distributed-systems/transactional-outbox-ef-core/**"
Expand Down Expand Up @@ -43,6 +44,7 @@ on:
- "dotnet-ai/agent-framework-incident-triage/**"
- "dotnet-ai/mcp-server-csharp-dotnet/**"
- "dotnet-ai/microsoft-extensions-ai-evaluation/**"
- "dotnet-ai/opentelemetry-ai-observability/**"
- "dotnet-aspire/orchestrate-distributed-system/**"
- "software-architecture/architecture-testing-dotnet/**"
- "distributed-systems/transactional-outbox-ef-core/**"
Expand Down Expand Up @@ -2139,3 +2141,26 @@ jobs:
dotnet run --project src/EvaluationRunner --configuration Release --no-build --no-restore -- --repaired . "$RUNNER_TEMP/evaluation-repaired.md"
diff -u reports/candidate-scorecard.md "$RUNNER_TEMP/evaluation-candidate.md"
diff -u reports/repaired-scorecard.md "$RUNNER_TEMP/evaluation-repaired.md"

test-opentelemetry-ai-observability:
name: Test .NET AI OpenTelemetry sample
runs-on: ubuntu-latest
timeout-minutes: 12

defaults:
run:
working-directory: dotnet-ai/opentelemetry-ai-observability

steps:
- name: Check out repository
uses: actions/checkout@v5
with:
persist-credentials: false

- name: Install verified .NET SDK
uses: actions/setup-dotnet@v5
with:
dotnet-version: "10.0.404"

- name: Verify offline traces, metrics, and payload exclusion
run: bash verify.sh --offline
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Each sample folder contains a focused implementation of one tutorial topic. The
| [`dotnet-ai/agent-framework-incident-triage`](dotnet-ai/agent-framework-incident-triage/) | Evidence-first Microsoft Agent Framework sample with read-only tools, deterministic incident evidence, `AgentSession` reuse, and correlation-vs-causation boundaries | [Microsoft Agent Framework Tutorial in C#: Build a Tool-Using AI Agent](https://www.dotnet-guide.com/tutorials/dotnet-ai/agent-framework-incident-triage/) |
| [`dotnet-ai/mcp-server-csharp-dotnet`](dotnet-ai/mcp-server-csharp-dotnet/) | .NET 10 MCP stdio server with three read-only tools, deterministic JSON-backed data, real client discovery/invocation, protocol error verification, and deterministic tests | [Build Your First MCP Server in C# and .NET](https://www.dotnet-guide.com/tutorials/dotnet-ai/mcp-server-csharp-dotnet/) |
| [`dotnet-ai/microsoft-extensions-ai-evaluation`](dotnet-ai/microsoft-extensions-ai-evaluation/) | Offline prompt regression testing across 12 incidents and five hard checks, with optional live evaluation | Tutorial in preparation. [Browse .NET AI tutorials](https://www.dotnet-guide.com/tutorials/dotnet-ai/) |
| [`dotnet-ai/opentelemetry-ai-observability`](dotnet-ai/opentelemetry-ai-observability/) | .NET 10 traces and metrics for model calls, tool execution, and a downstream Evidence API, with deterministic tests and optional Jaeger and live-model runs | Tutorial in preparation. [Browse .NET AI tutorials](https://www.dotnet-guide.com/tutorials/dotnet-ai/) |
| [`dotnet-aspire/orchestrate-distributed-system`](dotnet-aspire/orchestrate-distributed-system/) | Minimal Aspire AppHost coordinating a web project and API with service discovery and startup ordering | [Aspire in .NET: Orchestrate, Run, and Deploy a Distributed System from One App Host](https://www.dotnet-guide.com/tutorials/dotnet-aspire/orchestrate-distributed-system/) |
| [`software-architecture/architecture-testing-dotnet`](software-architecture/architecture-testing-dotnet/) | Minimal NetArchTest.eNhancedEdition rule that prevents Domain from depending on outer layers | [Architecture Testing in .NET: Enforce Layer and Module Boundaries with NetArchTest and ArchUnitNET](https://www.dotnet-guide.com/tutorials/software-architecture/architecture-testing-dotnet/) |
| [`distributed-systems/transactional-outbox-ef-core`](distributed-systems/transactional-outbox-ef-core/) | Minimal EF Core and SQLite demonstration that saves business state and an outbox message atomically, then publishes it through a one-shot relay | [Transactional Outbox Pattern in .NET with EF Core (.NET 10): Fix the Dual-Write Problem](https://www.dotnet-guide.com/tutorials/distributed-systems/transactional-outbox-ef-core/) |
Expand Down
2 changes: 2 additions & 0 deletions dotnet-ai/opentelemetry-ai-observability/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/results.*/
__pycache__/
10 changes: 10 additions & 0 deletions dotnet-ai/opentelemetry-ai-observability/NuGet.Config
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<configuration>
<packageSources>
<clear />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
</packageSources>
<auditSources>
<clear />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
</auditSources>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<Solution>
<Project Path="src/ObservabilityLab/ObservabilityLab.csproj" />
</Solution>
55 changes: 55 additions & 0 deletions dotnet-ai/opentelemetry-ai-observability/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Observe .NET AI Apps with OpenTelemetry

Follow one request through ASP.NET Core, `IChatClient`, tool invocation, a custom evidence lookup span, and a downstream HTTP service. This .NET 10 companion runs Triage and Evidence as two separate Kestrel processes from one executable.

| Scenario | Evidence API | Triage API | What to inspect |
| --- | --- | --- | --- |
| Healthy | 200 | 200 | Eight connected spans across two services |
| Slow | 200 after a 1.2 s delay | 200 | Evidence accounts for the extra dependency and tool time |
| Failed | 503 | 200 with `evidenceAvailable: false` | Trace shows the downstream failure and the controlled response |

## Run the offline verification

Use .NET SDK 10.0.404, Bash, and Python 3.10+ on Linux. Package restore uses NuGet. The run uses a scripted chat client and a local SDK exporter.

```bash
cd dotnet-ai/opentelemetry-ai-observability
bash verify.sh --offline
```

The verifier runs two requests per scenario, checks the trace structure and metrics, scans both signals for synthetic payload markers, and runs a separate capture-enabled build to prove the scanner can detect known content. Look for `results.*/verification.log`.

## Inspect the traces in Jaeger

```bash
docker compose -f docker/compose.yaml up -d
bash verify.sh --jaeger http://127.0.0.1:16686 http://127.0.0.1:4318/v1/traces
```

Open [Jaeger](http://127.0.0.1:16686) and use the trace IDs in the generated `jaeger-summary.json`. Open the slow trace and follow **Execute Tool → Evidence Lookup → HTTP GET → Evidence API**. In the failed trace, compare the Evidence 503 with the Triage 200. Both are part of one trace.

The Jaeger backend stores traces in memory. Use `docker compose -f docker/compose.yaml down` when you finish browsing.

## Optional live run

Start [llama.cpp b7124](https://github.com/ggml-org/llama.cpp/releases/tag/b7124) with the [Qwen3-0.6B Q8_0 model](https://huggingface.co/Qwen/Qwen3-0.6B-GGUF/tree/23749fefcc72300e3a2ad315e1317431b06b590a). Keep Jaeger running and use a second terminal for the verifier.

```bash
llama-server --host 127.0.0.1 --port 8080 --model /path/to/Qwen3-0.6B-Q8_0.gguf \
--alias qwen3-0.6b --ctx-size 2048 --threads 4 --parallel 1 \
--jinja --chat-template-kwargs '{"enable_thinking":false}'
```

```bash
bash verify.sh --live http://127.0.0.1:16686 http://127.0.0.1:4318/v1/traces \
http://127.0.0.1:8080/v1/chat/completions qwen3-0.6b
```

The live adapter maps the first model's schema-constrained action to a .NET function call and supplies the resulting evidence to a second model request. Its two model HTTP calls add two spans per trace. Token counts in the live probe come from the provider.

## Further reading

- [Trace contract](docs/trace-contract.md)
- [Metrics and telemetry privacy](docs/metrics-and-privacy.md)
- [Verified environment](docs/verified-environment.md)
- [.NET AI tutorials on DOTNET GUIDE](https://www.dotnet-guide.com/tutorials/dotnet-ai/)
12 changes: 12 additions & 0 deletions dotnet-ai/opentelemetry-ai-observability/docker/compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
services:
jaeger:
image: cr.jaegertracing.io/jaegertracing/jaeger@sha256:3823829974ccfc2485d2e48b165579091f32295022ae80ca49704e2f4834116e
command: ["--config", "/dotnet-guide-jaeger.yaml"]
environment:
DG_JAEGER_QUERY_LISTEN: 0.0.0.0:16686
DG_JAEGER_OTLP_LISTEN: 0.0.0.0:4318
ports:
- "127.0.0.1:16686:16686"
- "127.0.0.1:4318:4318"
volumes:
- "./jaeger.yaml:/dotnet-guide-jaeger.yaml:ro"
35 changes: 35 additions & 0 deletions dotnet-ai/opentelemetry-ai-observability/docker/jaeger.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
service:
extensions: [jaeger_storage, jaeger_query]
pipelines:
traces:
receivers: [otlp]
exporters: [jaeger_storage_exporter]
telemetry:
metrics:
level: none
logs:
level: info

extensions:
jaeger_storage:
backends:
local_traces:
memory:
max_traces: 1000
jaeger_query:
storage:
traces: local_traces
http:
endpoint: "${env:DG_JAEGER_QUERY_LISTEN:-127.0.0.1:16686}"
grpc:
endpoint: 127.0.0.1:0

receivers:
otlp:
protocols:
http:
endpoint: "${env:DG_JAEGER_OTLP_LISTEN:-127.0.0.1:4318}"

exporters:
jaeger_storage_exporter:
trace_storage: local_traces
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Metrics and telemetry privacy

| Instrument | Unit | Use |
| --- | --- | --- |
| `http.server.request.duration` | seconds | Compare the Triage and Evidence server views. Route templates and status codes are dimensions. |
| `http.client.request.duration` | seconds | Inspect dependency time and downstream HTTP status. When exporting to Jaeger, the exporter POST is a separate series from the Evidence GET. |
| `gen_ai.client.operation.duration` | seconds | Measure the two chat operations. |
| `gen_ai.client.token.usage` | tokens | Measure reported input and output token usage. The offline counts are synthetic. |
| `dotnet_guide.evidence.lookup.duration` | seconds | Group by `available` or `unavailable`. The unavailable series count measures failed lookups. |

The AI instrument names describe the pinned Microsoft.Extensions.AI version. The demo exports its metrics to local JSON. Jaeger is used for traces. The console proofs check counts, tags, units, and timing ranges.

The normal pipeline explicitly sets `EnableSensitiveData = false`. The offline harness sets the framework capture environment flag to true and requires the synthetic prompt, answer, tool argument, tool result, and evidence markers to stay out of trace and metric snapshots. A separate compile-time control captures synthetic content so the test verifies that all five markers can be found. The control and its artifacts live in test output. This verifies the sample's instrumented paths under the tested configuration. It is not a guarantee about every possible request, provider, or exporter.

HTTP response proofs include artificial sample content for test assertions. Use the SDK and Jaeger trace captures to inspect exported telemetry.
24 changes: 24 additions & 0 deletions dotnet-ai/opentelemetry-ai-observability/docs/trace-contract.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Trace contract

Triage receives `POST /triage/{incidentId}` and uses `UseFunctionInvocation().UseOpenTelemetry(...)` to observe the two model calls and the evidence tool. The custom `dotnet-guide.triage.evidence_lookup` span wraps the HTTP dependency call. Evidence handles `GET /evidence/{incidentId}` in its own process.

```mermaid
flowchart TD
Triage["Triage API"] --> Flow["orchestrate_tools"]
Flow --> First["First model call"]
Flow --> Tool["Evidence tool"]
Flow --> Last["Final model call"]
Tool --> Lookup["Evidence lookup"]
Lookup --> Client["Outbound HTTP"]
Client --> Evidence["Evidence API"]
```

All eight scripted spans have one trace ID and distinct span IDs. The two services report independent service names. Evidence's server span has the outbound HTTP span ID as its parent. The live probe adds an HTTP client child below each model call.

| Scenario | Expected behavior |
| --- | --- |
| Healthy | Evidence records E-201 and E-101. The scripted answer states the cause is unconfirmed. The custom lookup has status `Ok`. |
| Slow | The Evidence API waits 1.2 s and returns the healthy evidence. The duration increase is visible in the downstream span and aggregate metrics. |
| Failed | An empty HTTP 503 marks the Evidence server, outbound client, lookup, and tool spans as errors. Triage returns HTTP 200 with no evidence and the cause unconfirmed. The root span has status `Unset`. |

Nested span durations can overlap. Use their position within a trace to locate the delay. The trace verifier checks exact span counts so duplicate instrumentation is visible.
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Verified environment

| Component | Verified version |
| --- | --- |
| .NET SDK and target | 10.0.404, `net10.0` |
| Microsoft.Extensions.AI | 11.0.1 |
| OpenTelemetry .NET | 1.21.0 |
| Jaeger | 2.23.0, Linux amd64 |
| Optional local inference | llama.cpp b7124, Qwen3-0.6B Q8_0 |

The offline tests exercise actual loopback HTTP between two processes. They require Bash and Python and use no model API key or telemetry backend. The Jaeger and live modes are separate integration checks. Jaeger queries compare stored trace and span IDs, parents, service names, statuses, times, and selected attributes with the application's local captures.

The sample is designed to teach trace topology and operational diagnosis. Treat the artificial delay, token counts from the scripted model, and demonstration privacy canaries as test fixtures.
7 changes: 7 additions & 0 deletions dotnet-ai/opentelemetry-ai-observability/global.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"sdk": {
"version": "10.0.404",
"rollForward": "disable",
"allowPrerelease": false
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Net;

internal static class EvidenceLookup
{
public const string SourceName = "DotnetGuide.Triage";
public const string ActivityName = "dotnet-guide.triage.evidence_lookup";

public const string DurationInstrumentName = "dotnet_guide.evidence.lookup.duration";
private const string OutcomeKey = "dotnet_guide.evidence.outcome";

private static readonly ActivitySource Source = new(SourceName);
private static readonly Meter Meter = new(SourceName);
private static readonly Histogram<double> LookupDuration =
Meter.CreateHistogram<double>(DurationInstrumentName, unit: "s", description: "Time spent looking up incident evidence.");

public static async Task<EvidenceReply?> GetAsync(
HttpClient client, string incidentId, CancellationToken cancellation)
{
using Activity? lookup = Source.StartActivity(ActivityName, ActivityKind.Internal);
long started = Stopwatch.GetTimestamp();
string? outcome = null;
try
{
using var response = await client.GetAsync($"evidence/{Uri.EscapeDataString(incidentId)}", cancellation);
lookup?.SetTag("dotnet_guide.evidence.http_status_code", (int)response.StatusCode);
if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
{
outcome = "unavailable";
lookup?.SetTag(OutcomeKey, outcome);
lookup?.SetTag("error.type", "evidence_unavailable");
lookup?.SetStatus(ActivityStatusCode.Error);
return null;
}

response.EnsureSuccessStatusCode();
EvidenceReply reply = await response.Content.ReadFromJsonAsync<EvidenceReply>(cancellation)
?? throw new InvalidOperationException("Missing Evidence response.");
outcome = "available";
lookup?.SetTag(OutcomeKey, outcome);
lookup?.SetStatus(ActivityStatusCode.Ok);
return reply;
}
catch (Exception) when (!cancellation.IsCancellationRequested)
{
outcome = "unavailable";
lookup?.SetTag(OutcomeKey, outcome);
lookup?.SetTag("error.type", "lookup_failed");
lookup?.SetStatus(ActivityStatusCode.Error);
throw;
}
finally
{
if (outcome is not null)
{
LookupDuration.Record(Stopwatch.GetElapsedTime(started).TotalSeconds,
new KeyValuePair<string, object?>(OutcomeKey, outcome));
}
}
}
}
Loading
Loading