diff --git a/.github/workflows/build-samples.yml b/.github/workflows/build-samples.yml index b630030..6f70a7d 100644 --- a/.github/workflows/build-samples.yml +++ b/.github/workflows/build-samples.yml @@ -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/**" @@ -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/**" @@ -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 diff --git a/README.md b/README.md index 4c5bcbe..39e290f 100644 --- a/README.md +++ b/README.md @@ -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/) | diff --git a/dotnet-ai/opentelemetry-ai-observability/.gitignore b/dotnet-ai/opentelemetry-ai-observability/.gitignore new file mode 100644 index 0000000..76f8799 --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/.gitignore @@ -0,0 +1,2 @@ +/results.*/ +__pycache__/ diff --git a/dotnet-ai/opentelemetry-ai-observability/NuGet.Config b/dotnet-ai/opentelemetry-ai-observability/NuGet.Config new file mode 100644 index 0000000..5485860 --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/NuGet.Config @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/dotnet-ai/opentelemetry-ai-observability/OpenTelemetryAiObservability.slnx b/dotnet-ai/opentelemetry-ai-observability/OpenTelemetryAiObservability.slnx new file mode 100644 index 0000000..e61a1fa --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/OpenTelemetryAiObservability.slnx @@ -0,0 +1,3 @@ + + + diff --git a/dotnet-ai/opentelemetry-ai-observability/README.md b/dotnet-ai/opentelemetry-ai-observability/README.md new file mode 100644 index 0000000..3e7157e --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/README.md @@ -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/) diff --git a/dotnet-ai/opentelemetry-ai-observability/docker/compose.yaml b/dotnet-ai/opentelemetry-ai-observability/docker/compose.yaml new file mode 100644 index 0000000..c58e4fb --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/docker/compose.yaml @@ -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" diff --git a/dotnet-ai/opentelemetry-ai-observability/docker/jaeger.yaml b/dotnet-ai/opentelemetry-ai-observability/docker/jaeger.yaml new file mode 100644 index 0000000..0149ce0 --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/docker/jaeger.yaml @@ -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 diff --git a/dotnet-ai/opentelemetry-ai-observability/docs/metrics-and-privacy.md b/dotnet-ai/opentelemetry-ai-observability/docs/metrics-and-privacy.md new file mode 100644 index 0000000..5d077a1 --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/docs/metrics-and-privacy.md @@ -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. diff --git a/dotnet-ai/opentelemetry-ai-observability/docs/trace-contract.md b/dotnet-ai/opentelemetry-ai-observability/docs/trace-contract.md new file mode 100644 index 0000000..6efe7aa --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/docs/trace-contract.md @@ -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. diff --git a/dotnet-ai/opentelemetry-ai-observability/docs/verified-environment.md b/dotnet-ai/opentelemetry-ai-observability/docs/verified-environment.md new file mode 100644 index 0000000..b0a5fbd --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/docs/verified-environment.md @@ -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. diff --git a/dotnet-ai/opentelemetry-ai-observability/global.json b/dotnet-ai/opentelemetry-ai-observability/global.json new file mode 100644 index 0000000..1f4a137 --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "10.0.404", + "rollForward": "disable", + "allowPrerelease": false + } +} diff --git a/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/EvidenceLookup.cs b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/EvidenceLookup.cs new file mode 100644 index 0000000..b788efe --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/EvidenceLookup.cs @@ -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 LookupDuration = + Meter.CreateHistogram(DurationInstrumentName, unit: "s", description: "Time spent looking up incident evidence."); + + public static async Task 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(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(OutcomeKey, outcome)); + } + } + } +} diff --git a/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/LiveChatClient.cs b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/LiveChatClient.cs new file mode 100644 index 0000000..ebd2c33 --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/LiveChatClient.cs @@ -0,0 +1,178 @@ +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.Extensions.AI; + +internal sealed class LiveChatClient(HttpClient http, Uri endpoint, string model) : IChatClient +{ + public const string PromptMarker = "DG_OBSERVABILITY_PROMPT_CANARY"; + public const string ToolArgumentMarker = "DG_OBSERVABILITY_TOOL_ARGUMENT_CANARY"; + public const string ToolResultMarker = "DG_OBSERVABILITY_TOOL_RESULT_CANARY"; + public const string EvidenceMarker = "DG_OBSERVABILITY_EVIDENCE_BODY_CANARY"; + public const string ToolName = "lookup_evidence"; + public const string TurnKey = "dotnet-guide.live-turn"; + + private readonly ChatClientMetadata metadata = new("llama.cpp", endpoint, model); + + public async Task GetResponseAsync(IEnumerable messages, ChatOptions? options = null, + CancellationToken cancellationToken = default) + { + if (options?.AdditionalProperties?.TryGetValue(TurnKey, out object? state) != true || state is not LiveTurn turn) + { + throw new InvalidOperationException("The live request did not provide turn state."); + } + + ChatMessage[] transcript = messages.ToArray(); + var toolResult = transcript.SelectMany(message => message.Contents).OfType().SingleOrDefault(); + bool hasToolResult = toolResult is not null; + if (hasToolResult) + { + var supplied = JsonSerializer.Deserialize(toolResult!.Result?.ToString() ?? "null"); + turn.SawToolResult = supplied?.ProbeMarker == ToolResultMarker; + turn.SawEvidence = supplied?.Evidence?.Contains(EvidenceMarker, StringComparison.Ordinal) == true; + if (!turn.SawToolResult || supplied!.Available != turn.SawEvidence) + { + throw new InvalidOperationException("The completed tool turn did not supply the expected evidence state."); + } + } + turn.SawPrompt |= transcript.Any(message => message.Role == ChatRole.User + && message.Text.Contains(PromptMarker, StringComparison.Ordinal)); + var payload = new Dictionary + { + ["model"] = model, + ["messages"] = transcript.SelectMany(ToWireMessages).ToArray(), + ["temperature"] = 0, + ["max_tokens"] = 128, + ["seed"] = 17, + ["stream"] = false, + }; + if (!hasToolResult) + { + payload["messages"] = transcript.SelectMany(ToWireMessages) + .Append(new { role = "user", content = "Choose the lookup_evidence action before answering. Return the action as JSON." }) + .ToArray(); + payload["response_format"] = new + { + type = "json_schema", + json_schema = new + { + name = "evidence_action", + schema = new + { + type = "object", + properties = new + { + action = new { type = "string", @enum = new[] { ToolName } }, + incident = new { type = "string", @enum = new[] { turn.IncidentId } }, + note = new { type = "string", @enum = new[] { ToolArgumentMarker } }, + }, + required = new[] { "action", "incident", "note" }, + additionalProperties = false, + }, + }, + }; + } + + using HttpResponseMessage response = await http.PostAsJsonAsync(endpoint, payload, cancellationToken); + response.EnsureSuccessStatusCode(); + await using Stream body = await response.Content.ReadAsStreamAsync(cancellationToken); + using JsonDocument document = await JsonDocument.ParseAsync(body, cancellationToken: cancellationToken); + JsonElement data = document.RootElement; + JsonElement choice = data.GetProperty("choices")[0]; + JsonElement message = choice.GetProperty("message"); + string? text = message.TryGetProperty("content", out JsonElement content) && content.ValueKind is JsonValueKind.String + ? content.GetString() : null; + string? finish = choice.GetProperty("finish_reason").GetString(); + string? responseModel = data.GetProperty("model").GetString(); + string responseId = data.GetProperty("id").GetString() + ?? throw new InvalidOperationException("The provider did not supply a response ID."); + + AIContent part; + if (!hasToolResult) + { + using JsonDocument action = JsonDocument.Parse(text + ?? throw new InvalidOperationException("The model returned an empty action.")); + JsonElement item = action.RootElement; + if (item.GetProperty("action").GetString() != ToolName) + { + throw new InvalidOperationException("The generated action did not name the registered tool."); + } + + part = new FunctionCallContent(responseId, ToolName, new Dictionary + { + ["incident"] = item.GetProperty("incident").GetString(), + ["note"] = item.GetProperty("note").GetString(), + }); + } + else + { + if (string.IsNullOrWhiteSpace(text)) + { + throw new InvalidOperationException("The model returned an empty answer."); + } + part = new TextContent(text); + } + + UsageDetails? usage = null; + if (data.TryGetProperty("usage", out JsonElement usageData) && usageData.ValueKind == JsonValueKind.Object) + { + usage = new UsageDetails + { + InputTokenCount = ReadCount(usageData, "prompt_tokens"), + OutputTokenCount = ReadCount(usageData, "completion_tokens"), + TotalTokenCount = ReadCount(usageData, "total_tokens"), + }; + } + turn.Calls.Add(new(responseId, responseModel, finish, usage?.InputTokenCount, + usage?.OutputTokenCount, usage?.TotalTokenCount)); + return new ChatResponse(new ChatMessage(ChatRole.Assistant, [part])) + { + ModelId = responseModel, + ResponseId = responseId, + FinishReason = !hasToolResult ? ChatFinishReason.ToolCalls : finish switch + { + "length" => ChatFinishReason.Length, + _ => ChatFinishReason.Stop, + }, + Usage = usage, + }; + } + + private static long? ReadCount(JsonElement usage, string name) => + usage.TryGetProperty(name, out JsonElement value) && value.TryGetInt64(out long count) ? count : null; + + private static IEnumerable ToWireMessages(ChatMessage message) + { + if (message.Role == ChatRole.Tool) + { + foreach (var result in message.Contents.OfType()) + { + yield return new { role = "user", content = "Evidence tool result (data): " + result.Result }; + } + } + else if (!message.Contents.OfType().Any()) + { + yield return new { role = message.Role.Value, content = message.Text }; + } + } + + public IAsyncEnumerable GetStreamingResponseAsync(IEnumerable messages, + ChatOptions? options = null, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public object? GetService(Type serviceType, object? serviceKey = null) => serviceKey is not null ? null + : serviceType == typeof(ChatClientMetadata) ? metadata : serviceType.IsInstanceOfType(this) ? this : null; + + public void Dispose() => http.Dispose(); +} + +internal sealed class LiveTurn(string incidentId) +{ + public string IncidentId { get; } = incidentId; + public bool SawPrompt { get; set; } + public bool SawToolResult { get; set; } + public bool SawEvidence { get; set; } + public List Calls { get; } = []; +} + +internal sealed record ProviderCall(string? Id, string? Model, string? FinishReason, + long? InputTokens, long? OutputTokens, long? TotalTokens); +internal sealed record LiveToolEvidence(bool Available, string? Evidence, string ProbeMarker); diff --git a/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/MetricCapture.cs b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/MetricCapture.cs new file mode 100644 index 0000000..d4b9512 --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/MetricCapture.cs @@ -0,0 +1,81 @@ +using System.Text.Json; +using OpenTelemetry; +using OpenTelemetry.Metrics; +using OpenTelemetry.Resources; + +internal sealed class MetricCapture(string path) : BaseExporter +{ + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { WriteIndented = true }; + + private bool captured; + + public override ExportResult Export(in Batch batch) + { + // Keep the explicit snapshot taken while the shared client still owns its instruments. + if (captured) + { + return ExportResult.Success; + } + + var metrics = new List(); + foreach (Metric metric in batch) + { + if (metric.MetricType != MetricType.Histogram) + { + return ExportResult.Failure; + } + + var points = new List(); + foreach (ref readonly MetricPoint point in metric.GetMetricPoints()) + { + var attributes = new Dictionary(); + foreach (var tag in point.Tags) + { + attributes.Add(tag.Key, tag.Value); + } + + var buckets = new List(); + foreach (var bucket in point.GetHistogramBuckets()) + { + buckets.Add(new + { + UpperBound = double.IsPositiveInfinity(bucket.ExplicitBound) ? null : (double?)bucket.ExplicitBound, + Count = bucket.BucketCount, + }); + } + + points.Add(new + { + Attributes = attributes, + Count = point.GetHistogramCount(), + Sum = point.GetHistogramSum(), + Buckets = buckets, + }); + } + + metrics.Add(new + { + metric.Name, + Type = metric.MetricType.ToString(), + Temporality = metric.Temporality.ToString(), + metric.Unit, + metric.Description, + metric.MeterName, + metric.MeterVersion, + MeterTags = metric.MeterTags?.ToDictionary(), + Points = points, + }); + } + + var snapshot = new + { + ProcessId = Environment.ProcessId, + Resource = ParentProvider.GetResource().Attributes.ToDictionary(), + Metrics = metrics, + }; + File.WriteAllText(path + ".tmp", JsonSerializer.Serialize(snapshot, JsonOptions) + Environment.NewLine); + File.Move(path + ".tmp", path, overwrite: true); + captured = true; + return ExportResult.Success; + } +} diff --git a/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/ObservabilityLab.csproj b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/ObservabilityLab.csproj new file mode 100644 index 0000000..baa1ff7 --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/ObservabilityLab.csproj @@ -0,0 +1,19 @@ + + + net10.0 + enable + enable + true + true + true + all + + + + + + + + + + diff --git a/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/Program.cs b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/Program.cs new file mode 100644 index 0000000..667a4c5 --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/Program.cs @@ -0,0 +1,179 @@ +using System.Diagnostics; +using System.Net; +using System.Text.Json; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.Extensions.AI; +using OpenTelemetry; +using OpenTelemetry.Exporter; +using OpenTelemetry.Metrics; +using OpenTelemetry.Resources; +using OpenTelemetry.Trace; + +if (args.Length is < 2 or > 3 || args[0] is not ("triage" or "evidence") + || (args[0] == "triage") != (args.Length == 3)) +{ + throw new ArgumentException("Usage: ObservabilityLab evidence or ObservabilityLab triage "); +} + +string role = args[0]; +string outputDirectory = Path.GetFullPath(args[1]); +Directory.CreateDirectory(outputDirectory); +Uri? otlpEndpoint = ReadLoopbackEndpoint("DOTNET_GUIDE_OTLP_TRACES_ENDPOINT", "/v1/traces"); +Uri? modelEndpoint = role == "triage" + ? ReadLoopbackEndpoint("DOTNET_GUIDE_MODEL_ENDPOINT", "/v1/chat/completions") : null; +string modelId = Environment.GetEnvironmentVariable("DOTNET_GUIDE_MODEL_ID") ?? "qwen3-0.6b"; +#if DG_SYNTHETIC_CAPTURE_CONTROL +if (otlpEndpoint is not null || modelEndpoint is not null) +{ + throw new InvalidOperationException("The synthetic capture control uses local captures and the scripted model."); +} +#endif + +Activity.DefaultIdFormat = ActivityIdFormat.W3C; +Activity.ForceDefaultIdFormat = true; + +WebApplicationBuilder builder = WebApplication.CreateBuilder([]); +builder.WebHost.ConfigureKestrel(server => server.Listen(IPAddress.Loopback, 0)); +builder.Logging.ClearProviders(); + +var metricReader = new BaseExportingMetricReader(new MetricCapture(Path.Combine(outputDirectory, "metrics.json"))); +builder.Services.AddOpenTelemetry() + .ConfigureResource(resource => resource.AddService($"dotnet-guide-{role}-api")) + .WithTracing(tracing => + { + tracing.SetSampler(new AlwaysOnSampler()) + .AddAspNetCoreInstrumentation() + .AddProcessor(new SimpleActivityExportProcessor( + new TelemetryCapture(Path.Combine(outputDirectory, "spans.jsonl")))); + if (otlpEndpoint is not null) + { + tracing.AddOtlpExporter(exporter => + { + exporter.Protocol = OtlpExportProtocol.HttpProtobuf; + exporter.Endpoint = otlpEndpoint; + }); + } + + if (role == "triage") + { + tracing.AddSource(TriageWorkflow.AiSourceName, EvidenceLookup.SourceName).AddHttpClientInstrumentation(); + } + }) + .WithMetrics(metrics => + { + metrics.AddAspNetCoreInstrumentation() + .SetExemplarFilter(ExemplarFilterType.AlwaysOff) + .AddView(instrument => instrument.Name is + "http.server.request.duration" or "http.client.request.duration" + or "gen_ai.client.operation.duration" or "gen_ai.client.token.usage" + or EvidenceLookup.DurationInstrumentName ? null : MetricStreamConfiguration.Drop) + .AddReader(metricReader); + + if (role == "triage") + { + metrics.AddHttpClientInstrumentation().AddMeter(TriageWorkflow.AiSourceName, EvidenceLookup.SourceName); + } + }); + +if (role == "triage") +{ + builder.Services.AddSingleton(_ => + { + IChatClient inner = modelEndpoint is null ? new ScriptedChatClient() : new LiveChatClient( + new HttpClient(new HttpClientHandler { UseProxy = false }) { Timeout = TimeSpan.FromSeconds(90) }, + modelEndpoint, modelId); + var pipeline = new ChatClientBuilder(inner).UseFunctionInvocation(); +#if DG_SYNTHETIC_CAPTURE_CONTROL + pipeline.UseOpenTelemetry(configure: telemetry => telemetry.EnableSensitiveData = true); +#else + pipeline.UseOpenTelemetry(configure: telemetry => telemetry.EnableSensitiveData = false); +#endif + return pipeline.Build(); + }); + builder.Services.AddHttpClient("evidence", client => + { + client.BaseAddress = new Uri(args[2], UriKind.Absolute); + client.Timeout = TimeSpan.FromSeconds(8); + }).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { UseProxy = false }); +} + +await using WebApplication app = builder.Build(); +if (role == "evidence") +{ + string scenario = Environment.GetEnvironmentVariable("DOTNET_GUIDE_EVIDENCE_SCENARIO") ?? "healthy"; + TimeSpan delay = scenario switch + { + "healthy" or "failed" => TimeSpan.Zero, + "slow" => TimeSpan.FromMilliseconds(1200), + _ => throw new InvalidOperationException("Unknown Evidence probe scenario."), + }; + app.MapGet("/evidence/{incidentId}", async (string incidentId, HttpContext context, CancellationToken cancellation) => + { + if (scenario == "failed") + { + return Results.StatusCode(StatusCodes.Status503ServiceUnavailable); + } + + Activity serverSpan = Activity.Current ?? throw new InvalidOperationException("Missing Evidence server activity."); + await Task.Delay(delay, cancellation); + string evidence = "E-201: deployment at 14:02 UTC. E-101: checkout error spike at 14:09 UTC. " + + ScriptedChatClient.EvidenceMarker; + return Results.Ok(new EvidenceReply(incidentId, evidence, Environment.ProcessId, + context.Request.Headers["traceparent"].ToString(), serverSpan.TraceId.ToString(), + serverSpan.SpanId.ToString(), serverSpan.ParentSpanId.ToString())); + }); +} +else +{ + app.MapPost("/triage/{incidentId}", async (string incidentId, TriageRequest request, + IHttpClientFactory clients, IChatClient chat, CancellationToken cancellation) => + { + using HttpClient client = clients.CreateClient("evidence"); + return Results.Ok(await TriageWorkflow.RunAsync(chat, client, incidentId, request.Question, modelEndpoint is not null, cancellation)); + }); +} + +await app.StartAsync(); +string url = app.Services.GetRequiredService().Features.Get()!.Addresses.Single(); +string readyFile = Path.Combine(outputDirectory, "ready.json"); +await File.WriteAllTextAsync(readyFile + ".tmp", JsonSerializer.Serialize(new +{ + role, + url, + pid = Environment.ProcessId, + otlpEndpoint = otlpEndpoint?.AbsoluteUri, + captureEnvironment = Environment.GetEnvironmentVariable("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"), +})); +File.Move(readyFile + ".tmp", readyFile); +await app.WaitForShutdownAsync(); +if (!app.Services.GetRequiredService().ForceFlush(10000)) +{ + throw new InvalidOperationException("The trace processors did not complete their shutdown flush."); +} +if (!metricReader.Collect()) +{ + throw new InvalidOperationException("The local metric exporter did not complete."); +} + +static Uri? ReadLoopbackEndpoint(string variable, string path) +{ + string? value = Environment.GetEnvironmentVariable(variable); + if (string.IsNullOrWhiteSpace(value)) + { + return null; + } + if (!Uri.TryCreate(value, UriKind.Absolute, out Uri? uri) || uri.Scheme != Uri.UriSchemeHttp + || uri.Host != "127.0.0.1" || uri.AbsolutePath != path || uri.Query.Length != 0 + || uri.Fragment.Length != 0 || uri.UserInfo.Length != 0) + { + throw new InvalidOperationException($"Set {variable} to a loopback HTTP endpoint ending in {path}."); + } + return uri; +} + +internal sealed record EvidenceReply(string IncidentId, string? Evidence, int ProcessId, string ReceivedTraceparent, + string TraceId, string SpanId, string ParentSpanId); +internal sealed record TriageRequest(string Question); +internal sealed record TriageReply(bool EvidenceAvailable, string Answer, object Probe, int ProcessId, + string TraceId, string SpanId, EvidenceReply? Evidence); diff --git a/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/ScriptedChatClient.cs b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/ScriptedChatClient.cs new file mode 100644 index 0000000..c45ff54 --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/ScriptedChatClient.cs @@ -0,0 +1,101 @@ +using System.Text.Json; +using Microsoft.Extensions.AI; + +internal sealed class ScriptedChatClient : IChatClient +{ + public const string PromptMarker = "DG_OBSERVABILITY_PROMPT_CANARY"; + public const string ToolArgumentMarker = "DG_OBSERVABILITY_TOOL_ARGUMENT_CANARY"; + public const string ToolResultMarker = "DG_OBSERVABILITY_TOOL_RESULT_CANARY"; + public const string EvidenceMarker = "DG_OBSERVABILITY_EVIDENCE_BODY_CANARY"; + public const string ResponseMarker = "DG_OBSERVABILITY_RESPONSE_CANARY"; + + public const string ToolName = "lookup_evidence"; + public const string TurnKey = "dotnet-guide.scripted-turn"; + private const string ToolCallId = "telemetry-evidence-call"; + + private readonly ChatClientMetadata metadata = new("dotnet-guide-scripted", null, "scripted-model"); + + public Task GetResponseAsync( + IEnumerable messages, ChatOptions? options = null, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + if (options?.AdditionalProperties?.TryGetValue(TurnKey, out object? state) != true + || state is not ScriptedTurn turn) + { + throw new InvalidOperationException("The request did not provide scripted turn state."); + } + + turn.CallCount++; + ChatMessage[] transcript = messages.ToArray(); + turn.SawPrompt = transcript.Any(message => message.Role == ChatRole.User + && message.Text.Contains(PromptMarker, StringComparison.Ordinal)); + if (!turn.SawPrompt) + { + throw new InvalidOperationException("The scripted model did not receive the incoming prompt."); + } + + if (turn.CallCount == 1 && options?.Tools?.Count == 1) + { + return Task.FromResult(CreateResponse(new ChatMessage(ChatRole.Assistant, + [new FunctionCallContent(ToolCallId, ToolName, new Dictionary + { + ["incident"] = turn.IncidentId, + ["note"] = ToolArgumentMarker, + })]), ChatFinishReason.ToolCalls, turn.CallCount)); + } + + var result = transcript.SelectMany(message => message.Contents).OfType() + .Single(content => content.CallId == ToolCallId); + var payload = JsonSerializer.Deserialize(result.Result?.ToString() ?? "null"); + turn.SawToolResult = payload?.ProbeMarker == ToolResultMarker; + turn.SawEvidence = payload?.Available == true && payload.Evidence?.Contains(EvidenceMarker, StringComparison.Ordinal) == true; + turn.SawUnavailableEvidence = payload is { Available: false, Evidence: null }; + if (turn.CallCount != 2 || !turn.SawToolResult || !(turn.SawEvidence || turn.SawUnavailableEvidence)) + { + throw new InvalidOperationException("The scripted turn requires valid evidence or an explicit unavailable result."); + } + + string answer = turn.SawEvidence + ? "E-201 records the deployment before the error spike in E-101. The cause is unconfirmed." + : "Evidence is unavailable. The cause is unconfirmed."; + return Task.FromResult(CreateResponse(new ChatMessage(ChatRole.Assistant, $"{answer} {ResponseMarker}"), + ChatFinishReason.Stop, turn.CallCount)); + } + + private ChatResponse CreateResponse(ChatMessage message, ChatFinishReason reason, int callNumber) => new(message) + { + FinishReason = reason, + ModelId = metadata.DefaultModelId, + ResponseId = $"scripted-response-{callNumber}", + Usage = new UsageDetails { InputTokenCount = 11, OutputTokenCount = 7, TotalTokenCount = 18 }, + }; + + public IAsyncEnumerable GetStreamingResponseAsync( + IEnumerable messages, ChatOptions? options = null, CancellationToken cancellationToken = default) => + throw new NotSupportedException("This probe uses non-streaming calls."); + + public object? GetService(Type serviceType, object? serviceKey = null) + { + if (serviceKey is not null) + { + return null; + } + + return serviceType == typeof(ChatClientMetadata) ? metadata + : serviceType.IsInstanceOfType(this) ? this : null; + } + + public void Dispose() { } +} + +internal sealed record ToolEvidence(bool Available, string? Evidence, string ProbeMarker); + +internal sealed class ScriptedTurn(string incidentId) +{ + public string IncidentId { get; } = incidentId; + public int CallCount { get; set; } + public bool SawPrompt { get; set; } + public bool SawToolResult { get; set; } + public bool SawEvidence { get; set; } + public bool SawUnavailableEvidence { get; set; } +} diff --git a/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/TelemetryCapture.cs b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/TelemetryCapture.cs new file mode 100644 index 0000000..01820d0 --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/TelemetryCapture.cs @@ -0,0 +1,50 @@ +using System.Diagnostics; +using System.Text.Json; +using OpenTelemetry; +using OpenTelemetry.Resources; + +internal sealed class TelemetryCapture(string path) : BaseExporter +{ + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + private readonly object writeLock = new(); + + public override ExportResult Export(in Batch batch) + { + var resource = ParentProvider.GetResource().Attributes.ToDictionary(); + lock (writeLock) + { + using var output = File.AppendText(path); + foreach (Activity span in batch) + { + var snapshot = new + { + ProcessId = Environment.ProcessId, + Resource = resource, + Source = span.Source.Name, + Name = span.DisplayName, + Kind = span.Kind.ToString(), + Status = span.Status.ToString(), + span.StatusDescription, + TraceId = span.TraceId.ToString(), + SpanId = span.SpanId.ToString(), + ParentSpanId = span.ParentSpanId.ToString(), + StartUnixMicroseconds = (span.StartTimeUtc.Ticks - DateTime.UnixEpoch.Ticks) / TimeSpan.TicksPerMicrosecond, + DurationMilliseconds = span.Duration.TotalMilliseconds, + Attributes = span.TagObjects.ToDictionary(), + span.TraceStateString, + Events = span.Events.Select(entry => new { entry.Name, Attributes = entry.Tags.ToDictionary() }).ToArray(), + Links = span.Links.Select(link => new + { + TraceId = link.Context.TraceId.ToString(), + SpanId = link.Context.SpanId.ToString(), + link.Context.TraceState, + Attributes = link.Tags?.ToDictionary(), + }).ToArray(), + }; + output.WriteLine(JsonSerializer.Serialize(snapshot, JsonOptions)); + } + } + + return ExportResult.Success; + } +} diff --git a/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/TriageWorkflow.cs b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/TriageWorkflow.cs new file mode 100644 index 0000000..ad6304a --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/TriageWorkflow.cs @@ -0,0 +1,80 @@ +using System.Diagnostics; +using System.Text.Json; +using Microsoft.Extensions.AI; + +internal static class TriageWorkflow +{ + public const string AiSourceName = "Experimental.Microsoft.Extensions.AI"; + + public static async Task RunAsync(IChatClient chat, HttpClient client, string incidentId, string question, + bool live, CancellationToken cancellation) + { + Activity serverSpan = Activity.Current ?? throw new InvalidOperationException("Missing Triage server activity."); + var turn = new ScriptedTurn(incidentId); + var liveTurn = live ? new LiveTurn(incidentId) : null; + + int toolCalls = 0; + bool sawToolArgument = false; + EvidenceReply? evidence = null; + + async Task LookupAsync(string incident, string note, CancellationToken toolCancellation) + { + toolCalls++; + sawToolArgument = note == ScriptedChatClient.ToolArgumentMarker; + if (incident != incidentId || !sawToolArgument) + { + throw new InvalidOperationException("Unexpected arguments reached the scripted tool."); + } + + evidence = await EvidenceLookup.GetAsync(client, incident, toolCancellation); + // An unavailable result completes orchestration but represents a failed tool operation. + // Only annotate the matching tool activity, even if tracing omits that activity. + if (evidence is null && Activity.Current is { } tool + && tool.Source.Name == AiSourceName + && tool.GetTagItem("gen_ai.operation.name") is "execute_tool" + && tool.GetTagItem("gen_ai.tool.name") is ScriptedChatClient.ToolName) + { + tool.SetTag("error.type", "evidence_unavailable"); + tool.SetStatus(ActivityStatusCode.Error); + } + + return JsonSerializer.Serialize(new ToolEvidence( + evidence is not null, evidence?.Evidence, ScriptedChatClient.ToolResultMarker)); + } + + var options = new ChatOptions + { + Tools = [AIFunctionFactory.Create(LookupAsync, ScriptedChatClient.ToolName)], + AdditionalProperties = new(), + }; + if (liveTurn is null) + { + options.AdditionalProperties[ScriptedChatClient.TurnKey] = turn; + } + else + { + options.AdditionalProperties[LiveChatClient.TurnKey] = liveTurn; + } + + ChatMessage[] messages = live + ? [new(ChatRole.System, "You summarize incident evidence. Use the tool result. State that the cause is unconfirmed. " + + "If evidence is available, cite its evidence IDs and summarize the timeline in one short sentence. " + + "If no evidence is available, say so and do not invent evidence. Do not repeat test markers."), + new(ChatRole.User, question)] + : [new(ChatRole.User, question)]; + ChatResponse response = await chat.GetResponseAsync(messages, options, cancellation); + object probe = liveTurn is null + ? new TurnProbe(turn.CallCount, toolCalls, turn.SawPrompt, sawToolArgument, + turn.SawToolResult, turn.SawEvidence, turn.SawUnavailableEvidence) + : new LiveProbe(liveTurn.Calls.ToArray(), toolCalls, liveTurn.SawPrompt, sawToolArgument, + liveTurn.SawToolResult, liveTurn.SawEvidence, response.Text); + string answer = live && evidence is null ? "Evidence is unavailable. The cause is unconfirmed." : response.Text; + return new(evidence is not null, answer, probe, + Environment.ProcessId, serverSpan.TraceId.ToString(), serverSpan.SpanId.ToString(), evidence); + } +} + +internal sealed record TurnProbe(int ModelCalls, int ToolCalls, bool SawPrompt, bool SawToolArgument, bool SawToolResult, bool SawEvidence, bool SawUnavailableEvidence); + +internal sealed record LiveProbe(ProviderCall[] ProviderCalls, int ToolCalls, bool SawPrompt, bool SawToolArgument, + bool SawToolResult, bool SawEvidence, string ModelText); diff --git a/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/packages.lock.json b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/packages.lock.json new file mode 100644 index 0000000..b1dcfe0 --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/src/ObservabilityLab/packages.lock.json @@ -0,0 +1,123 @@ +{ + "version": 1, + "dependencies": { + "net10.0": { + "Microsoft.Extensions.AI": { + "type": "Direct", + "requested": "[11.0.1, 11.0.1]", + "resolved": "11.0.1", + "contentHash": "MP6zzZzPseaXu0DtZFCkPCWPXLTu7JY28ciyxqSoeDOP5Raf+wJT8+HapyLfXaI7F1CXpyr5PgiCQEE0CeVCqw==", + "dependencies": { + "Microsoft.Extensions.AI.Abstractions": "11.0.1", + "Microsoft.Extensions.Caching.Abstractions": "11.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "Microsoft.Extensions.Logging.Abstractions": "11.0.0", + "System.Numerics.Tensors": "11.0.0" + } + }, + "OpenTelemetry": { + "type": "Direct", + "requested": "[1.21.0, 1.21.0]", + "resolved": "1.21.0", + "contentHash": "ynAzNO/ebDTPxARbz4z/HgL8azMk/iDk4GXFuIRQ6krr1+a5QMC4eoiXRl+e7COd+3RLyL/yTuE6bevwqbv4Bw==", + "dependencies": { + "OpenTelemetry.Api.ProviderBuilderExtensions": "1.21.0" + } + }, + "OpenTelemetry.Exporter.OpenTelemetryProtocol": { + "type": "Direct", + "requested": "[1.21.0, 1.21.0]", + "resolved": "1.21.0", + "contentHash": "Xo/3lqiZhv+an00t5N9Jxt3U2vIOcY6/bu0wo5LiQrrRIwd/8dv9FdlIVB3k3ypiyG1VkbCXhWH1tiC48HQS4w==", + "dependencies": { + "OpenTelemetry": "1.21.0" + } + }, + "OpenTelemetry.Extensions.Hosting": { + "type": "Direct", + "requested": "[1.21.0, 1.21.0]", + "resolved": "1.21.0", + "contentHash": "+cOZFDBLktHT8V/aUb2SXQVFNP5JrcX/F24TgHcbD2kd4SFcKlBMChYeU/K+Tg3nuL+4HAS7dcR7Y2+tcSnFbQ==", + "dependencies": { + "OpenTelemetry": "1.21.0" + } + }, + "OpenTelemetry.Instrumentation.AspNetCore": { + "type": "Direct", + "requested": "[1.21.0, 1.21.0]", + "resolved": "1.21.0", + "contentHash": "mHX+dOb0uGLGuVJxoKdYTsndz8pNg+Uxe7YqTp6IY3No9tmoLCiUjXf/fI82IrTRnF1PraVzU+VWymzLR1CmFw==", + "dependencies": { + "OpenTelemetry.Api.ProviderBuilderExtensions": "[1.21.0, 2.0.0)" + } + }, + "OpenTelemetry.Instrumentation.Http": { + "type": "Direct", + "requested": "[1.21.0, 1.21.0]", + "resolved": "1.21.0", + "contentHash": "sThY0J9yMUZ4yWX5/JWpRlFN0LedPpA2ZTj35Z2unkxXLcCiXxDmmlL8UkqFDR6I16E+o/bTFC1HPylr/CbJ8A==", + "dependencies": { + "OpenTelemetry.Api.ProviderBuilderExtensions": "[1.21.0, 2.0.0)" + } + }, + "Microsoft.Extensions.AI.Abstractions": { + "type": "Transitive", + "resolved": "11.0.1", + "contentHash": "pG3n1nHRnVcYuMAiqhDPuKefXTtUGAhAtqhBUKpNsZXYef9Vm51iZhUAVfQ2EzYhechFaA5hCcgQgK18jTzuiw==" + }, + "Microsoft.Extensions.Caching.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "L+eahU5QGaFaCau3Y9qqY7WThUsR18sHASVDD1KuaSx2dy73NOY9U5Qz5eOe6bJOF3wHzkEaCl2LZhgwtlClyw==", + "dependencies": { + "Microsoft.Extensions.Primitives": "11.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "a2c4Kp55miXT6G+DSb75pczXQJHgNMzPyZEyMxrrKxuQrgvctcDWJWD9fVe/uGbQdu4Z0c3B7AVKp1DXmD64nQ==" + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "MTMO2V1eT9Dm5VIpJGLNwIjAjoBErUlfuB+DEaZ0tb8J+Nf/Xlj8he5AztK9p1iOJPIyuBeOrVy2u/CSdsfzPw==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "11.0.0", + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "HH2akbW2HeY/xeZJA5UceuQQX+1Pv/Kxrz/x4XPoH6wYDtgPIlBeOTZlQXlT+b50b1Ym/xfP+WJCX9FW4uLBXQ==" + }, + "OpenTelemetry.Api": { + "type": "Transitive", + "resolved": "1.21.0", + "contentHash": "KptD6ThegQORUzwot75zW2AUH6IDyKXH1R2yhovJPYfrzqSgHQidMfVfKLjaYEnJa5ySQgQm0RjuM6X+TCJ9yw==", + "dependencies": { + "System.Diagnostics.DiagnosticSource": "11.0.0" + } + }, + "OpenTelemetry.Api.ProviderBuilderExtensions": { + "type": "Transitive", + "resolved": "1.21.0", + "contentHash": "ZcBCBTGbzjj8Y+9UnZKbSjnRyKc2ub2IvvU68fFHKmyKzTS4hU+4/f0PO1GoIf7FTYLKTyw+l/EwLL/PPIDkxg==", + "dependencies": { + "OpenTelemetry.Api": "1.21.0" + } + }, + "System.Diagnostics.DiagnosticSource": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "+boRR9uSKiIPtFeRLGwO5xylhDF80xpwM+dmk5jgIqqeUKLbujGkGICMTKqQrBzKO6fIp8BU8DV6YZkQukqo3A==" + }, + "System.Numerics.Tensors": { + "type": "Transitive", + "resolved": "11.0.0", + "contentHash": "thx6y1hMzB6LumB/aLcZoLHWq8wr+dbldk/FiNghyT+4ynxo9u2oCTFfb5iDMDG6hykDXLorXuaf4EPEij2BBg==" + } + } + } +} \ No newline at end of file diff --git a/dotnet-ai/opentelemetry-ai-observability/tests/check_jaeger.py b/dotnet-ai/opentelemetry-ai-observability/tests/check_jaeger.py new file mode 100644 index 0000000..c353deb --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/tests/check_jaeger.py @@ -0,0 +1,190 @@ +"""Verify OTLP traces returned by Jaeger's v3 query API against the local SDK export.""" + +import argparse +import json +from pathlib import Path +import re +import time +from urllib.error import URLError +from urllib.parse import urlsplit +from urllib.request import ProxyHandler, build_opener + +import verify_local_signals as local + +OPENER = build_opener(ProxyHandler({})) +SERVICES = {"dotnet-guide-triage-api", "dotnet-guide-evidence-api"} +KINDS = {"Internal": 1, "Server": 2, "Client": 3} +STATUSES = {"Unset": 0, "Ok": 1, "Error": 2} + + +def local_url(value, path): + url = urlsplit(value) + assert url.scheme == "http" and url.hostname == "127.0.0.1" and url.port + assert not url.username and not url.password and not url.query and not url.fragment + assert url.path in path + return value.rstrip("/") + + +def get(url): + with OPENER.open(url, timeout=2) as response: + assert response.status == 200 + return response.read() + + +def wait_for(url, parse): + deadline = time.monotonic() + 15 + while True: + try: + content = get(url) + return content, parse(content) + except (URLError, ValueError) as error: + if time.monotonic() >= deadline: + raise RuntimeError(f"Jaeger did not return the expected data at {url}") from error + time.sleep(0.15) + + +def ui_title(content): + title = re.search(rb"([^<]+)", content, re.IGNORECASE) + if not title or b"Jaeger" not in title.group(1): + raise ValueError("Jaeger UI title was absent") + return title.group(1).decode() + + +def json_objects(content): + remaining = content.decode("utf-8").strip() + decoder = json.JSONDecoder() + while remaining: + document, end = decoder.raw_decode(remaining) + yield document + remaining = remaining[end:].lstrip() + + +def trace_spans(content, expected_count=8): + documents = list(json_objects(content)) + spans = {} + for document in documents: + if "result" not in document: + raise ValueError(f"No result in Jaeger response: {document}") + for resource_spans in document["result"]["resourceSpans"]: + resource = attributes(resource_spans["resource"]["attributes"]) + for scope_spans in resource_spans["scopeSpans"]: + scope = scope_spans["scope"]["name"] + for span in scope_spans["spans"]: + assert span["spanId"] not in spans, "Duplicate span returned by Jaeger." + spans[span["spanId"]] = (resource["service.name"], scope, span) + if len(spans) < expected_count: + raise ValueError(f"Expected the complete trace, received {len(spans)} spans") + assert len(spans) == expected_count + return documents, spans + + +def attributes(items): + def decode(value): + kind, content = next(iter(value.items())) + return int(content) if kind == "intValue" else content + + return {item["key"]: decode(item["value"]) for item in items} + + +def validate_trace(content, expected): + documents, indexed_spans = trace_spans(content) + assert not list(local.scan_fields(documents)), "Unexpected synthetic marker in a Jaeger query result." + assert indexed_spans.keys() == {span["spanId"] for span in expected} + + for span in expected: + service, scope, returned = indexed_spans[span["spanId"]] + assert service == span["resource"]["service.name"] and scope == span["source"] + assert returned["traceId"] == span["traceId"] and returned["name"] == span["name"] + assert returned.get("parentSpanId", "0" * 16) == span["parentSpanId"], "Jaeger parent span ID differs from the SDK." + assert returned["kind"] == KINDS[span["kind"]] + assert returned.get("status", {}).get("code", 0) == STATUSES[span["status"]] + exported_attributes = attributes(returned.get("attributes", [])) + for name in ("http.response.status_code", "error.type", "dotnet_guide.evidence.outcome", + "gen_ai.response.id", "gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens"): + assert exported_attributes.get(name) == span["attributes"].get(name), (span["name"], name) + start = int(returned["startTimeUnixNano"]) + end = int(returned["endTimeUnixNano"]) + assert abs(start / 1000 - span["startUnixMicroseconds"]) <= 1000 + assert abs((end - start) / 1_000_000 - span["durationMilliseconds"]) <= 1 + + +def matching_spans(root, trace_id): + return [ + span for role in ("triage", "evidence") + for span in local.read_spans(root / role / "spans.jsonl") + if span["traceId"] == trace_id + ] + + +def verify(root, query_url=None): + local.verify(root) + jaeger = root / "jaeger" + if query_url: + jaeger.mkdir() + _, title = wait_for(query_url + "/", ui_title) + services, _ = wait_for(query_url + "/api/v3/services", json.loads) + (jaeger / "services.json").write_bytes(services) + (jaeger / "ui.json").write_text(json.dumps({"status": 200, "title": title}) + "\n", encoding="utf-8") + assert set(local.read_json(jaeger / "services.json")["services"]) >= SERVICES + ui = local.read_json(jaeger / "ui.json") + assert ui["status"] == 200 and "Jaeger" in ui["title"] + + summary = {} + for case in local.SCENARIOS: + replies = local.read_json(root / case / "http-responses.json") + cases = [] + for index, reply in enumerate(replies, start=1): + trace_id = reply["body"]["traceId"] + assert re.fullmatch(r"[0-9a-f]{32}", trace_id) + filename = f"{case}-{index}.jsonl" + path = jaeger / filename + expected = matching_spans(root / case, trace_id) + if query_url: + content, _ = wait_for(f"{query_url}/api/v3/traces/{trace_id}", trace_spans) + path.write_bytes(content) + _, title = wait_for(f"{query_url}/trace/{trace_id}", ui_title) + assert title == ui["title"] + validate_trace(path.read_bytes(), expected) + evidence = next(span for span in expected if span["resource"]["service.name"] == "dotnet-guide-evidence-api") + record = { + "traceId": trace_id, + "queryPath": f"/api/v3/traces/{trace_id}", + "uiPath": f"/trace/{trace_id}", + "spanCount": len(expected), + "errorSpans": [span["name"] for span in expected if span["status"] == "Error"], + "evidenceHttpStatus": evidence["attributes"]["http.response.status_code"], + "evidenceDurationMilliseconds": evidence["durationMilliseconds"], + "capture": filename, + } + cases.append(record) + summary[case] = cases + print(f"PASS Jaeger {case}: {len(cases)} stored traces × 8 matching spans") + print("PASS both Jaeger services listed and query results matched IDs, links, durations, statuses, and selected attributes") + return summary + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("directory", type=Path) + parser.add_argument("--app", type=Path) + parser.add_argument("--otlp") + parser.add_argument("--query") + args = parser.parse_args() + root = args.directory.resolve() + + if args.app: + if not args.otlp or not args.query: + parser.error("A live run needs --otlp and --query.") + otlp = local_url(args.otlp, {"/v1/traces"}) + query = local_url(args.query, {"", "/"}) + wait_for(query + "/", ui_title) + for case in local.SCENARIOS: + local.exercise(args.app.resolve(), root / case, case, otlp) + for role in ("triage", "evidence"): + ready = local.read_json(root / case / role / "ready.json") + assert ready["otlpEndpoint"] == otlp + summary = verify(root, query) + (root / "jaeger-summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + else: + assert local.read_json(root / "jaeger-summary.json") == verify(root) + print("PASS six traces ingested through OTLP and verified through the Jaeger v3 query API") diff --git a/dotnet-ai/opentelemetry-ai-observability/tests/check_live.py b/dotnet-ai/opentelemetry-ai-observability/tests/check_live.py new file mode 100644 index 0000000..21bf8ac --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/tests/check_live.py @@ -0,0 +1,183 @@ +"""Verify a live llama.cpp model, tool, and Evidence API in one distributed trace.""" + +import argparse +from contextlib import ExitStack +from functools import partial +import json +from pathlib import Path +import re +from urllib.request import Request + +from check_jaeger import KINDS, OPENER, SERVICES, STATUSES, attributes, get, local_url, trace_spans, ui_title, wait_for +from verify_local_signals import read_json, service + +live_spans = partial(trace_spans, expected_count=10) + + +SCENARIOS = ("healthy", "slow", "failed") +MARKERS = ("DG_OBSERVABILITY_PROMPT_CANARY", "DG_OBSERVABILITY_TOOL_ARGUMENT_CANARY", "DG_OBSERVABILITY_TOOL_RESULT_CANARY", + "DG_OBSERVABILITY_EVIDENCE_BODY_CANARY") +AI = "Experimental.Microsoft.Extensions.AI" +PAYLOAD_TAGS = {"gen_ai.input.messages", "gen_ai.output.messages", "gen_ai.system_instructions", + "gen_ai.tool.call.arguments", "gen_ai.tool.call.result"} + + +def exercise(app, root, scenario, otlp, model_endpoint, model_id): + root.mkdir() + with ExitStack() as stack: + args = {"otlp_endpoint": otlp, "model_endpoint": model_endpoint, "model_id": model_id} + evidence = stack.enter_context(service(app, root, "evidence", scenario=scenario, **args)) + triage = stack.enter_context(service(app, root, "triage", evidence["url"], **args)) + question = {"question": "What does the checkout-api evidence establish? " + MARKERS[0]} + url = triage["url"] + "/triage/checkout-api" + request = Request(url, data=json.dumps(question).encode(), method="POST", + headers={"Content-Type": "application/json"}) + with OPENER.open(request, timeout=120) as reply: + payload = {"status": reply.status, "body": json.loads(reply.read())} + (root / "http-response.json").write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + + +def check_markers(value, path): + serialized = json.dumps(value) + assert not any(marker in serialized for marker in MARKERS), f"Synthetic marker escaped into {path}." + + +def verify_case(folder, model_id, model_endpoint): + response = read_json(folder / "http-response.json") + reply = response["body"] + probe = reply["probe"] + calls = probe["providerCalls"] + failed = folder.name == "failed" + assert response["status"] == 200 and len(calls) == 2 and probe["toolCalls"] == 1 + assert probe["sawPrompt"] and probe["sawToolArgument"] and probe["sawToolResult"] and probe["modelText"].strip() + assert probe["sawEvidence"] is (not failed) + assert reply["evidenceAvailable"] is (not failed) + if failed: + assert reply["evidence"] is None and reply["answer"] == "Evidence is unavailable. The cause is unconfirmed." + else: + assert MARKERS[3] in reply["evidence"]["evidence"] and reply["answer"] == probe["modelText"] + + trace_file = folder / "jaeger-trace.jsonl" + docs, jaeger_spans = live_spans(trace_file.read_bytes()) + check_markers(docs, trace_file) + local = [] + for role in ("triage", "evidence"): + local += [json.loads(line) for line in (folder / role / "spans.jsonl").read_text().splitlines()] + check_markers(read_json(folder / role / "metrics.json"), f"{role} metrics") + check_markers(local, "local spans") + assert len(local) == 10 + assert probe["modelText"] not in json.dumps(docs, ensure_ascii=False) + assert {span["spanId"] for span in local} == jaeger_spans.keys() + assert {span["traceId"] for span in local} == {reply["traceId"]} + assert {span["resource"]["service.name"] for span in local} == SERVICES + for span in local: + name, scope, remote = jaeger_spans[span["spanId"]] + assert name == span["resource"]["service.name"] and scope == span["source"] + assert remote["traceId"] == reply["traceId"] and remote["name"] == span["name"] + assert remote.get("parentSpanId", "0" * 16) == span["parentSpanId"] + assert remote["kind"] == KINDS[span["kind"]] + assert remote.get("status", {}).get("code", 0) == STATUSES[span["status"]] + remote_tags = attributes(remote.get("attributes", [])) + assert not (PAYLOAD_TAGS & remote_tags.keys()) and not (PAYLOAD_TAGS & span["attributes"].keys()) + for key in ("http.response.status_code", "gen_ai.provider.name", "gen_ai.request.model", + "gen_ai.response.model", "gen_ai.response.id", "gen_ai.usage.input_tokens", + "gen_ai.usage.output_tokens", "error.type"): + assert remote_tags.get(key) == span["attributes"].get(key), (span["name"], key) + raw_response = probe["modelText"] + assert raw_response not in json.dumps(span, ensure_ascii=False) + + root, = [span for span in local if span["name"] == "POST /triage/{incidentId}"] + receiver, = [span for span in local if span["name"] == "GET /evidence/{incidentId}"] + orchestration, = [span for span in local if span["name"] == "orchestrate_tools"] + tool, = [span for span in local if span["name"] == "execute_tool lookup_evidence"] + lookup, = [span for span in local if span["name"] == "dotnet-guide.triage.evidence_lookup"] + evidence_client, = [span for span in local if span["source"] == "System.Net.Http" and span["name"] == "GET"] + provider_http = [span for span in local if span["source"] == "System.Net.Http" and span["name"] == "POST"] + ai = [span for span in local if span["source"] == AI and span["name"].startswith("chat ")] + assert len(provider_http) == len(ai) == 2 + assert root["spanId"] == reply["spanId"] and root["parentSpanId"] == "0" * 16 + for parent, child in [(root, orchestration), (orchestration, tool), (tool, lookup), (lookup, evidence_client), + (evidence_client, receiver), *((orchestration, span) for span in ai)]: + assert child["parentSpanId"] == parent["spanId"] + assert root["attributes"]["http.response.status_code"] == 200 + assert root["status"] == "Unset" + assert receiver["attributes"]["http.response.status_code"] == (503 if failed else 200) + assert evidence_client["attributes"]["http.response.status_code"] == (503 if failed else 200) + assert {span["spanId"] for span in local if span["status"] == "Error"} == ( + {receiver["spanId"], evidence_client["spanId"], tool["spanId"], lookup["spanId"]} if failed else set()) + if folder.name == "slow": + assert receiver["durationMilliseconds"] >= 1080 + + assert calls[0]["finishReason"] == "stop" + for index, call in enumerate(calls): + assert call["id"] and call["model"] == model_id + span, = [span for span in ai if span["attributes"].get("gen_ai.response.id") == call["id"]] + http, = [candidate for candidate in provider_http if candidate["parentSpanId"] == span["spanId"]] + assert http["attributes"]["url.full"] == model_endpoint and http["attributes"]["http.response.status_code"] == 200 + tags = span["attributes"] + finish_reasons = json.loads(tags["gen_ai.response.finish_reasons"]) + assert finish_reasons == (["tool_calls"] if index == 0 else [call["finishReason"]]) + assert tags["gen_ai.provider.name"] == "llama.cpp" + assert tags["gen_ai.request.model"] == tags["gen_ai.response.model"] == model_id + if call["inputTokens"] is not None: + assert tags["gen_ai.usage.input_tokens"] == call["inputTokens"] + if call["outputTokens"] is not None: + assert tags["gen_ai.usage.output_tokens"] == call["outputTokens"] + if call["totalTokens"] is not None: + assert call["totalTokens"] == call["inputTokens"] + call["outputTokens"] + assert len({call["id"] for call in calls}) == 2 + metrics = read_json(folder / "triage" / "metrics.json")["metrics"] + token_metric, = (metric for metric in metrics if metric["name"] == "gen_ai.client.token.usage") + assert token_metric["unit"] == "{token}" and token_metric["meterName"] == AI + tokens = {point["attributes"]["gen_ai.token.type"]: point for point in token_metric["points"]} + assert set(tokens) == {"input", "output"} + token_totals = {} + for direction, point in tokens.items(): + actual = [call[f"{direction}Tokens"] for call in calls] + assert all(isinstance(value, int) and value > 0 for value in actual) + assert point["count"] == len(actual) and point["sum"] == sum(actual) + token_totals[direction] = sum(actual) + + print(f"PASS {folder.name}: 10 spans, 2 actual model HTTP calls, tool/Evidence chain, Triage 200, " + f"Evidence {receiver['attributes']['http.response.status_code']}, trace {reply['traceId']}") + return {"traceId": reply["traceId"], "spanCount": len(local), "model": model_id, "providerCalls": calls, + "evidenceStatus": receiver["attributes"]["http.response.status_code"], "tokenTotals": token_totals, + "evidenceDurationMs": receiver["durationMilliseconds"], "errorSpans": sum(s["status"] == "Error" for s in local)} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("directory", type=Path) + parser.add_argument("--app", type=Path) + parser.add_argument("--otlp") + parser.add_argument("--query") + parser.add_argument("--model-endpoint") + parser.add_argument("--model-id", default="qwen3-0.6b") + args = parser.parse_args() + root_path = args.directory.resolve() + metadata_path = root_path / "run-endpoints.json" + + if args.app: + otlp = local_url(args.otlp, {"/v1/traces"}) + query = local_url(args.query, {"", "/"}) + model_endpoint = local_url(args.model_endpoint, {"/v1/chat/completions"}) + assert args.model_id in {model["id"] for model in json.loads(get(model_endpoint.split("/chat/completions", 1)[0] + "/models"))["data"]} + wait_for(query + "/", ui_title) + metadata_path.write_text(json.dumps({"modelEndpoint": model_endpoint, "modelId": args.model_id}, indent=2) + "\n") + for case in SCENARIOS: + folder = root_path / case + exercise(args.app.resolve(), folder, case, otlp, model_endpoint, args.model_id) + trace_id = read_json(folder / "http-response.json")["body"]["traceId"] + assert re.fullmatch(r"[0-9a-f]{32}", trace_id) + content, _ = wait_for(f"{query}/api/v3/traces/{trace_id}", live_spans) + (folder / "jaeger-trace.jsonl").write_bytes(content) + + metadata = read_json(metadata_path) + summary = {case: verify_case(root_path / case, metadata["modelId"], metadata["modelEndpoint"]) for case in SCENARIOS} + result = root_path / "live-summary.json" + if args.app: + result.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + else: + assert read_json(result) == summary + assert len({entry["traceId"] for entry in summary.values()}) == len(SCENARIOS) + print("PASS live model, provider usage, cross-service trace, and payload checks verified") diff --git a/dotnet-ai/opentelemetry-ai-observability/tests/verify_local_signals.py b/dotnet-ai/opentelemetry-ai-observability/tests/verify_local_signals.py new file mode 100644 index 0000000..3be298b --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/tests/verify_local_signals.py @@ -0,0 +1,412 @@ +"""Verify real metrics exported by the pinned .NET AI and OpenTelemetry stack.""" + +import argparse +from contextlib import ExitStack, contextmanager +import json +import math +import os +from pathlib import Path +import re +import subprocess +import time +from urllib.parse import urlsplit +from urllib.request import ProxyHandler, Request, build_opener + +SCENARIOS = ("healthy", "slow", "failed") +REQUEST_COUNT = 2 +DELAY_MS = 1200 +INCIDENT = "checkout-api" +AI_SOURCE = "Experimental.Microsoft.Extensions.AI" +MARKERS = tuple(f"DG_OBSERVABILITY_{field}_CANARY" for field in + ("PROMPT", "TOOL_ARGUMENT", "TOOL_RESULT", "EVIDENCE_BODY", "RESPONSE")) + + +def read_json(path): + return json.loads(path.read_text(encoding="utf-8")) + + +def read_spans(path): + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] + + +@contextmanager +def service(dll, root, role, *arguments, otlp_endpoint=None, scenario=None, model_endpoint=None, model_id=None): + output = root / role + output.mkdir() + environment = os.environ.copy() + # Keep host-specific resource metadata out of the standalone evidence. + environment.pop("OTEL_RESOURCE_ATTRIBUTES", None) + environment.pop("OTEL_SERVICE_NAME", None) + environment["OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"] = "true" + for key in ("DOTNET_GUIDE_OTLP_TRACES_ENDPOINT", "DOTNET_GUIDE_MODEL_ENDPOINT", "DOTNET_GUIDE_MODEL_ID"): + environment.pop(key, None) + if otlp_endpoint: + environment["DOTNET_GUIDE_OTLP_TRACES_ENDPOINT"] = otlp_endpoint + if model_endpoint: + environment["DOTNET_GUIDE_MODEL_ENDPOINT"] = model_endpoint + environment["DOTNET_GUIDE_MODEL_ID"] = model_id + environment.pop("DOTNET_GUIDE_EVIDENCE_SCENARIO", None) + if scenario is not None: + environment["DOTNET_GUIDE_EVIDENCE_SCENARIO"] = scenario + with (output / "process.log").open("w", encoding="utf-8") as log: + process = subprocess.Popen( + ["dotnet", str(dll), role, str(output), *arguments], + stdout=log, stderr=subprocess.STDOUT, env=environment + ) + try: + ready_file = output / "ready.json" + deadline = time.monotonic() + 20 + while not ready_file.exists(): + if process.poll() is not None or time.monotonic() >= deadline: + raise RuntimeError(f"{role} did not start. See {output / 'process.log'}.") + time.sleep(0.05) + ready = read_json(ready_file) + assert ready["role"] == role and ready["pid"] == process.pid + address = urlsplit(ready["url"]) + assert address.scheme == "http" and address.hostname == "127.0.0.1" and address.port + yield ready + finally: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + if process.returncode != 0: + raise RuntimeError(f"{role} exited with {process.returncode}. See {output / 'process.log'}.") + + +def exercise(dll, root, scenario, otlp_endpoint=None): + root.mkdir() + with ExitStack() as stack: + evidence = stack.enter_context(service(dll, root, "evidence", otlp_endpoint=otlp_endpoint, scenario=scenario)) + triage = stack.enter_context(service(dll, root, "triage", evidence["url"], otlp_endpoint=otlp_endpoint)) + opener = build_opener(ProxyHandler({})) + question = {"question": f"Why did checkout-api errors spike? {MARKERS[0]}"} + url = triage["url"] + f"/triage/{INCIDENT}" + responses = [] + for _ in range(REQUEST_COUNT): + request = Request(url, data=json.dumps(question).encode(), method="POST", + headers={"Content-Type": "application/json"}) + with opener.open(request, timeout=12) as reply: + responses.append({"status": reply.status, "body": json.loads(reply.read())}) + (root / "http-request.json").write_text(json.dumps( + {"method": "POST", "url": url, "body": question, "repetitions": REQUEST_COUNT}, indent=2) + "\n", encoding="utf-8") + (root / "http-responses.json").write_text(json.dumps(responses, indent=2) + "\n", encoding="utf-8") + + +def verify_case(root): + failed = root.name == "failed" + downstream_code = 503 if failed else 200 + triage_ready = read_json(root / "triage" / "ready.json") + evidence_ready = read_json(root / "evidence" / "ready.json") + assert triage_ready["role"] == "triage" and evidence_ready["role"] == "evidence" + assert triage_ready["pid"] != evidence_ready["pid"] + assert triage_ready["url"] != evidence_ready["url"] + assert triage_ready["captureEnvironment"] == evidence_ready["captureEnvironment"] == "true" + triage = read_spans(root / "triage" / "spans.jsonl") + evidence = read_spans(root / "evidence" / "spans.jsonl") + assert len(triage) == REQUEST_COUNT * 7 and len(evidence) == REQUEST_COUNT + assert all(span["resource"]["service.name"] == "dotnet-guide-triage-api" + and span["processId"] == triage_ready["pid"] for span in triage) + assert all(span["resource"]["service.name"] == "dotnet-guide-evidence-api" + and span["processId"] == evidence_ready["pid"] for span in evidence) + + request = read_json(root / "http-request.json") + assert request["method"] == "POST" and request["url"] == triage_ready["url"] + f"/triage/{INCIDENT}" + assert request["repetitions"] == REQUEST_COUNT and MARKERS[0] in request["body"]["question"] + responses = read_json(root / "http-responses.json") + ids = {response["body"]["traceId"] for response in responses} + assert len(responses) == len(ids) == REQUEST_COUNT + assert ids == {span["traceId"] for span in [*triage, *evidence]} + + traces = [] + for response in responses: + trace_id = response["body"]["traceId"] + receiver, = (span for span in evidence if span["traceId"] == trace_id) + trace = verify_trace([span for span in triage if span["traceId"] == trace_id], + receiver, evidence_ready["url"], response, failed, downstream_code) + traces.append(trace) + assert all(topology(trace) == topology(traces[0]) for trace in traces) + print(f"PASS {root.name}: {REQUEST_COUNT} successful Triage responses with the expected eight-span trace") + return traces + + +def verify_trace(triage, receiver, evidence_url, response, failed, downstream_code): + server, = (span for span in triage if span["kind"] == "Server") + lookup, = (span for span in triage if span["source"] == "DotnetGuide.Triage") + client, = (span for span in triage if span["source"] == "System.Net.Http" and span["kind"] == "Client") + ai = [span for span in triage if span["source"] == AI_SOURCE] + assert len(ai) == 4 + orchestration, = (span for span in ai if span["name"] == "orchestrate_tools") + tool, = (span for span in ai if span["name"] == "execute_tool lookup_evidence") + model_calls = [span for span in ai if span["name"] == "chat scripted-model"] + first, final = sorted(model_calls, key=lambda span: span["attributes"]["gen_ai.response.id"]) + + spans = [*triage, receiver] + trace_id = server["traceId"] + assert re.fullmatch(r"[0-9a-f]{32}", trace_id) and int(trace_id, 16) + assert all(span["traceId"] == trace_id for span in spans) + assert all(re.fullmatch(r"[0-9a-f]{16}", span["spanId"]) and int(span["spanId"], 16) for span in spans) + assert len({span["spanId"] for span in spans}) == 8 + assert server["parentSpanId"] == "0" * 16 + assert lookup["name"] == "dotnet-guide.triage.evidence_lookup" and lookup["kind"] == "Internal" + assert tool["kind"] == orchestration["kind"] == "Internal" and receiver["kind"] == "Server" + assert_parent(orchestration, server) + for span in (first, tool, final): + assert_parent(span, orchestration) + assert_parent(lookup, tool) + assert_parent(client, lookup) + assert_parent(receiver, client) + assert triage.index(first) < triage.index(client) < triage.index(lookup) < triage.index(tool) < triage.index(final) + assert tool["attributes"]["gen_ai.tool.name"] == "lookup_evidence" + assert tool["attributes"]["gen_ai.tool.call.id"] == "telemetry-evidence-call" + + for number, model_span, finish_reason in [(1, first, "tool_calls"), (2, final, "stop")]: + attrs = model_span["attributes"] + assert model_span["kind"] == "Client" + assert attrs["gen_ai.operation.name"] == "chat" and attrs["gen_ai.provider.name"] == "dotnet-guide-scripted" + assert attrs["gen_ai.request.model"] == attrs["gen_ai.response.model"] == "scripted-model" + assert attrs["gen_ai.response.id"] == f"scripted-response-{number}" + assert (attrs["gen_ai.usage.input_tokens"], attrs["gen_ai.usage.output_tokens"]) == (11, 7) + assert json.loads(attrs["gen_ai.response.finish_reasons"]) == [finish_reason] + + expected_lookup_tags = { + "dotnet_guide.evidence.http_status_code": downstream_code, + "dotnet_guide.evidence.outcome": "unavailable" if failed else "available", + } + if failed: + expected_lookup_tags["error.type"] = "evidence_unavailable" + assert lookup["status"] == ("Error" if failed else "Ok") + assert lookup["attributes"] == expected_lookup_tags + assert lookup["statusDescription"] is None and lookup["events"] == [] + + assert tool["status"] == ("Error" if failed else "Unset"), "Incorrect tool span status." + assert tool["attributes"].get("error.type") == ("evidence_unavailable" if failed else None) + assert all(span["status"] == "Unset" for span in (orchestration, first, final)) + for span, method, code in [(server, "POST", 200), (client, "GET", downstream_code), + (receiver, "GET", downstream_code)]: + assert span["status"] == ("Error" if code == 503 else "Unset") + assert span["attributes"]["http.request.method"] == method + assert span["attributes"]["http.response.status_code"] == code + assert span["attributes"].get("error.type") == ("503" if code == 503 else None) + assert server["attributes"]["http.route"] == "/triage/{incidentId}" + assert receiver["attributes"]["http.route"] == "/evidence/{incidentId}" + assert client["attributes"]["url.full"] == evidence_url + f"/evidence/{INCIDENT}" + + assert response["status"] == 200 + body = response["body"] + assert body["evidenceAvailable"] is (not failed) + assert body["probe"] == { + "modelCalls": 2, "toolCalls": 1, "sawPrompt": True, + "sawToolArgument": True, "sawToolResult": True, "sawEvidence": not failed, + "sawUnavailableEvidence": failed, + } + assert body["processId"] == server["processId"] + assert body["traceId"] == trace_id and body["spanId"] == server["spanId"] + if failed: + assert body["evidence"] is None, "Fallback must not return evidence." + assert body["answer"] == f"Evidence is unavailable. The cause is unconfirmed. {MARKERS[4]}" + else: + downstream = body["evidence"] + assert downstream["incidentId"] == INCIDENT + assert all(item in body["answer"] for item in ("E-201", "E-101", "The cause is unconfirmed.", MARKERS[4])) + assert all(item in downstream["evidence"] for item in ("E-201", "E-101", MARKERS[3])) + assert downstream["processId"] == receiver["processId"] + assert downstream["traceId"] == trace_id and downstream["spanId"] == receiver["spanId"] + assert downstream["parentSpanId"] == receiver["parentSpanId"] + version, header_trace_id, parent_id, flags = downstream["receivedTraceparent"].split("-") + assert version == "00" and header_trace_id == trace_id and parent_id == client["spanId"] + assert re.fullmatch(r"[0-9a-f]{2}", flags) and int(flags, 16) & 1 + + return { + "Triage API": server, "Tool orchestration": orchestration, "First chat": first, + "Evidence tool": tool, "Custom lookup": lookup, "Outbound HttpClient": client, + "Evidence API": receiver, "Final chat": final, + } + + +def assert_parent(child, parent): + assert child["parentSpanId"] == parent["spanId"], (child["name"], parent["name"]) + + +def topology(trace): + labels = {span["spanId"]: label for label, span in trace.items()} + return {label: (span["source"], span["name"], span["kind"], labels.get(span["parentSpanId"])) + for label, span in trace.items()} + + +def scan_fields(value, path=()): + if isinstance(value, dict): + for key, entry in value.items(): + yield from scan_fields(key, (*path, key, "")) + yield from scan_fields(entry, (*path, key)) + elif isinstance(value, list): + for index, entry in enumerate(value): + yield from scan_fields(entry, (*path, index)) + elif isinstance(value, str): + for marker in MARKERS: + if marker in value: + yield marker, list(path) + + +HTTP_SERVER = "http.server.request.duration" +HTTP_CLIENT = "http.client.request.duration" +AI_DURATION = "gen_ai.client.operation.duration" +AI_TOKENS = "gen_ai.client.token.usage" +LOOKUP = "dotnet_guide.evidence.lookup.duration" + + +def metric_series(snapshot, name, meter, unit, series_count=1): + metric, = (metric for metric in snapshot["metrics"] if metric["name"] == name) + assert metric["meterName"] == meter and metric["unit"] == unit, (name, metric) + assert metric["type"] == "Histogram" and metric["temporality"] == "Cumulative", name + points = metric["points"] + assert series_count is None or len(points) == series_count, (name, points) + for point in points: + assert math.isfinite(point["sum"]) and point["sum"] >= 0, name + buckets = point["buckets"] + assert buckets and buckets[-1]["upperBound"] is None + assert all(bucket["count"] >= 0 for bucket in buckets) + assert sum(bucket["count"] for bucket in buckets) == point["count"] + return points + + +def verify_point(point, count, attributes): + assert point["count"] == count, (point["count"], count) + assert point["attributes"] == attributes, (point["attributes"], attributes) + + +def verify_metrics(root): + failed = root.name == "failed" + triage = read_json(root / "triage" / "metrics.json") + evidence = read_json(root / "evidence" / "metrics.json") + for role, snapshot, names in [ + ("triage", triage, {HTTP_SERVER, HTTP_CLIENT, AI_DURATION, AI_TOKENS, LOOKUP}), + ("evidence", evidence, {HTTP_SERVER}), + ]: + assert snapshot["resource"]["service.name"] == f"dotnet-guide-{role}-api" + assert snapshot["processId"] == read_json(root / role / "ready.json")["pid"] + assert {metric["name"] for metric in snapshot["metrics"]} == names + assert not list(scan_fields(snapshot)), f"Unexpected payload marker in {role} metrics." + + triage_http, = metric_series(triage, HTTP_SERVER, "Microsoft.AspNetCore.Hosting", "s") + evidence_http, = metric_series(evidence, HTTP_SERVER, "Microsoft.AspNetCore.Hosting", "s") + client_series = metric_series(triage, HTTP_CLIENT, "System.Net.Http", "s", series_count=None) + client_http, = (point for point in client_series if point["attributes"]["http.request.method"] == "GET") + otlp_endpoint = read_json(root / "triage" / "ready.json")["otlpEndpoint"] + if otlp_endpoint is None: + assert len(client_series) == 1 + else: + exporter_http, = (point for point in client_series if point["attributes"]["http.request.method"] == "POST") + assert len(client_series) == 2 + exporter_endpoint = urlsplit(otlp_endpoint) + assert exporter_http["count"] >= 1 + assert exporter_http["attributes"] == { + "http.request.method": "POST", "http.response.status_code": 200, + "network.protocol.version": "1.1", "server.address": exporter_endpoint.hostname, + "server.port": exporter_endpoint.port, "url.scheme": "http", + } + lookup, = metric_series(triage, LOOKUP, "DotnetGuide.Triage", "s") + ai_duration, = metric_series(triage, AI_DURATION, AI_SOURCE, "s") + token_series = metric_series(triage, AI_TOKENS, AI_SOURCE, "{token}", series_count=2) + + common_http = {"network.protocol.version": "1.1", "url.scheme": "http"} + downstream_http = {**common_http, "http.request.method": "GET", + "http.response.status_code": 503 if failed else 200} + if failed: + downstream_http["error.type"] = "503" + evidence_port = urlsplit(read_json(root / "evidence" / "ready.json")["url"]).port + verify_point(triage_http, REQUEST_COUNT, { + **common_http, "http.request.method": "POST", "http.response.status_code": 200, + "http.route": "/triage/{incidentId}", + }) + verify_point(evidence_http, REQUEST_COUNT, {**downstream_http, "http.route": "/evidence/{incidentId}"}) + verify_point(client_http, REQUEST_COUNT, { + **downstream_http, "server.address": "127.0.0.1", "server.port": evidence_port, + }) + verify_point(lookup, REQUEST_COUNT, {"dotnet_guide.evidence.outcome": "unavailable" if failed else "available"}) + + ai_tags = { + "gen_ai.operation.name": "chat", + "gen_ai.provider.name": "dotnet-guide-scripted", + "gen_ai.request.model": "scripted-model", + "gen_ai.response.model": "scripted-model", + } + calls = REQUEST_COUNT * 2 + verify_point(ai_duration, calls, ai_tags) + tokens = {point["attributes"]["gen_ai.token.type"]: point for point in token_series} + assert set(tokens) == {"input", "output"} + for key, per_call in [("input", 11), ("output", 7)]: + verify_point(tokens[key], calls, {**ai_tags, "gen_ai.token.type": key}) + assert tokens[key]["sum"] == per_call * calls, f"Incorrect scripted {key} token total." + + means = {label: point["sum"] / point["count"] * 1000 for label, point in [ + ("triageHttpMs", triage_http), ("evidenceHttpMs", evidence_http), + ("outboundHttpMs", client_http), ("lookupMs", lookup), ("chatMs", ai_duration) + ]} + print(f"PASS {root.name} metrics: {REQUEST_COUNT} HTTP/lookup observations, {calls} chat observations, " + f"{tokens['input']['sum']:.0f} input and {tokens['output']['sum']:.0f} output synthetic tokens") + print(f" Evidence HTTP mean {means['evidenceHttpMs']:.2f} ms | lookup mean {means['lookupMs']:.2f} ms") + return { + "requests": REQUEST_COUNT, + "modelCalls": calls, + "scriptedInputTokens": tokens["input"]["sum"], + "scriptedOutputTokens": tokens["output"]["sum"], + "evidenceHttpFailures": evidence_http["count"] if evidence_http["attributes"]["http.response.status_code"] >= 500 else 0, + "triageHttpFailures": triage_http["count"] if triage_http["attributes"]["http.response.status_code"] >= 500 else 0, + "unavailableLookups": lookup["count"] if lookup["attributes"]["dotnet_guide.evidence.outcome"] == "unavailable" else 0, + "meansMilliseconds": means, + } + + +def verify(root): + traces = {case: verify_case(root / case) for case in SCENARIOS} + all_traces = [trace for pair in traces.values() for trace in pair] + assert len({trace["Triage API"]["traceId"] for trace in all_traces}) == len(all_traces) + assert all(topology(trace) == topology(all_traces[0]) for trace in all_traces) + for trace in all_traces: + assert not list(scan_fields(list(trace.values()))), "Unexpected payload marker in a captured span." + + summary = {case: verify_metrics(root / case) for case in SCENARIOS} + healthy = summary["healthy"]["meansMilliseconds"] + slow = summary["slow"]["meansMilliseconds"] + assert slow["evidenceHttpMs"] >= DELAY_MS * 0.90 + assert slow["evidenceHttpMs"] - healthy["evidenceHttpMs"] >= DELAY_MS * 0.70 + assert slow["lookupMs"] - healthy["lookupMs"] >= DELAY_MS * 0.70 + assert slow["chatMs"] < slow["evidenceHttpMs"] * 0.25 + print("PASS slow delay visible in aggregate Evidence and lookup duration") + print("PASS derived unavailable count: failed 2/2 lookups; all six Triage calls returned HTTP 200") + print("PASS synthetic markers absent across all captured metrics and spans") + if read_json(root / "healthy/triage/ready.json")["otlpEndpoint"]: + print("PASS application HTTP GET and telemetry export POST metric series identified independently") + return summary + + +def verify_capture_control(control_dll, root): + exercise(control_dll, root, "healthy") + traces = verify_case(root) + for trace in traces: + hits = {marker for marker, _ in scan_fields(list(trace.values()))} + assert hits == set(MARKERS), ("capture control did not expose every canary", hits) + print("PASS capture-enabled known-leak control exposed all five canary classes") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("results", type=Path) + parser.add_argument("--app", type=Path, required=True) + parser.add_argument("--capture-control", type=Path) + args = parser.parse_args() + root = args.results.resolve() + for scenario in SCENARIOS: + exercise(args.app.resolve(), root / scenario, scenario) + summary = verify(root) + if args.capture_control: + control = root / "capture-control" + control.mkdir() + verify_capture_control(args.capture_control.resolve(), control / "healthy") + + (root / "metrics-summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + print("PASS deterministic topology, slow path, Evidence 503 fallback, metrics, and privacy") diff --git a/dotnet-ai/opentelemetry-ai-observability/verify.sh b/dotnet-ai/opentelemetry-ai-observability/verify.sh new file mode 100755 index 0000000..674e3bc --- /dev/null +++ b/dotnet-ai/opentelemetry-ai-observability/verify.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")" + +mode=${1:---offline} +case "$mode" in + --offline) [[ $# -le 1 ]] ;; + --jaeger) [[ $# -eq 3 ]] ;; + --live) [[ $# -eq 5 ]] ;; + *) + printf '%s\n' 'Usage: bash verify.sh [--offline | --jaeger QUERY_URL OTLP_URL | --live QUERY_URL OTLP_URL MODEL_ENDPOINT MODEL_ID]' >&2 + exit 2 + ;; +esac + +export DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_NOLOGO=1 DOTNET_NUGET_SIGNATURE_VERIFICATION=true +results=$(mktemp -d "$PWD/results.XXXXXXXX") +scratch=$(mktemp -d) +trap 'rm -rf -- "$scratch"' EXIT + +printf 'Verification evidence directory: %s\n' "$results" +( + app="$PWD/src/ObservabilityLab/bin/Release/net10.0/ObservabilityLab.dll" + dotnet restore OpenTelemetryAiObservability.slnx --locked-mode --configfile NuGet.Config + dotnet build OpenTelemetryAiObservability.slnx --configuration Release --no-restore + + case "$mode" in + --offline) + cp -- src/ObservabilityLab/*.cs src/ObservabilityLab/*.csproj src/ObservabilityLab/packages.lock.json "$scratch/" + cp -- global.json NuGet.Config "$scratch/" + ( + cd -- "$scratch" + dotnet restore ObservabilityLab.csproj --locked-mode --configfile NuGet.Config + dotnet build ObservabilityLab.csproj --configuration Release --no-restore -p:DefineConstants=DG_SYNTHETIC_CAPTURE_CONTROL + ) + python3 -E tests/verify_local_signals.py "$results" --app "$app" \ + --capture-control "$scratch/bin/Release/net10.0/ObservabilityLab.dll" + ;; + --jaeger) + python3 -E tests/check_jaeger.py "$results" --app "$app" --query "$2" --otlp "$3" + ;; + --live) + python3 -E tests/check_live.py "$results" --app "$app" --query "$2" --otlp "$3" \ + --model-endpoint "$4" --model-id "$5" + ;; + esac +) 2>&1 | tee "$results/verification.log"