diff --git a/.github/workflows/build-samples.yml b/.github/workflows/build-samples.yml index 93e3ec4..b630030 100644 --- a/.github/workflows/build-samples.yml +++ b/.github/workflows/build-samples.yml @@ -8,6 +8,7 @@ on: - "dotnet-ai/hybrid-search-ef-core-pgvector/**" - "dotnet-ai/agent-framework-incident-triage/**" - "dotnet-ai/mcp-server-csharp-dotnet/**" + - "dotnet-ai/microsoft-extensions-ai-evaluation/**" - "dotnet-aspire/orchestrate-distributed-system/**" - "software-architecture/architecture-testing-dotnet/**" - "distributed-systems/transactional-outbox-ef-core/**" @@ -41,6 +42,7 @@ on: - "dotnet-ai/hybrid-search-ef-core-pgvector/**" - "dotnet-ai/agent-framework-incident-triage/**" - "dotnet-ai/mcp-server-csharp-dotnet/**" + - "dotnet-ai/microsoft-extensions-ai-evaluation/**" - "dotnet-aspire/orchestrate-distributed-system/**" - "software-architecture/architecture-testing-dotnet/**" - "distributed-systems/transactional-outbox-ef-core/**" @@ -2102,3 +2104,38 @@ jobs: --no-build -- src/FirstMcpServer/bin/Release/net10.0/FirstMcpServer.dll + + test-microsoft-extensions-ai-evaluation: + name: Test Microsoft.Extensions.AI.Evaluation sample + runs-on: ubuntu-latest + + defaults: + run: + working-directory: dotnet-ai/microsoft-extensions-ai-evaluation + + 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: Restore + run: dotnet restore MicrosoftExtensionsAIEvaluation.slnx + + - name: Build Release + run: dotnet build MicrosoftExtensionsAIEvaluation.slnx --configuration Release --no-restore + + - name: Run offline tests + run: dotnet test MicrosoftExtensionsAIEvaluation.slnx --configuration Release --no-build --no-restore + + - name: Reproduce and compare both offline scorecards + run: | + dotnet run --project src/EvaluationRunner --configuration Release --no-build --no-restore -- . "$RUNNER_TEMP/evaluation-candidate.md" + 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" diff --git a/README.md b/README.md index 602f919..4c5bcbe 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Each sample folder contains a focused implementation of one tutorial topic. The | [`dotnet-ai/hybrid-search-ef-core-pgvector`](dotnet-ai/hybrid-search-ef-core-pgvector/) | Verified .NET 10 API combining PostgreSQL full-text search (GIN) and pgvector cosine retrieval (HNSW), fused with Reciprocal Rank Fusion | [Hybrid Search in .NET with EF Core 10 and pgvector](https://www.dotnet-guide.com/tutorials/dotnet-ai/hybrid-search-ef-core-pgvector/) | | [`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-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/) | @@ -91,6 +92,15 @@ dotnet build .\FirstMcpServer.slnx --configuration Release --no-restore dotnet test .\tests\FirstMcpServer.Tests\FirstMcpServer.Tests.csproj --configuration Release --no-build dotnet run --project .\src\McpClientDemo\McpClientDemo.csproj --configuration Release --no-build -- .\src\FirstMcpServer\bin\Release\net10.0\FirstMcpServer.dll ``` +### Microsoft.Extensions.AI.Evaluation incident triage + +```powershell +cd dotnet-ai\microsoft-extensions-ai-evaluation +dotnet test .\MicrosoftExtensionsAIEvaluation.slnx --configuration Release +dotnet run --project .\src\EvaluationRunner --configuration Release -- . +dotnet run --project .\src\EvaluationRunner --configuration Release -- --repaired . +``` + ## Repository structure ```text @@ -119,13 +129,21 @@ tutorials/ | | |-- docs/ | | |-- src/ | | `-- tests/ -| `-- mcp-server-csharp-dotnet/ -| |-- FirstMcpServer.slnx -| |-- README.md -| |-- global.json -| |-- verified-environment.json -| |-- docs/ -| |-- scripts/ +| |-- mcp-server-csharp-dotnet/ +| | |-- FirstMcpServer.slnx +| | |-- README.md +| | |-- global.json +| | |-- verified-environment.json +| | |-- docs/ +| | |-- scripts/ +| | |-- src/ +| | `-- tests/ +| `-- microsoft-extensions-ai-evaluation/ +| |-- MicrosoftExtensionsAIEvaluation.slnx +| |-- cases/ +| |-- prompts/ +| |-- responses/ +| |-- reports/ | |-- src/ | `-- tests/ |-- dotnet-aspire/ diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/.gitattributes b/dotnet-ai/microsoft-extensions-ai-evaluation/.gitattributes new file mode 100644 index 0000000..063446e --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/.gitattributes @@ -0,0 +1,3 @@ +/prompts/*.txt -text +/examples/provenance/prompt.txt -text +/reports/*.md text eol=lf diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/MicrosoftExtensionsAIEvaluation.slnx b/dotnet-ai/microsoft-extensions-ai-evaluation/MicrosoftExtensionsAIEvaluation.slnx new file mode 100644 index 0000000..f62af6c --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/MicrosoftExtensionsAIEvaluation.slnx @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/README.md b/dotnet-ai/microsoft-extensions-ai-evaluation/README.md new file mode 100644 index 0000000..4fc7433 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/README.md @@ -0,0 +1,183 @@ +# Microsoft.Extensions.AI.Evaluation incident triage sample + +This solution implements five `Microsoft.Extensions.AI.Evaluation.IEvaluator` +checks against the validated Step 2 dataset and compares baseline and +candidate results for each incident and check. The release policy combines +those results into a SHIP, REVIEW, or BLOCK decision. The evaluators consume response JSON +and case evidence. They require neither a model endpoint nor an API key. + +- [12-case incident evaluation dataset](docs/dataset.md) +- [Baseline vs candidate scorecard](reports/candidate-scorecard.md) +- [Baseline vs repaired scorecard](reports/repaired-scorecard.md) + +## Reproduce the candidate scorecard + +From the extracted sample root, run: + +```powershell +dotnet run --project src/EvaluationRunner -c Release -- . +``` + +To save the output, pass a second path: + +```powershell +dotnet run --project src/EvaluationRunner -c Release -- . candidate-scorecard.local.md +``` + +The runner validates the case and prompt metadata on all 24 hand-authored +responses, evaluates five hard checks per incident and run, and compares +all 60 paired results. The [candidate scorecard](reports/candidate-scorecard.md) +records **BLOCK**. Both prompts pass nine cases overall. The per-check results +show four regressions, two improvements, and one existing noncritical failure. + +The command exits successfully after producing the scorecard because the +replay ran successfully. The release decision is shown in the scorecard. +Invalid fixture sets stop replay with a nonzero exit code. The test suite +checks the expected BLOCK and requires a byte-for-byte scorecard match. + +The fixtures reproduce the intended tutorial examples without model calls. +The prompt files and matching fixtures are illustrative material. + +## Diagnose and replay the repair + +Start with the original failing incident: + +```powershell +dotnet run --project src/EvaluationRunner -c Release -- --case incident-01-temporal-correlation . +``` + +This diagnostic compares candidate v2 with repaired v3. Cause support and +unknown preservation improve from FAIL to PASS. It provides quick feedback +on one case. Then run the full repaired suite for a release decision: + +```powershell +dotnet run --project src/EvaluationRunner -c Release -- --repaired . +``` + +The full replay compares repaired v3 against the original baseline v1. +All 12 repaired fixtures pass all five checks. The [repaired scorecard](reports/repaired-scorecard.md) +records **SHIP** under this tutorial's fixture policy. It shows three +citation improvements versus baseline and 57 unchanged passes. The +original candidate scorecard still reproduces **BLOCK**. + +Repaired v3 requires evidence that establishes a cause. It also asks for +citations when documenting a gap in the data. All 12 repaired responses +are hand-authored to illustrate these changes. The replay verifies the +harness and its release decision on those fixtures. + +## Run the tests + +Use .NET SDK 10.0.404 or a later patch in the same SDK feature band. +From the extracted folder, run: + +```powershell +dotnet test MicrosoftExtensionsAIEvaluation.slnx -c Release +``` + +The initial restore needs a reachable NuGet feed. The solution targets +`net10.0` and uses `Microsoft.Extensions.AI.Evaluation` 10.11.1. + +## Hard checks + +| Check | What it evaluates | Severity on failure | +|---|---|---| +| Response contract | JSON fields and types, unique IDs, and cause-status/null consistency | Critical | +| Required citations | Every required evidence ID is cited | Critical when the case's `critical` flag is true | +| Citation validity | Every cited ID exists in the current case | Critical | +| Unknown preservation | The response preserves the expected unknowns and avoids marking other facts unknown | Critical when a required critical unknown is omitted | +| Cause support | The cause status and cause ID agree with the case | Critical when the response asserts a confirmed cause that disagrees with the case | + +Every evaluator returns a named `BooleanMetric` with a reason. A failed +metric records severity in `dotnet-guide.severity` metadata. Invalid JSON fails +the response contract. The remaining checks return a null metric with +`Not evaluated` in the reason, since the fields cannot be trusted. A +case-specific evaluator requires an `IncidentEvaluationContext`. + +The general response contract checks that the summary has text. A human can +review its meaning. The tests demonstrate a well-formed response with an +unsupported claim in the summary whose structured checks all pass. + +The canonical unsupported-cause example has valid JSON and citations. It fails +cause support and unknown preservation, each at critical severity. Both that +example and the passing examples are hand-authored. The tests also construct +expected structured responses for all 12 cases to exercise the checks. + +## Compare two evaluation runs + +Use `HardCheckResult.FromMetric` to pair a named `BooleanMetric` with its +incident ID, then pass the resulting rows from both runs to +`HardCheckComparer.Compare`. The result preserves the reason and any failure +severity from each run. + +| Baseline | Candidate | Classification | +|---|---|---| +| Pass | Pass | Unchanged pass | +| Pass | Fail | Regression | +| Fail | Pass | Improvement | +| Fail | Fail | Existing failure | +| Either result was unevaluated | | Not comparable | + +The comparer pairs rows by the case ID and check name. Input order does not +affect the pairing. Duplicate keys, empty inputs, and keys present in only one +run raise an error. A full-suite caller must still verify that both runs +cover the expected cases and checks. + +In the tested incident-01 example, the baseline leaves the cause unconfirmed +and the candidate asserts an unsupported cause. Their cause support row +is classified as a regression with critical candidate severity. + +## Mixed-failure walkthrough + +Use `incident-03-latency-and-feature-flag` as a second scenario. Its baseline +and candidate response files in `examples/` are hand-authored. + +The baseline reports the latency alert and leaves the cause unconfirmed. +It omits the evidence ID for the flag rollout. The candidate cites both +records, then claims the flag caused the latency increase. The evidence +only shows that the rollout preceded the alert. + +| Hard check | Baseline | Candidate | Classification | +|---|---|---|---| +| Response contract | Pass | Pass | Unchanged pass | +| Required citations | Fail | Pass | Improvement | +| Citation validity | Pass | Pass | Unchanged pass | +| Unknown preservation | Pass | Fail | Regression | +| Cause support | Pass | Fail | Critical regression | + +Both responses fail overall. The per-check comparison shows why they failed +and preserves the improvement. The release-policy test returns `BLOCK` +and identifies cause support as a blocker. + +## Evaluate a release + +Pass the comparison rows and the independent list of expected incident and +check pairs to `ReleasePolicy.Evaluate`. For a full run, derive the expected +pairs from the configured cases and evaluator names. Use the original +baseline for both candidate and repaired release decisions. + +The returned assessment includes the decision and reasons for its issues. +See [the evaluation policy](docs/evaluation-policy.md) for the decision +table, coverage handling, and the optional quality review signal. + +## Verify a saved response + +`PromptIdentity` computes a SHA-256 hash of the exact UTF-8 prompt. +`ResponseFixture.Load` requires the expected case and prompt. It rejects +a fixture whose case ID, prompt ID, prompt version, or prompt hash differs. +The loader preserves the response text for the evaluators. + +See [response provenance](docs/response-provenance.md) for the metadata +contract and the hand-authored example. + +## Optional live evaluation + +For model-generated evidence, see [optional live evaluation](docs/live-evaluation.md). +The runner captures baseline and candidate outputs into a separate run folder +and writes detailed reports. The committed offline scorecards continue to use +their hand-authored fixtures. The test suite uses scripted clients for live +runner coverage. + +## Verification + +See the [verification record](docs/verified-environment.md) and +[scope](SCOPE.md) for the offline and live evidence. diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/SCOPE.md b/dotnet-ai/microsoft-extensions-ai-evaluation/SCOPE.md new file mode 100644 index 0000000..698b82d --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/SCOPE.md @@ -0,0 +1,16 @@ +# Sample scope + +This sample teaches prompt regression testing with +`Microsoft.Extensions.AI.Evaluation`. It uses synthetic incident evidence +to show how an answer can improve one hard check and regress on another. + +The sample includes 12 incidents, five deterministic checks, and three +sets of hand-authored responses tied to versioned prompts. Compare the +candidate and repaired prompts against the original baseline. The offline +policy applies to the structured response contract and the case evidence. +Read the free-text summary separately for unsupported claims. + +The optional live runner captures separate model responses and writes +hard-check and optional coherence results. Its output is independent of the +committed offline scorecards. See the [live evidence](docs/live-evaluation.md) +for the limits of the verified models. diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-01-temporal-correlation.json b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-01-temporal-correlation.json new file mode 100644 index 0000000..6069099 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-01-temporal-correlation.json @@ -0,0 +1,31 @@ +{ + "id": "incident-01-temporal-correlation", + "category": "ambiguous-causation", + "question": "What happened to checkout-api relative to deploy-1842, and is the root cause confirmed?", + "requestedFactIds": [ + "root-cause" + ], + "evidence": [ + { + "id": "E-201", + "observation": "Deployment deploy-1842 completed at 14:02 UTC." + }, + { + "id": "E-101", + "observation": "The checkout-api error spike started at 14:09 UTC." + } + ], + "requiredEvidenceIds": [ + "E-101", + "E-201" + ], + "requiredUnknowns": [ + "root-cause" + ], + "expectedCauseStatus": "unconfirmed", + "expectedCauseId": null, + "critical": true, + "criticalUnknownIds": [ + "root-cause" + ] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-02-queue-and-scheduled-export.json b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-02-queue-and-scheduled-export.json new file mode 100644 index 0000000..bc60feb --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-02-queue-and-scheduled-export.json @@ -0,0 +1,35 @@ +{ + "id": "incident-02-queue-and-scheduled-export", + "category": "ambiguous-causation", + "question": "How did the queue backlog line up with the scheduled export, and is the root cause confirmed?", + "requestedFactIds": [ + "root-cause" + ], + "evidence": [ + { + "id": "E-202", + "observation": "The scheduled export started at 11:00 UTC." + }, + { + "id": "E-203", + "observation": "The fulfillment queue crossed its backlog threshold at 11:04 UTC." + }, + { + "id": "E-204", + "observation": "Worker CPU was below its alert threshold during that interval. No per-job worker trace is available." + } + ], + "requiredEvidenceIds": [ + "E-202", + "E-203" + ], + "requiredUnknowns": [ + "root-cause" + ], + "expectedCauseStatus": "unconfirmed", + "expectedCauseId": null, + "critical": false, + "criticalUnknownIds": [ + "root-cause" + ] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-03-latency-and-feature-flag.json b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-03-latency-and-feature-flag.json new file mode 100644 index 0000000..8a552b0 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-03-latency-and-feature-flag.json @@ -0,0 +1,33 @@ +{ + "id": "incident-03-latency-and-feature-flag", + "category": "ambiguous-causation", + "question": "What did the feature-flag audit and latency monitor record, and is the root cause confirmed?", + "requestedFactIds": [ + "root-cause" + ], + "evidence": [ + { + "id": "E-205", + "observation": "The ranking-v2 flag was enabled for 10 percent of traffic at 09:12 UTC." + }, + { + "id": "E-206", + "observation": "Search p95 latency exceeded 900 ms at 09:16 UTC." + }, + { + "id": "E-207", + "observation": "The available latency chart combines flagged and unflagged requests." + } + ], + "requiredEvidenceIds": [ + "E-205", + "E-206" + ], + "requiredUnknowns": [ + "root-cause" + ], + "expectedCauseStatus": "unconfirmed", + "expectedCauseId": null, + "critical": false, + "criticalUnknownIds": [] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-04-maintenance-window.json b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-04-maintenance-window.json new file mode 100644 index 0000000..8b2a2dc --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-04-maintenance-window.json @@ -0,0 +1,25 @@ +{ + "id": "incident-04-maintenance-window", + "category": "clear-evidence", + "question": "Summarize the approved maintenance window and the actual time service returned.", + "requestedFactIds": [], + "evidence": [ + { + "id": "E-304", + "observation": "The approved maintenance window was 01:00 to 01:30 UTC." + }, + { + "id": "E-305", + "observation": "The availability probe recorded service recovery at 01:21 UTC." + } + ], + "requiredEvidenceIds": [ + "E-304", + "E-305" + ], + "requiredUnknowns": [], + "expectedCauseStatus": "not-applicable", + "expectedCauseId": null, + "critical": false, + "criticalUnknownIds": [] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-05-confirmed-roll-back.json b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-05-confirmed-roll-back.json new file mode 100644 index 0000000..217406b --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-05-confirmed-roll-back.json @@ -0,0 +1,25 @@ +{ + "id": "incident-05-confirmed-roll-back", + "category": "clear-evidence", + "question": "Which build was restored and when did the rollback complete?", + "requestedFactIds": [], + "evidence": [ + { + "id": "E-306", + "observation": "The rollback changed the running build from build-42 to build-41." + }, + { + "id": "E-307", + "observation": "The rollout controller marked rollback complete at 18:26 UTC." + } + ], + "requiredEvidenceIds": [ + "E-306", + "E-307" + ], + "requiredUnknowns": [], + "expectedCauseStatus": "not-applicable", + "expectedCauseId": null, + "critical": false, + "criticalUnknownIds": [] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-06-impact-count.json b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-06-impact-count.json new file mode 100644 index 0000000..65786dc --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-06-impact-count.json @@ -0,0 +1,27 @@ +{ + "id": "incident-06-impact-count", + "category": "clear-evidence", + "question": "Which region and how many requests were affected during the measured interval?", + "requestedFactIds": [ + "affected-request-count" + ], + "evidence": [ + { + "id": "E-308", + "observation": "The measured interval was 13:00 to 13:10 UTC; only the east region had recorded failures." + }, + { + "id": "E-309", + "observation": "The finalized count for the east region and interval was 48 failed requests." + } + ], + "requiredEvidenceIds": [ + "E-308", + "E-309" + ], + "requiredUnknowns": [], + "expectedCauseStatus": "not-applicable", + "expectedCauseId": null, + "critical": false, + "criticalUnknownIds": [] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-07-missing-start-time.json b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-07-missing-start-time.json new file mode 100644 index 0000000..9503792 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-07-missing-start-time.json @@ -0,0 +1,29 @@ +{ + "id": "incident-07-missing-start-time", + "category": "missing-facts", + "question": "When was the first recorded failure, and what is the actual outage start time?", + "requestedFactIds": [ + "outage-start-time" + ], + "evidence": [ + { + "id": "E-407", + "observation": "The first recorded failed probe was at 06:15 UTC." + }, + { + "id": "E-408", + "observation": "The probe collector has no records from 05:55 UTC until 06:15 UTC; the actual onset is undetermined." + } + ], + "requiredEvidenceIds": [ + "E-407", + "E-408" + ], + "requiredUnknowns": [ + "outage-start-time" + ], + "expectedCauseStatus": "not-applicable", + "expectedCauseId": null, + "critical": false, + "criticalUnknownIds": [] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-08-unrecorded-rollback-completion.json b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-08-unrecorded-rollback-completion.json new file mode 100644 index 0000000..e4af3c5 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-08-unrecorded-rollback-completion.json @@ -0,0 +1,31 @@ +{ + "id": "incident-08-unrecorded-rollback-completion", + "category": "missing-facts", + "question": "When was rollback requested, and when did it complete?", + "requestedFactIds": [ + "rollback-completed-at" + ], + "evidence": [ + { + "id": "E-409", + "observation": "The operator requested rollback at 16:03 UTC." + }, + { + "id": "E-410", + "observation": "The controller lost its connection after accepting the request; completion and completion time are unconfirmed." + } + ], + "requiredEvidenceIds": [ + "E-409", + "E-410" + ], + "requiredUnknowns": [ + "rollback-completed-at" + ], + "expectedCauseStatus": "not-applicable", + "expectedCauseId": null, + "critical": true, + "criticalUnknownIds": [ + "rollback-completed-at" + ] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-09-missing-request-count.json b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-09-missing-request-count.json new file mode 100644 index 0000000..35acf05 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-09-missing-request-count.json @@ -0,0 +1,29 @@ +{ + "id": "incident-09-missing-request-count", + "category": "missing-facts", + "question": "Which region showed failures, and how many total requests were affected?", + "requestedFactIds": [ + "affected-request-count" + ], + "evidence": [ + { + "id": "E-411", + "observation": "Synthetic probes recorded failures in the west region between 12:00 and 12:20 UTC." + }, + { + "id": "E-412", + "observation": "Request logs are incomplete for that window. The probes cannot establish the total affected request count." + } + ], + "requiredEvidenceIds": [ + "E-411", + "E-412" + ], + "requiredUnknowns": [ + "affected-request-count" + ], + "expectedCauseStatus": "not-applicable", + "expectedCauseId": null, + "critical": false, + "criticalUnknownIds": [] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-10-confirmed-certificate-expiry.json b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-10-confirmed-certificate-expiry.json new file mode 100644 index 0000000..b0634e6 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-10-confirmed-certificate-expiry.json @@ -0,0 +1,28 @@ +{ + "id": "incident-10-confirmed-certificate-expiry", + "category": "confirmed-cause", + "question": "What caused the payment callback failures, and what confirms it?", + "requestedFactIds": [ + "root-cause" + ], + "evidence": [ + { + "id": "E-610", + "observation": "All affected TLS handshakes failed validation with an expired certificate. The certificate expired before the first failure." + }, + { + "id": "E-611", + "observation": "The incident review confirmed that the expired certificate caused the handshake failures. Replacing it restored callbacks without any other change.", + "confirmedCauseId": "CAUSE-CERTIFICATE-EXPIRED" + } + ], + "requiredEvidenceIds": [ + "E-610", + "E-611" + ], + "requiredUnknowns": [], + "expectedCauseStatus": "confirmed", + "expectedCauseId": "CAUSE-CERTIFICATE-EXPIRED", + "critical": true, + "criticalUnknownIds": [] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-11-confirmed-storage-quota.json b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-11-confirmed-storage-quota.json new file mode 100644 index 0000000..585d150 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-11-confirmed-storage-quota.json @@ -0,0 +1,28 @@ +{ + "id": "incident-11-confirmed-storage-quota", + "category": "confirmed-cause", + "question": "What caused invoice processing to stop accepting new jobs?", + "requestedFactIds": [ + "root-cause" + ], + "evidence": [ + { + "id": "E-612", + "observation": "The invoice worker recorded a filesystem quota error when each failed job tried to write its spool file." + }, + { + "id": "E-613", + "observation": "The incident review confirmed that the spool quota was exhausted. Raising that quota restored writes without other changes.", + "confirmedCauseId": "CAUSE-STORAGE-QUOTA-EXHAUSTED" + } + ], + "requiredEvidenceIds": [ + "E-612", + "E-613" + ], + "requiredUnknowns": [], + "expectedCauseStatus": "confirmed", + "expectedCauseId": "CAUSE-STORAGE-QUOTA-EXHAUSTED", + "critical": true, + "criticalUnknownIds": [] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-12-confirmed-config-mismatch.json b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-12-confirmed-config-mismatch.json new file mode 100644 index 0000000..eb69932 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/cases/incident-12-confirmed-config-mismatch.json @@ -0,0 +1,36 @@ +{ + "id": "incident-12-confirmed-config-mismatch", + "category": "confirmed-cause", + "question": "What caused the notifications outage, and what is the total affected request count?", + "requestedFactIds": [ + "root-cause", + "affected-request-count" + ], + "evidence": [ + { + "id": "E-614", + "observation": "Failed notifications read the wrong queue name from the service configuration." + }, + { + "id": "E-615", + "observation": "The incident review confirmed the queue-name mismatch caused the outage. Correcting the setting restored notifications.", + "confirmedCauseId": "CAUSE-QUEUE-NAME-MISMATCH" + }, + { + "id": "E-616", + "observation": "Partial request logging prevented a reliable total for the affected requests." + } + ], + "requiredEvidenceIds": [ + "E-614", + "E-615", + "E-616" + ], + "requiredUnknowns": [ + "affected-request-count" + ], + "expectedCauseStatus": "confirmed", + "expectedCauseId": "CAUSE-QUEUE-NAME-MISMATCH", + "critical": true, + "criticalUnknownIds": [] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/docs/dataset.md b/dotnet-ai/microsoft-extensions-ai-evaluation/docs/dataset.md new file mode 100644 index 0000000..fd6e30f --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/docs/dataset.md @@ -0,0 +1,20 @@ +# Incident evaluation dataset + +These 12 fictional cases pair documented observations with explicit evaluation expectations. The baseline, candidate, and repaired replays use the same cases. Each case is a standalone JSON file. + +| Case | What it covers | +|---|---| +| [incident-01-temporal-correlation](../cases/incident-01-temporal-correlation.json) | A deployment precedes an error spike. The cause remains unconfirmed. | +| [incident-02-queue-and-scheduled-export](../cases/incident-02-queue-and-scheduled-export.json) | A scheduled export precedes queue backlog. Worker traces are unavailable. | +| [incident-03-latency-and-feature-flag](../cases/incident-03-latency-and-feature-flag.json) | A flag rollout precedes a latency increase. The chart combines traffic groups. | +| [incident-04-maintenance-window](../cases/incident-04-maintenance-window.json) | Approved maintenance and service recovery times are recorded. | +| [incident-05-confirmed-roll-back](../cases/incident-05-confirmed-roll-back.json) | The restored build and completion time are recorded. | +| [incident-06-impact-count](../cases/incident-06-impact-count.json) | The region and affected request count are recorded. | +| [incident-07-missing-start-time](../cases/incident-07-missing-start-time.json) | The first observed failure is known. A coverage gap hides the true start time. | +| [incident-08-unrecorded-rollback-completion](../cases/incident-08-unrecorded-rollback-completion.json) | The rollback request is recorded. Completion remains unknown. | +| [incident-09-missing-request-count](../cases/incident-09-missing-request-count.json) | Probes show the affected region. Incomplete logs prevent a request count. | +| [incident-10-confirmed-certificate-expiry](../cases/incident-10-confirmed-certificate-expiry.json) | The incident review confirms certificate expiry. | +| [incident-11-confirmed-storage-quota](../cases/incident-11-confirmed-storage-quota.json) | The incident review confirms quota exhaustion. | +| [incident-12-confirmed-config-mismatch](../cases/incident-12-confirmed-config-mismatch.json) | The review confirms a queue name mismatch. The affected request count remains unknown. | + +Use the [case schema](../schemas/incident-case.schema.json) when adding a case and the [response schema](../schemas/incident-response.schema.json) for the evaluated answer. In a live run, pass only the question, requested fact IDs, and evidence to the model. The expected answers stay in the evaluator. diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/docs/evaluation-policy.md b/dotnet-ai/microsoft-extensions-ai-evaluation/docs/evaluation-policy.md new file mode 100644 index 0000000..7668805 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/docs/evaluation-policy.md @@ -0,0 +1,35 @@ +# Evaluation release policy + +The DOTNET GUIDE sample applies the policy to each incident and hard check. +A `BLOCK` finding takes precedence over `REVIEW`. An improvement is shown +in the comparison and cannot offset a blocker. + +| Baseline check | Candidate check | Candidate severity | Impact | +|---|---|---|---| +| Pass | Pass | — | None | +| Fail | Pass | — | Improvement | +| Pass | Fail | Either | **BLOCK**, new hard-check regression | +| Fail | Fail | Critical | **BLOCK**, critical failure remains | +| Fail | Fail | Noncritical | **REVIEW**, noncritical failure remains | +| Unevaluated | Fail | Critical | **BLOCK**, critical candidate failure | +| Unevaluated | Fail | Noncritical | **REVIEW**, comparison needs a baseline result | +| Any | Unevaluated | — | **REVIEW**, candidate has an unevaluated check | + +`SHIP` requires a passing candidate result for every expected hard check +and no optional quality concern. When a candidate passes a check that the +baseline could not evaluate, there is no current failure to investigate on +that check. Its comparison is still marked `NotComparable`. + +For a full release decision, the expected coverage is all 12 incidents and +all five hard checks. A missing result calls for `REVIEW` unless another +result already requires `BLOCK`. Duplicate or unexpected result keys are +input errors. Keep the original baseline for the candidate and repaired +release decisions. A direct candidate-to-repaired comparison can illustrate +what the fix changed. + +A caller can supply an optional, human-readable quality concern. It prompts +review if the candidate otherwise qualifies to ship. This policy does not +calculate quality scores or assign a universal threshold. + +The feature-flag example shows the rule in action. The citation check +improves, but cause support regresses and the release decision is `BLOCK`. diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/docs/hard-check-matrix.md b/dotnet-ai/microsoft-extensions-ai-evaluation/docs/hard-check-matrix.md new file mode 100644 index 0000000..79af638 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/docs/hard-check-matrix.md @@ -0,0 +1,17 @@ +# Hard-check matrix + +The release decision compares 12 cases across five hard checks, for 60 +paired results per proposal. The [candidate scorecard](../reports/candidate-scorecard.md) +and [repaired scorecard](../reports/repaired-scorecard.md) show the failing +or changed checks for each case. The tests verify all 60 transitions for +both proposals. + +In the feature-flag case, both baseline and candidate fail overall. +Required citations improve from FAIL to PASS. Cause support regresses from +PASS to FAIL because the candidate treats timing as proof. Unknown +preservation also regresses. The release policy records the improvement +and returns BLOCK for the regressions. + +A missing or unevaluated row is different from a failing row. See the +[evaluation policy](evaluation-policy.md) for how incomplete coverage and +critical findings affect the decision. diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/docs/live-evaluation.md b/dotnet-ai/microsoft-extensions-ai-evaluation/docs/live-evaluation.md new file mode 100644 index 0000000..a2225ba --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/docs/live-evaluation.md @@ -0,0 +1,73 @@ +# Optional live evaluation + +The separate runner uses an OpenAI-compatible chat endpoint. Pick an endpoint +and model supporting chat completions and JSON-object response format. The +generation model and settings are the same for baseline and candidate. The +system prompt is the variable. The case question, requested fact IDs, and +evidence are sent to the model. Evaluation expectations stay local. + +## Start with one case + +Set environment variables in PowerShell. This example assumes a compatible +server already listening on the local machine. + +```powershell +$env:DOTNET_EVAL_ENDPOINT = 'http://127.0.0.1:43181/v1' +$env:DOTNET_EVAL_MODEL = 'qwen2.5-0.5b-instruct' + +dotnet run --project src/LiveEvaluation -c Release -- . ../live-output incident-01-temporal-correlation +``` + +For a hosted endpoint, use its HTTPS API base, set its model ID, and supply +`DOTNET_EVAL_API_KEY` through your environment. Omit the final case ID to +generate responses for all 12 incidents with each prompt. + +Set `DOTNET_EVAL_JUDGE_MODEL` to opt into coherence scoring on the same +endpoint. A second model ID is supported if the endpoint exposes one. +`CoherenceEvaluator` scores the readable summary of each response that +passes the JSON contract. The model may return no parseable score. The +report preserves that diagnostic and the run summary counts scored and +attempted evaluations. Coherence remains separate from factual correctness. +See the [Microsoft Learn evaluation walkthrough](https://learn.microsoft.com/en-us/dotnet/ai/evaluation/evaluate-with-reporting). + +## Read the artifacts + +Each invocation creates a new run folder, whose path appears in the console. +The first request for each case and prompt must reach the generation client. +These responses are saved as `captured-live`, with prompt identity, model, +and generation settings. A repeat of the first request verifies a disk-cache +hit by checking both the response text and that the generation client received +no second call. The cache hit is counted separately. + +The run writes `responses/`, `generation-cache/`, `reports/`, and a +`run-summary.json`. The summary appears after a complete run. Use the run +folder printed by the command: + +```powershell +$run = '' +dotnet tool install Microsoft.Extensions.AI.Evaluation.Console --version 10.11.1 --tool-path "$run/tools" +& "$run/tools/aieval.exe" report --path "$run/reports" --output "$run/evaluation-report.html" +``` + +The HTML report shows persisted hard checks and any coherence evaluations. +The original offline scorecards remain the reproducible fixture examples. + +## Stage 10 verification + +The full generation run used Qwen2.5-0.5B-Instruct on a local llama.cpp +server, build b7124, without a hosted API call. It produced 12 baseline +and 12 candidate captures, verified one repeated-request cache hit, and +persisted 24 hard-check scenario results. The HTML report was generated +with `aieval` 10.11.1. Five responses passed the response contract +(three baseline and two candidate). The remaining responses and their +contract failures were retained in the report. + +The 0.5B coherence smoke run reached the judge twice, and the evaluator +persisted the two unparseable-score diagnostics. The deterministic test +suite also exercised the successful scoring path with scripted responses. + +A separate single-case smoke test used Qwen2.5-0.5B-Instruct for generation +and Qwen2.5-1.5B-Instruct as the judge. Generation and cache checks passed. +The judge returned responses for both prompts. The evaluator again recorded +two unparseable scores in the generated HTML report. A usable live coherence +score was not verified with these local models. diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/docs/response-provenance.md b/dotnet-ai/microsoft-extensions-ai-evaluation/docs/response-provenance.md new file mode 100644 index 0000000..8bb5fb4 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/docs/response-provenance.md @@ -0,0 +1,37 @@ +# Response provenance + +Use a response fixture to tie saved response text to the incident case and the +prompt used or represented. The file contains a `provenance` object and a +`responseText` JSON string. + +| Field | Meaning | +|---|---| +| `caseId` | Stable incident ID | +| `promptId` | Stable ID for the prompt | +| `promptVersion` | Version of that prompt | +| `promptHash` | Lowercase hexadecimal SHA-256 of the exact UTF-8 prompt text | +| `createdAt` | Fixture creation timestamp, with a UTC offset | +| `responseOrigin` | `captured-live` or `hand-authored-fixture` | +| `model` | Model recorded for a captured live response | +| `generationSettings` | Settings object recorded for a captured live response | + +The loader checks the case ID, prompt ID, and version before comparing the +hash. A prompt edit invalidates a fixture even when the ID and version stay +the same. The hash includes whitespace, line endings, and any UTF-8 byte order +mark. Preserve the prompt files' bytes across environments. Load the same +prompt text for hashing and for model generation. + +A `captured-live` response requires a model and a settings object. +A `hand-authored-fixture` has no model or generation settings. These are +declared origins. The hash verifies the prompt association. It does not +independently prove the response came from a model. Fresh generation, cache +retrieval, and offline replay describe how a run obtained a response. + +The fixture stores raw response text so malformed model responses can +reach the response-contract check without being repaired or reformatted. + +The files in [examples/provenance](../examples/provenance) contain a small +prompt and a matching hand-authored response for the temporal-correlation +case. They demonstrate fixture validation before the evaluator receives the +response. The complete baseline, candidate, and repaired sets live under `responses/`. +The report identifies their origin as hand-authored fixture replay. diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/docs/verified-environment.md b/dotnet-ai/microsoft-extensions-ai-evaluation/docs/verified-environment.md new file mode 100644 index 0000000..2a9c1bc --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/docs/verified-environment.md @@ -0,0 +1,20 @@ +# Verified environment + +The publication candidate was verified locally on Linux with .NET SDK +10.0.404 targeting `net10.0`. Evaluation, Quality, Reporting, and the +OpenAI client adapter are pinned to 10.11.1. + +| Check | Result | +|---|---| +| Restore and Release build | Passed. The build reported zero warnings and errors. | +| Deterministic tests | 104 passed without model calls. | +| Baseline vs candidate replay | All 60 comparisons verified. Scorecard reproduced BLOCK. | +| Baseline vs repaired replay | All 60 comparisons verified. Scorecard reproduced SHIP for the repaired fixtures. | +| Fixture provenance | All 36 response files reference their case and exact prompt hash. All are hand-authored. | + +The [optional live run](live-evaluation.md) generated 24 fresh local +responses, verified a disk-cache hit, persisted the results, and generated +the HTML report. The tested local judges returned no usable coherence +scores. The scripted test covers the successful scoring path. + +See the [machine-readable verification record](../verified-environment.json). diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-01-unconfirmed.json b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-01-unconfirmed.json new file mode 100644 index 0000000..1fb5f65 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-01-unconfirmed.json @@ -0,0 +1,12 @@ +{ + "summary": "Deployment deploy-1842 completed seven minutes before the error spike. The incident cause remains unconfirmed.", + "evidenceIds": [ + "E-101", + "E-201" + ], + "unknowns": [ + "root-cause" + ], + "causeStatus": "unconfirmed", + "cause": null +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-01-unsupported-cause.json b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-01-unsupported-cause.json new file mode 100644 index 0000000..8f26424 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-01-unsupported-cause.json @@ -0,0 +1,10 @@ +{ + "summary": "Deployment deploy-1842 caused the checkout-api incident.", + "evidenceIds": [ + "E-101", + "E-201" + ], + "unknowns": [], + "causeStatus": "confirmed", + "cause": "CAUSE-DEPLOYMENT" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-03-baseline.json b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-03-baseline.json new file mode 100644 index 0000000..9a4f9c7 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-03-baseline.json @@ -0,0 +1,7 @@ +{ + "summary": "Search p95 latency exceeded 900 ms at 09:16 UTC. The root cause remains unconfirmed.", + "evidenceIds": ["E-206"], + "unknowns": ["root-cause"], + "causeStatus": "unconfirmed", + "cause": null +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-03-candidate.json b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-03-candidate.json new file mode 100644 index 0000000..aa5a9a9 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-03-candidate.json @@ -0,0 +1,7 @@ +{ + "summary": "The ranking-v2 flag was enabled for 10 percent of traffic at 09:12 UTC. Search p95 latency exceeded 900 ms at 09:16 UTC. The flag change caused the latency increase.", + "evidenceIds": ["E-205", "E-206"], + "unknowns": [], + "causeStatus": "confirmed", + "cause": "CAUSE-RANKING-FLAG" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-04-not-applicable.json b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-04-not-applicable.json new file mode 100644 index 0000000..a27537c --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-04-not-applicable.json @@ -0,0 +1,10 @@ +{ + "summary": "The approved maintenance window was 01:00 to 01:30 UTC. Service returned at 01:21 UTC.", + "evidenceIds": [ + "E-304", + "E-305" + ], + "unknowns": [], + "causeStatus": "not-applicable", + "cause": null +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-10-confirmed.json b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-10-confirmed.json new file mode 100644 index 0000000..f53e0c2 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/incident-10-confirmed.json @@ -0,0 +1,10 @@ +{ + "summary": "The incident review confirmed that certificate expiration caused the callback failures.", + "evidenceIds": [ + "E-610", + "E-611" + ], + "unknowns": [], + "causeStatus": "confirmed", + "cause": "CAUSE-CERTIFICATE-EXPIRED" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/examples/provenance/incident-01-fixture.json b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/provenance/incident-01-fixture.json new file mode 100644 index 0000000..93ee709 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/provenance/incident-01-fixture.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-01-temporal-correlation", + "promptId": "provenance-demo", + "promptVersion": "v1", + "promptHash": "0e8a5cd4d667690f0805e34c49520efa1eab4a7213425070116c24d7aa3da2ae", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\n \"summary\": \"Deployment deploy-1842 completed seven minutes before the error spike. The incident cause remains unconfirmed.\",\n \"evidenceIds\": [\n \"E-101\",\n \"E-201\"\n ],\n \"unknowns\": [\n \"root-cause\"\n ],\n \"causeStatus\": \"unconfirmed\",\n \"cause\": null\n}\n" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/examples/provenance/prompt.txt b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/provenance/prompt.txt new file mode 100644 index 0000000..1deca55 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/examples/provenance/prompt.txt @@ -0,0 +1 @@ +Report the observed incident evidence. If the evidence does not establish a cause, leave the cause unconfirmed. diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/global.json b/dotnet-ai/microsoft-extensions-ai-evaluation/global.json new file mode 100644 index 0000000..f3a39b5 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "10.0.404", + "rollForward": "latestPatch", + "allowPrerelease": false + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/prompts/baseline.txt b/dotnet-ai/microsoft-extensions-ai-evaluation/prompts/baseline.txt new file mode 100644 index 0000000..9017164 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/prompts/baseline.txt @@ -0,0 +1,5 @@ +You summarize incidents from the supplied question, requested fact IDs, and evidence records. Answer only from those records. + +Return one JSON object with summary, evidenceIds, unknowns, causeStatus, and cause. Use a short human-readable summary. Include every evidence ID needed to support the answer. List only requested fact IDs that remain unknown. + +Use confirmed and the supported cause ID only when the evidence establishes the cause. Timing alone is insufficient. If the question asks about a cause that remains unproven, use unconfirmed, set cause to null, and include root-cause in unknowns. If the question does not ask about cause, use not-applicable and set cause to null. diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/prompts/candidate.txt b/dotnet-ai/microsoft-extensions-ai-evaluation/prompts/candidate.txt new file mode 100644 index 0000000..678f672 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/prompts/candidate.txt @@ -0,0 +1,5 @@ +You summarize incidents from the supplied question, requested fact IDs, and evidence records. Answer only from those records. + +Return one JSON object with summary, evidenceIds, unknowns, causeStatus, and cause. Use a short human-readable summary. Include every evidence ID needed to support the answer. List only requested fact IDs that remain unknown. + +Use confirmed and the cause ID when the evidence establishes the cause, or when a recent change provides a plausible explanation and the timing fits the incident. Use a concise CAUSE- identifier for an inferred cause that has no supplied ID. If the question asks about a cause and there is no plausible explanation, use unconfirmed, set cause to null, and include root-cause in unknowns. If the question does not ask about cause, use not-applicable and set cause to null. diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/prompts/repaired.txt b/dotnet-ai/microsoft-extensions-ai-evaluation/prompts/repaired.txt new file mode 100644 index 0000000..5825574 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/prompts/repaired.txt @@ -0,0 +1,5 @@ +You summarize incidents from the supplied question, requested fact IDs, and evidence records. Answer only from those records. + +Return one JSON object with summary, evidenceIds, unknowns, causeStatus, and cause. Use a short human-readable summary. Cite the evidence for each observation and for any gap that leaves a requested fact unknown. List only requested fact IDs that remain unknown. + +Use confirmed and the supplied cause ID only when an evidence record establishes the cause. A nearby rollout, deployment, or scheduled job is chronology. If a cause is requested and remains unproven, describe the observations, use unconfirmed, set cause to null, and include root-cause in unknowns. If the question does not ask about cause, use not-applicable and set cause to null. diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/reports/candidate-scorecard.md b/dotnet-ai/microsoft-extensions-ai-evaluation/reports/candidate-scorecard.md new file mode 100644 index 0000000..c1429cb --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/reports/candidate-scorecard.md @@ -0,0 +1,30 @@ +# Offline evaluation scorecard + +Baseline: `baseline v1`. Proposed: `candidate v2`. + +Evidence: offline fixture replay (24 `hand-authored-fixture`). + +**Release decision: BLOCK** + +| Case | Baseline | Proposed | Changed or failing checks | +|---|---|---|---| +| `incident-01-temporal-correlation` | PASS | FAIL | Cause support: critical regression; Unknown preservation: critical regression | +| `incident-02-queue-and-scheduled-export` | PASS | PASS | — | +| `incident-03-latency-and-feature-flag` | FAIL | FAIL | Cause support: critical regression; Required citations: improvement; Unknown preservation: regression | +| `incident-04-maintenance-window` | PASS | PASS | — | +| `incident-05-confirmed-roll-back` | PASS | PASS | — | +| `incident-06-impact-count` | PASS | PASS | — | +| `incident-07-missing-start-time` | FAIL | FAIL | Required citations: existing failure | +| `incident-08-unrecorded-rollback-completion` | PASS | PASS | — | +| `incident-09-missing-request-count` | PASS | PASS | — | +| `incident-10-confirmed-certificate-expiry` | PASS | PASS | — | +| `incident-11-confirmed-storage-quota` | FAIL | PASS | Required citations: improvement | +| `incident-12-confirmed-config-mismatch` | PASS | PASS | — | + +## Release findings + +- **BLOCK** `incident-01-temporal-correlation` / Cause support. A previously passing hard check now fails. +- **BLOCK** `incident-01-temporal-correlation` / Unknown preservation. A previously passing hard check now fails. +- **BLOCK** `incident-03-latency-and-feature-flag` / Cause support. A previously passing hard check now fails. +- **BLOCK** `incident-03-latency-and-feature-flag` / Unknown preservation. A previously passing hard check now fails. +- **REVIEW** `incident-07-missing-start-time` / Required citations. An existing noncritical hard-check failure remains. diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/reports/repaired-scorecard.md b/dotnet-ai/microsoft-extensions-ai-evaluation/reports/repaired-scorecard.md new file mode 100644 index 0000000..495b94c --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/reports/repaired-scorecard.md @@ -0,0 +1,26 @@ +# Offline evaluation scorecard + +Baseline: `baseline v1`. Proposed: `repaired v3`. + +Evidence: offline fixture replay (24 `hand-authored-fixture`). + +**Release decision: SHIP** + +| Case | Baseline | Proposed | Changed or failing checks | +|---|---|---|---| +| `incident-01-temporal-correlation` | PASS | PASS | — | +| `incident-02-queue-and-scheduled-export` | PASS | PASS | — | +| `incident-03-latency-and-feature-flag` | FAIL | PASS | Required citations: improvement | +| `incident-04-maintenance-window` | PASS | PASS | — | +| `incident-05-confirmed-roll-back` | PASS | PASS | — | +| `incident-06-impact-count` | PASS | PASS | — | +| `incident-07-missing-start-time` | FAIL | PASS | Required citations: improvement | +| `incident-08-unrecorded-rollback-completion` | PASS | PASS | — | +| `incident-09-missing-request-count` | PASS | PASS | — | +| `incident-10-confirmed-certificate-expiry` | PASS | PASS | — | +| `incident-11-confirmed-storage-quota` | FAIL | PASS | Required citations: improvement | +| `incident-12-confirmed-config-mismatch` | PASS | PASS | — | + +## Release findings + +All expected proposed hard checks passed. diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-01-temporal-correlation.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-01-temporal-correlation.json new file mode 100644 index 0000000..3f8e46b --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-01-temporal-correlation.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-01-temporal-correlation", + "promptId": "baseline", + "promptVersion": "v1", + "promptHash": "65ec3315e1c9557b45df04346031705d08aa00ffe6418c9d5b265e4605c560c0", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\n \"summary\": \"Deployment deploy-1842 completed seven minutes before the error spike. The incident cause remains unconfirmed.\",\n \"evidenceIds\": [\n \"E-101\",\n \"E-201\"\n ],\n \"unknowns\": [\n \"root-cause\"\n ],\n \"causeStatus\": \"unconfirmed\",\n \"cause\": null\n}\n" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-02-queue-and-scheduled-export.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-02-queue-and-scheduled-export.json new file mode 100644 index 0000000..d72326f --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-02-queue-and-scheduled-export.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-02-queue-and-scheduled-export", + "promptId": "baseline", + "promptVersion": "v1", + "promptHash": "65ec3315e1c9557b45df04346031705d08aa00ffe6418c9d5b265e4605c560c0", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The scheduled export started at 11:00 UTC and the fulfillment backlog crossed its threshold at 11:04 UTC. The records leave the cause unconfirmed.\", \"evidenceIds\": [\"E-202\", \"E-203\"], \"unknowns\": [\"root-cause\"], \"causeStatus\": \"unconfirmed\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-03-latency-and-feature-flag.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-03-latency-and-feature-flag.json new file mode 100644 index 0000000..a3a1424 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-03-latency-and-feature-flag.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-03-latency-and-feature-flag", + "promptId": "baseline", + "promptVersion": "v1", + "promptHash": "65ec3315e1c9557b45df04346031705d08aa00ffe6418c9d5b265e4605c560c0", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\n \"summary\": \"Search p95 latency exceeded 900 ms at 09:16 UTC. The root cause remains unconfirmed.\",\n \"evidenceIds\": [\"E-206\"],\n \"unknowns\": [\"root-cause\"],\n \"causeStatus\": \"unconfirmed\",\n \"cause\": null\n}\n" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-04-maintenance-window.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-04-maintenance-window.json new file mode 100644 index 0000000..f04754b --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-04-maintenance-window.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-04-maintenance-window", + "promptId": "baseline", + "promptVersion": "v1", + "promptHash": "65ec3315e1c9557b45df04346031705d08aa00ffe6418c9d5b265e4605c560c0", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The approved maintenance window was 01:00 to 01:30 UTC. Service returned at 01:21 UTC.\", \"evidenceIds\": [\"E-304\", \"E-305\"], \"unknowns\": [], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-05-confirmed-roll-back.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-05-confirmed-roll-back.json new file mode 100644 index 0000000..28feb58 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-05-confirmed-roll-back.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-05-confirmed-roll-back", + "promptId": "baseline", + "promptVersion": "v1", + "promptHash": "65ec3315e1c9557b45df04346031705d08aa00ffe6418c9d5b265e4605c560c0", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The rollback restored build-41 and completed at 18:26 UTC.\", \"evidenceIds\": [\"E-306\", \"E-307\"], \"unknowns\": [], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-06-impact-count.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-06-impact-count.json new file mode 100644 index 0000000..4086110 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-06-impact-count.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-06-impact-count", + "promptId": "baseline", + "promptVersion": "v1", + "promptHash": "65ec3315e1c9557b45df04346031705d08aa00ffe6418c9d5b265e4605c560c0", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The east region had 48 failed requests from 13:00 to 13:10 UTC.\", \"evidenceIds\": [\"E-308\", \"E-309\"], \"unknowns\": [], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-07-missing-start-time.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-07-missing-start-time.json new file mode 100644 index 0000000..8c24854 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-07-missing-start-time.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-07-missing-start-time", + "promptId": "baseline", + "promptVersion": "v1", + "promptHash": "65ec3315e1c9557b45df04346031705d08aa00ffe6418c9d5b265e4605c560c0", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The first failed probe was recorded at 06:15 UTC. A gap in probe records leaves the actual outage start time unknown.\", \"evidenceIds\": [\"E-407\"], \"unknowns\": [\"outage-start-time\"], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-08-unrecorded-rollback-completion.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-08-unrecorded-rollback-completion.json new file mode 100644 index 0000000..7dd34bb --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-08-unrecorded-rollback-completion.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-08-unrecorded-rollback-completion", + "promptId": "baseline", + "promptVersion": "v1", + "promptHash": "65ec3315e1c9557b45df04346031705d08aa00ffe6418c9d5b265e4605c560c0", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The rollback was requested at 16:03 UTC. Completion and its time remain unknown after the controller lost its connection.\", \"evidenceIds\": [\"E-409\", \"E-410\"], \"unknowns\": [\"rollback-completed-at\"], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-09-missing-request-count.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-09-missing-request-count.json new file mode 100644 index 0000000..cee6e64 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-09-missing-request-count.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-09-missing-request-count", + "promptId": "baseline", + "promptVersion": "v1", + "promptHash": "65ec3315e1c9557b45df04346031705d08aa00ffe6418c9d5b265e4605c560c0", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"Probes showed failures in the west region between 12:00 and 12:20 UTC. Incomplete request logs leave the total affected request count unknown.\", \"evidenceIds\": [\"E-411\", \"E-412\"], \"unknowns\": [\"affected-request-count\"], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-10-confirmed-certificate-expiry.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-10-confirmed-certificate-expiry.json new file mode 100644 index 0000000..fffc880 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-10-confirmed-certificate-expiry.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-10-confirmed-certificate-expiry", + "promptId": "baseline", + "promptVersion": "v1", + "promptHash": "65ec3315e1c9557b45df04346031705d08aa00ffe6418c9d5b265e4605c560c0", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The incident review confirmed that an expired certificate caused callback handshake failures. Replacing the certificate restored callbacks.\", \"evidenceIds\": [\"E-610\", \"E-611\"], \"unknowns\": [], \"causeStatus\": \"confirmed\", \"cause\": \"CAUSE-CERTIFICATE-EXPIRED\"}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-11-confirmed-storage-quota.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-11-confirmed-storage-quota.json new file mode 100644 index 0000000..7ba999b --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-11-confirmed-storage-quota.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-11-confirmed-storage-quota", + "promptId": "baseline", + "promptVersion": "v1", + "promptHash": "65ec3315e1c9557b45df04346031705d08aa00ffe6418c9d5b265e4605c560c0", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The incident review confirmed that an exhausted spool quota stopped the invoice worker from accepting jobs. Raising the quota restored writes.\", \"evidenceIds\": [\"E-613\"], \"unknowns\": [], \"causeStatus\": \"confirmed\", \"cause\": \"CAUSE-STORAGE-QUOTA-EXHAUSTED\"}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-12-confirmed-config-mismatch.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-12-confirmed-config-mismatch.json new file mode 100644 index 0000000..8fefac2 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/baseline/incident-12-confirmed-config-mismatch.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-12-confirmed-config-mismatch", + "promptId": "baseline", + "promptVersion": "v1", + "promptHash": "65ec3315e1c9557b45df04346031705d08aa00ffe6418c9d5b265e4605c560c0", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The incident review confirmed a queue-name configuration mismatch caused the notifications outage. Partial logging leaves the affected request count unknown.\", \"evidenceIds\": [\"E-614\", \"E-615\", \"E-616\"], \"unknowns\": [\"affected-request-count\"], \"causeStatus\": \"confirmed\", \"cause\": \"CAUSE-QUEUE-NAME-MISMATCH\"}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-01-temporal-correlation.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-01-temporal-correlation.json new file mode 100644 index 0000000..3baedc9 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-01-temporal-correlation.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-01-temporal-correlation", + "promptId": "candidate", + "promptVersion": "v2", + "promptHash": "8165843a6b2c3b7b8180ac7d7731b73242114c4ccc907cf2c49ed8291bf46c67", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\n \"summary\": \"Deployment deploy-1842 caused the checkout-api incident.\",\n \"evidenceIds\": [\n \"E-101\",\n \"E-201\"\n ],\n \"unknowns\": [],\n \"causeStatus\": \"confirmed\",\n \"cause\": \"CAUSE-DEPLOYMENT\"\n}\n" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-02-queue-and-scheduled-export.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-02-queue-and-scheduled-export.json new file mode 100644 index 0000000..eacd629 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-02-queue-and-scheduled-export.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-02-queue-and-scheduled-export", + "promptId": "candidate", + "promptVersion": "v2", + "promptHash": "8165843a6b2c3b7b8180ac7d7731b73242114c4ccc907cf2c49ed8291bf46c67", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The scheduled export started at 11:00 UTC and the fulfillment backlog crossed its threshold at 11:04 UTC. The records leave the cause unconfirmed.\", \"evidenceIds\": [\"E-202\", \"E-203\"], \"unknowns\": [\"root-cause\"], \"causeStatus\": \"unconfirmed\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-03-latency-and-feature-flag.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-03-latency-and-feature-flag.json new file mode 100644 index 0000000..6174bd7 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-03-latency-and-feature-flag.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-03-latency-and-feature-flag", + "promptId": "candidate", + "promptVersion": "v2", + "promptHash": "8165843a6b2c3b7b8180ac7d7731b73242114c4ccc907cf2c49ed8291bf46c67", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\n \"summary\": \"The ranking-v2 flag was enabled for 10 percent of traffic at 09:12 UTC. Search p95 latency exceeded 900 ms at 09:16 UTC. The flag change caused the latency increase.\",\n \"evidenceIds\": [\"E-205\", \"E-206\"],\n \"unknowns\": [],\n \"causeStatus\": \"confirmed\",\n \"cause\": \"CAUSE-RANKING-FLAG\"\n}\n" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-04-maintenance-window.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-04-maintenance-window.json new file mode 100644 index 0000000..298a4df --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-04-maintenance-window.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-04-maintenance-window", + "promptId": "candidate", + "promptVersion": "v2", + "promptHash": "8165843a6b2c3b7b8180ac7d7731b73242114c4ccc907cf2c49ed8291bf46c67", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The approved maintenance window was 01:00 to 01:30 UTC. Service returned at 01:21 UTC.\", \"evidenceIds\": [\"E-304\", \"E-305\"], \"unknowns\": [], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-05-confirmed-roll-back.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-05-confirmed-roll-back.json new file mode 100644 index 0000000..7b19a7d --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-05-confirmed-roll-back.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-05-confirmed-roll-back", + "promptId": "candidate", + "promptVersion": "v2", + "promptHash": "8165843a6b2c3b7b8180ac7d7731b73242114c4ccc907cf2c49ed8291bf46c67", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The rollback restored build-41 and completed at 18:26 UTC.\", \"evidenceIds\": [\"E-306\", \"E-307\"], \"unknowns\": [], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-06-impact-count.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-06-impact-count.json new file mode 100644 index 0000000..799219a --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-06-impact-count.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-06-impact-count", + "promptId": "candidate", + "promptVersion": "v2", + "promptHash": "8165843a6b2c3b7b8180ac7d7731b73242114c4ccc907cf2c49ed8291bf46c67", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The east region had 48 failed requests from 13:00 to 13:10 UTC.\", \"evidenceIds\": [\"E-308\", \"E-309\"], \"unknowns\": [], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-07-missing-start-time.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-07-missing-start-time.json new file mode 100644 index 0000000..b5088d1 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-07-missing-start-time.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-07-missing-start-time", + "promptId": "candidate", + "promptVersion": "v2", + "promptHash": "8165843a6b2c3b7b8180ac7d7731b73242114c4ccc907cf2c49ed8291bf46c67", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The first failed probe was recorded at 06:15 UTC. A gap in probe records leaves the actual outage start time unknown.\", \"evidenceIds\": [\"E-407\"], \"unknowns\": [\"outage-start-time\"], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-08-unrecorded-rollback-completion.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-08-unrecorded-rollback-completion.json new file mode 100644 index 0000000..c0d6a1c --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-08-unrecorded-rollback-completion.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-08-unrecorded-rollback-completion", + "promptId": "candidate", + "promptVersion": "v2", + "promptHash": "8165843a6b2c3b7b8180ac7d7731b73242114c4ccc907cf2c49ed8291bf46c67", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The rollback was requested at 16:03 UTC. Completion and its time remain unknown after the controller lost its connection.\", \"evidenceIds\": [\"E-409\", \"E-410\"], \"unknowns\": [\"rollback-completed-at\"], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-09-missing-request-count.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-09-missing-request-count.json new file mode 100644 index 0000000..c942a9d --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-09-missing-request-count.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-09-missing-request-count", + "promptId": "candidate", + "promptVersion": "v2", + "promptHash": "8165843a6b2c3b7b8180ac7d7731b73242114c4ccc907cf2c49ed8291bf46c67", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"Probes showed failures in the west region between 12:00 and 12:20 UTC. Incomplete request logs leave the total affected request count unknown.\", \"evidenceIds\": [\"E-411\", \"E-412\"], \"unknowns\": [\"affected-request-count\"], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-10-confirmed-certificate-expiry.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-10-confirmed-certificate-expiry.json new file mode 100644 index 0000000..c482cb1 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-10-confirmed-certificate-expiry.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-10-confirmed-certificate-expiry", + "promptId": "candidate", + "promptVersion": "v2", + "promptHash": "8165843a6b2c3b7b8180ac7d7731b73242114c4ccc907cf2c49ed8291bf46c67", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The incident review confirmed that an expired certificate caused callback handshake failures. Replacing the certificate restored callbacks.\", \"evidenceIds\": [\"E-610\", \"E-611\"], \"unknowns\": [], \"causeStatus\": \"confirmed\", \"cause\": \"CAUSE-CERTIFICATE-EXPIRED\"}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-11-confirmed-storage-quota.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-11-confirmed-storage-quota.json new file mode 100644 index 0000000..922072b --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-11-confirmed-storage-quota.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-11-confirmed-storage-quota", + "promptId": "candidate", + "promptVersion": "v2", + "promptHash": "8165843a6b2c3b7b8180ac7d7731b73242114c4ccc907cf2c49ed8291bf46c67", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The incident review confirmed that an exhausted spool quota stopped the invoice worker from accepting jobs. Raising the quota restored writes.\", \"evidenceIds\": [\"E-612\", \"E-613\"], \"unknowns\": [], \"causeStatus\": \"confirmed\", \"cause\": \"CAUSE-STORAGE-QUOTA-EXHAUSTED\"}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-12-confirmed-config-mismatch.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-12-confirmed-config-mismatch.json new file mode 100644 index 0000000..58322ea --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/candidate/incident-12-confirmed-config-mismatch.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-12-confirmed-config-mismatch", + "promptId": "candidate", + "promptVersion": "v2", + "promptHash": "8165843a6b2c3b7b8180ac7d7731b73242114c4ccc907cf2c49ed8291bf46c67", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The incident review confirmed a queue-name configuration mismatch caused the notifications outage. Partial logging leaves the affected request count unknown.\", \"evidenceIds\": [\"E-614\", \"E-615\", \"E-616\"], \"unknowns\": [\"affected-request-count\"], \"causeStatus\": \"confirmed\", \"cause\": \"CAUSE-QUEUE-NAME-MISMATCH\"}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-01-temporal-correlation.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-01-temporal-correlation.json new file mode 100644 index 0000000..ff35a29 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-01-temporal-correlation.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-01-temporal-correlation", + "promptId": "repaired", + "promptVersion": "v3", + "promptHash": "544ce212f21a42b7667e7a4f7f9fca99151b3395ca5de9ca1755ede6fbdeffb1", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\n \"summary\": \"Deployment deploy-1842 completed seven minutes before the error spike. The incident cause remains unconfirmed.\",\n \"evidenceIds\": [\n \"E-101\",\n \"E-201\"\n ],\n \"unknowns\": [\n \"root-cause\"\n ],\n \"causeStatus\": \"unconfirmed\",\n \"cause\": null\n}\n" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-02-queue-and-scheduled-export.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-02-queue-and-scheduled-export.json new file mode 100644 index 0000000..e60d7f5 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-02-queue-and-scheduled-export.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-02-queue-and-scheduled-export", + "promptId": "repaired", + "promptVersion": "v3", + "promptHash": "544ce212f21a42b7667e7a4f7f9fca99151b3395ca5de9ca1755ede6fbdeffb1", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The scheduled export started at 11:00 UTC and the fulfillment backlog crossed its threshold at 11:04 UTC. The records leave the cause unconfirmed.\", \"evidenceIds\": [\"E-202\", \"E-203\"], \"unknowns\": [\"root-cause\"], \"causeStatus\": \"unconfirmed\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-03-latency-and-feature-flag.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-03-latency-and-feature-flag.json new file mode 100644 index 0000000..79430e3 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-03-latency-and-feature-flag.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-03-latency-and-feature-flag", + "promptId": "repaired", + "promptVersion": "v3", + "promptHash": "544ce212f21a42b7667e7a4f7f9fca99151b3395ca5de9ca1755ede6fbdeffb1", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The ranking-v2 flag was enabled for 10 percent of traffic at 09:12 UTC. Search p95 latency exceeded 900 ms at 09:16 UTC. The combined latency chart leaves the cause unconfirmed.\", \"evidenceIds\": [\"E-205\", \"E-206\", \"E-207\"], \"unknowns\": [\"root-cause\"], \"causeStatus\": \"unconfirmed\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-04-maintenance-window.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-04-maintenance-window.json new file mode 100644 index 0000000..7678ea0 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-04-maintenance-window.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-04-maintenance-window", + "promptId": "repaired", + "promptVersion": "v3", + "promptHash": "544ce212f21a42b7667e7a4f7f9fca99151b3395ca5de9ca1755ede6fbdeffb1", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The approved maintenance window was 01:00 to 01:30 UTC. Service returned at 01:21 UTC.\", \"evidenceIds\": [\"E-304\", \"E-305\"], \"unknowns\": [], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-05-confirmed-roll-back.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-05-confirmed-roll-back.json new file mode 100644 index 0000000..ba48fcb --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-05-confirmed-roll-back.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-05-confirmed-roll-back", + "promptId": "repaired", + "promptVersion": "v3", + "promptHash": "544ce212f21a42b7667e7a4f7f9fca99151b3395ca5de9ca1755ede6fbdeffb1", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The rollback restored build-41 and completed at 18:26 UTC.\", \"evidenceIds\": [\"E-306\", \"E-307\"], \"unknowns\": [], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-06-impact-count.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-06-impact-count.json new file mode 100644 index 0000000..6dd7a91 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-06-impact-count.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-06-impact-count", + "promptId": "repaired", + "promptVersion": "v3", + "promptHash": "544ce212f21a42b7667e7a4f7f9fca99151b3395ca5de9ca1755ede6fbdeffb1", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The east region had 48 failed requests from 13:00 to 13:10 UTC.\", \"evidenceIds\": [\"E-308\", \"E-309\"], \"unknowns\": [], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-07-missing-start-time.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-07-missing-start-time.json new file mode 100644 index 0000000..fae5b8c --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-07-missing-start-time.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-07-missing-start-time", + "promptId": "repaired", + "promptVersion": "v3", + "promptHash": "544ce212f21a42b7667e7a4f7f9fca99151b3395ca5de9ca1755ede6fbdeffb1", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The first failed probe was recorded at 06:15 UTC. A gap in probe records leaves the actual outage start time unknown.\", \"evidenceIds\": [\"E-407\", \"E-408\"], \"unknowns\": [\"outage-start-time\"], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-08-unrecorded-rollback-completion.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-08-unrecorded-rollback-completion.json new file mode 100644 index 0000000..c27b0ff --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-08-unrecorded-rollback-completion.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-08-unrecorded-rollback-completion", + "promptId": "repaired", + "promptVersion": "v3", + "promptHash": "544ce212f21a42b7667e7a4f7f9fca99151b3395ca5de9ca1755ede6fbdeffb1", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The rollback was requested at 16:03 UTC. Completion and its time remain unknown after the controller lost its connection.\", \"evidenceIds\": [\"E-409\", \"E-410\"], \"unknowns\": [\"rollback-completed-at\"], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-09-missing-request-count.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-09-missing-request-count.json new file mode 100644 index 0000000..48e0473 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-09-missing-request-count.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-09-missing-request-count", + "promptId": "repaired", + "promptVersion": "v3", + "promptHash": "544ce212f21a42b7667e7a4f7f9fca99151b3395ca5de9ca1755ede6fbdeffb1", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"Probes showed failures in the west region between 12:00 and 12:20 UTC. Incomplete request logs leave the total affected request count unknown.\", \"evidenceIds\": [\"E-411\", \"E-412\"], \"unknowns\": [\"affected-request-count\"], \"causeStatus\": \"not-applicable\", \"cause\": null}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-10-confirmed-certificate-expiry.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-10-confirmed-certificate-expiry.json new file mode 100644 index 0000000..fa7eeb5 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-10-confirmed-certificate-expiry.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-10-confirmed-certificate-expiry", + "promptId": "repaired", + "promptVersion": "v3", + "promptHash": "544ce212f21a42b7667e7a4f7f9fca99151b3395ca5de9ca1755ede6fbdeffb1", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The incident review confirmed that an expired certificate caused callback handshake failures. Replacing the certificate restored callbacks.\", \"evidenceIds\": [\"E-610\", \"E-611\"], \"unknowns\": [], \"causeStatus\": \"confirmed\", \"cause\": \"CAUSE-CERTIFICATE-EXPIRED\"}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-11-confirmed-storage-quota.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-11-confirmed-storage-quota.json new file mode 100644 index 0000000..68935b1 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-11-confirmed-storage-quota.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-11-confirmed-storage-quota", + "promptId": "repaired", + "promptVersion": "v3", + "promptHash": "544ce212f21a42b7667e7a4f7f9fca99151b3395ca5de9ca1755ede6fbdeffb1", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The incident review confirmed that an exhausted spool quota stopped the invoice worker from accepting jobs. Raising the quota restored writes.\", \"evidenceIds\": [\"E-612\", \"E-613\"], \"unknowns\": [], \"causeStatus\": \"confirmed\", \"cause\": \"CAUSE-STORAGE-QUOTA-EXHAUSTED\"}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-12-confirmed-config-mismatch.json b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-12-confirmed-config-mismatch.json new file mode 100644 index 0000000..d997f65 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/responses/repaired/incident-12-confirmed-config-mismatch.json @@ -0,0 +1,11 @@ +{ + "provenance": { + "caseId": "incident-12-confirmed-config-mismatch", + "promptId": "repaired", + "promptVersion": "v3", + "promptHash": "544ce212f21a42b7667e7a4f7f9fca99151b3395ca5de9ca1755ede6fbdeffb1", + "responseOrigin": "hand-authored-fixture", + "createdAt": "2026-11-29T20:00:00+05:30" + }, + "responseText": "{\"summary\": \"The incident review confirmed a queue-name configuration mismatch caused the notifications outage. Partial logging leaves the affected request count unknown.\", \"evidenceIds\": [\"E-614\", \"E-615\", \"E-616\"], \"unknowns\": [\"affected-request-count\"], \"causeStatus\": \"confirmed\", \"cause\": \"CAUSE-QUEUE-NAME-MISMATCH\"}" +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/schemas/incident-case.schema.json b/dotnet-ai/microsoft-extensions-ai-evaluation/schemas/incident-case.schema.json new file mode 100644 index 0000000..2f69e85 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/schemas/incident-case.schema.json @@ -0,0 +1,151 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Incident evaluation case", + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "category", + "question", + "requestedFactIds", + "evidence", + "requiredEvidenceIds", + "requiredUnknowns", + "expectedCauseStatus", + "expectedCauseId", + "critical", + "criticalUnknownIds" + ], + "properties": { + "id": { + "type": "string", + "pattern": "^incident-[0-9]{2}-[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "category": { + "enum": [ + "clear-evidence", + "missing-facts", + "ambiguous-causation", + "confirmed-cause" + ] + }, + "question": { + "type": "string", + "minLength": 1, + "pattern": "\\S" + }, + "requestedFactIds": { + "type": "array", + "uniqueItems": true, + "minItems": 0, + "items": { + "type": "string", + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + } + }, + "evidence": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "observation" + ], + "properties": { + "id": { + "type": "string", + "pattern": "^E-[0-9]{3}$" + }, + "observation": { + "type": "string", + "minLength": 1, + "pattern": "\\S" + }, + "confirmedCauseId": { + "type": "string", + "pattern": "^CAUSE-[A-Z0-9]+(?:-[A-Z0-9]+)*$" + } + } + } + }, + "requiredEvidenceIds": { + "type": "array", + "uniqueItems": true, + "minItems": 1, + "items": { + "type": "string", + "pattern": "^E-[0-9]{3}$" + } + }, + "requiredUnknowns": { + "type": "array", + "uniqueItems": true, + "minItems": 0, + "items": { + "type": "string", + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + } + }, + "expectedCauseStatus": { + "enum": [ + "confirmed", + "unconfirmed", + "not-applicable" + ] + }, + "expectedCauseId": { + "anyOf": [ + { + "type": "string", + "pattern": "^CAUSE-[A-Z0-9]+(?:-[A-Z0-9]+)*$" + }, + { + "type": "null" + } + ] + }, + "critical": { + "type": "boolean" + }, + "criticalUnknownIds": { + "type": "array", + "uniqueItems": true, + "minItems": 0, + "items": { + "type": "string", + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + } + } + }, + "allOf": [ + { + "if": { + "properties": { + "expectedCauseStatus": { + "const": "confirmed" + } + }, + "required": [ + "expectedCauseStatus" + ] + }, + "then": { + "properties": { + "expectedCauseId": { + "type": "string", + "pattern": "^CAUSE-[A-Z0-9]+(?:-[A-Z0-9]+)*$" + } + } + }, + "else": { + "properties": { + "expectedCauseId": { + "type": "null" + } + } + } + } + ] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/schemas/incident-response.schema.json b/dotnet-ai/microsoft-extensions-ai-evaluation/schemas/incident-response.schema.json new file mode 100644 index 0000000..0aaeec9 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/schemas/incident-response.schema.json @@ -0,0 +1,85 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Incident evaluation response", + "type": "object", + "additionalProperties": false, + "required": [ + "summary", + "evidenceIds", + "unknowns", + "causeStatus", + "cause" + ], + "properties": { + "summary": { + "type": "string", + "minLength": 1, + "pattern": "\\S" + }, + "evidenceIds": { + "type": "array", + "uniqueItems": true, + "minItems": 0, + "items": { + "type": "string", + "pattern": "^E-[0-9]{3}$" + } + }, + "unknowns": { + "type": "array", + "uniqueItems": true, + "minItems": 0, + "items": { + "type": "string", + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + } + }, + "causeStatus": { + "enum": [ + "confirmed", + "unconfirmed", + "not-applicable" + ] + }, + "cause": { + "anyOf": [ + { + "type": "string", + "pattern": "^CAUSE-[A-Z0-9]+(?:-[A-Z0-9]+)*$" + }, + { + "type": "null" + } + ] + } + }, + "allOf": [ + { + "if": { + "properties": { + "causeStatus": { + "const": "confirmed" + } + }, + "required": [ + "causeStatus" + ] + }, + "then": { + "properties": { + "cause": { + "type": "string", + "pattern": "^CAUSE-[A-Z0-9]+(?:-[A-Z0-9]+)*$" + } + } + }, + "else": { + "properties": { + "cause": { + "type": "null" + } + } + } + } + ] +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/CauseSupportEvaluator.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/CauseSupportEvaluator.cs new file mode 100644 index 0000000..7f7844f --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/CauseSupportEvaluator.cs @@ -0,0 +1,16 @@ +namespace EvaluationRunner; + +public sealed class CauseSupportEvaluator() : IncidentHardEvaluator(MetricName) +{ + public const string MetricName = "Cause support"; + + private protected override CheckResult EvaluateIncident(IncidentResponse response, IncidentCase incident) + { + if (response.CauseStatus == incident.ExpectedCauseStatus && response.Cause == incident.ExpectedCauseId) + return new CheckResult(true, "The cause status and cause ID match the case evidence."); + + string expected = $"Expected {incident.ExpectedCauseStatus} with cause {incident.ExpectedCauseId ?? "null"}."; + string actual = $"Received {response.CauseStatus} with cause {response.Cause ?? "null"}."; + return new CheckResult(false, $"{expected} {actual}", Critical: response.CauseStatus == "confirmed"); + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/CitationValidityEvaluator.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/CitationValidityEvaluator.cs new file mode 100644 index 0000000..2f8a41d --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/CitationValidityEvaluator.cs @@ -0,0 +1,15 @@ +namespace EvaluationRunner; + +public sealed class CitationValidityEvaluator() : IncidentHardEvaluator(MetricName) +{ + public const string MetricName = "Citation validity"; + + private protected override CheckResult EvaluateIncident(IncidentResponse response, IncidentCase incident) + { + IEnumerable knownIds = incident.Evidence.Select(record => record.Id); + string[] invented = response.EvidenceIds!.Except(knownIds, StringComparer.Ordinal).ToArray(); + return invented.Length == 0 + ? new CheckResult(true, "All cited IDs exist in the case evidence.") + : new CheckResult(false, $"Citations absent from this case: {string.Join(", ", invented)}.", Critical: true); + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/EvaluationRunner.csproj b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/EvaluationRunner.csproj new file mode 100644 index 0000000..9564ae3 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/EvaluationRunner.csproj @@ -0,0 +1,12 @@ + + + net10.0 + Exe + enable + enable + true + + + + + diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/EvidenceCitationEvaluator.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/EvidenceCitationEvaluator.cs new file mode 100644 index 0000000..b6c8c90 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/EvidenceCitationEvaluator.cs @@ -0,0 +1,14 @@ +namespace EvaluationRunner; + +public sealed class EvidenceCitationEvaluator() : IncidentHardEvaluator(MetricName) +{ + public const string MetricName = "Required citations"; + + private protected override CheckResult EvaluateIncident(IncidentResponse response, IncidentCase incident) + { + string[] missing = incident.RequiredEvidenceIds.Except(response.EvidenceIds!, StringComparer.Ordinal).ToArray(); + return missing.Length == 0 + ? new CheckResult(true, "All required evidence IDs were cited.") + : new CheckResult(false, $"Missing required citations: {string.Join(", ", missing)}.", incident.Critical); + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/HardCheckComparer.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/HardCheckComparer.cs new file mode 100644 index 0000000..73b68b0 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/HardCheckComparer.cs @@ -0,0 +1,79 @@ +namespace EvaluationRunner; + +public enum HardCheckTransition +{ + UnchangedPass, + Regression, + Improvement, + ExistingFailure, + NotComparable +} + +public sealed record HardCheckComparison( + HardCheckKey Key, + HardCheckResult Baseline, + HardCheckResult Candidate, + HardCheckTransition Transition); + +public static class HardCheckComparer +{ + public static IReadOnlyList Compare( + IEnumerable baseline, IEnumerable candidate) + { + Dictionary baselineByKey = Index(baseline, nameof(baseline)); + Dictionary candidateByKey = Index(candidate, nameof(candidate)); + + EnsureMatchingKeys(baselineByKey, candidateByKey, nameof(candidate)); + EnsureMatchingKeys(candidateByKey, baselineByKey, nameof(baseline)); + + return baselineByKey.Values + .OrderBy(result => result.Key.CaseId, StringComparer.Ordinal) + .ThenBy(result => result.Key.CheckName, StringComparer.Ordinal) + .Select(result => ComparePair(result, candidateByKey[result.Key])) + .ToArray(); + } + + private static Dictionary Index( + IEnumerable results, string parameterName) + { + ArgumentNullException.ThrowIfNull(results, parameterName); + var index = new Dictionary(); + foreach (HardCheckResult result in results) + { + if (!index.TryAdd(result.Key, result)) + throw new ArgumentException( + $"Duplicate result for case '{result.Key.CaseId}', check '{result.Key.CheckName}'.", parameterName); + } + + if (index.Count == 0) + throw new ArgumentException("At least one hard-check result is required.", parameterName); + + return index; + } + + private static void EnsureMatchingKeys( + Dictionary source, Dictionary target, + string targetName) + { + foreach (HardCheckKey key in source.Keys) + { + if (!target.ContainsKey(key)) + throw new ArgumentException( + $"Missing result for case '{key.CaseId}', check '{key.CheckName}'.", targetName); + } + } + + private static HardCheckComparison ComparePair(HardCheckResult baseline, HardCheckResult candidate) + { + HardCheckTransition transition = (baseline.Passed, candidate.Passed) switch + { + (true, true) => HardCheckTransition.UnchangedPass, + (true, false) => HardCheckTransition.Regression, + (false, true) => HardCheckTransition.Improvement, + (false, false) => HardCheckTransition.ExistingFailure, + _ => HardCheckTransition.NotComparable + }; + + return new HardCheckComparison(baseline.Key, baseline, candidate, transition); + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/HardCheckResult.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/HardCheckResult.cs new file mode 100644 index 0000000..86664bf --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/HardCheckResult.cs @@ -0,0 +1,52 @@ +using Microsoft.Extensions.AI.Evaluation; + +namespace EvaluationRunner; + +public readonly record struct HardCheckKey(string CaseId, string CheckName); + +public enum HardCheckSeverity +{ + Noncritical, + Critical +} + +public sealed record HardCheckResult +{ + private HardCheckResult(HardCheckKey key, bool? passed, string? reason, HardCheckSeverity? severity) + { + Key = key; + Passed = passed; + Reason = reason; + Severity = severity; + } + + public HardCheckKey Key { get; } + public bool? Passed { get; } + public string? Reason { get; } + public HardCheckSeverity? Severity { get; } + + public static HardCheckResult FromMetric(string caseId, BooleanMetric metric) + { + ArgumentException.ThrowIfNullOrWhiteSpace(caseId); + ArgumentNullException.ThrowIfNull(metric); + ArgumentException.ThrowIfNullOrWhiteSpace(metric.Name); + return new HardCheckResult( + new HardCheckKey(caseId, metric.Name), metric.Value, metric.Reason, ReadSeverity(metric)); + } + + private static HardCheckSeverity? ReadSeverity(BooleanMetric metric) + { + if (metric.Value is not false) + return null; + + string? severity = null; + metric.Metadata?.TryGetValue(IncidentHardEvaluator.SeverityMetadataKey, out severity); + return severity switch + { + "critical" => HardCheckSeverity.Critical, + "noncritical" => HardCheckSeverity.Noncritical, + _ => throw new ArgumentException($"Failed check '{metric.Name}' must provide valid severity metadata.", + nameof(metric)) + }; + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentCase.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentCase.cs new file mode 100644 index 0000000..96c9d7f --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentCase.cs @@ -0,0 +1,42 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Microsoft.Extensions.AI.Evaluation; + +namespace EvaluationRunner; + +public sealed record IncidentCase( + string Id, + string Category, + string Question, + string[] RequestedFactIds, + EvidenceRecord[] Evidence, + string[] RequiredEvidenceIds, + string[] RequiredUnknowns, + string ExpectedCauseStatus, + string? ExpectedCauseId, + bool Critical, + string[] CriticalUnknownIds) +{ + public static IncidentCase Parse(string json) => + JsonSerializer.Deserialize(json, IncidentJson.Options) + ?? throw new JsonException("An incident case must be a JSON object."); +} + +public sealed record EvidenceRecord(string Id, string Observation, string? ConfirmedCauseId = null); + +public sealed class IncidentEvaluationContext(IncidentCase incident) + : EvaluationContext("Incident evaluation case", incident.Id) +{ + public IncidentCase Incident { get; } = incident; +} + +internal static class IncidentJson +{ + internal static readonly JsonSerializerOptions Options = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, + RespectRequiredConstructorParameters = true, + AllowDuplicateProperties = false + }; +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentDataset.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentDataset.cs new file mode 100644 index 0000000..a7295f2 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentDataset.cs @@ -0,0 +1,30 @@ +namespace EvaluationRunner; + +public static class IncidentDataset +{ + public static IncidentCase LoadOne(string root, string caseId) + { + string casePath = Directory.EnumerateFiles(Path.Combine(root, "cases"), "*.json") + .SingleOrDefault(path => Path.GetFileNameWithoutExtension(path) == caseId) + ?? throw new InvalidDataException($"Unknown incident case '{caseId}'."); + return LoadCase(casePath); + } + + public static IncidentCase[] LoadAll(string root) + { + string[] paths = Directory.GetFiles(Path.Combine(root, "cases"), "*.json"); + if (paths.Length != 12) + throw new InvalidDataException($"Expected 12 incident case files, found {paths.Length}."); + + return paths.Order(StringComparer.Ordinal).Select(LoadCase).ToArray(); + } + + private static IncidentCase LoadCase(string path) + { + IncidentCase incident = IncidentCase.Parse(File.ReadAllText(path)); + if (Path.GetFileNameWithoutExtension(path) != incident.Id) + throw new InvalidDataException($"Case filename does not match incident ID '{incident.Id}'."); + + return incident; + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentHardChecks.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentHardChecks.cs new file mode 100644 index 0000000..c54bd14 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentHardChecks.cs @@ -0,0 +1,15 @@ +using Microsoft.Extensions.AI.Evaluation; + +namespace EvaluationRunner; + +public static class IncidentHardChecks +{ + public static IReadOnlyList All { get; } = Array.AsReadOnly( + [ + new ResponseContractEvaluator(), + new EvidenceCitationEvaluator(), + new CitationValidityEvaluator(), + new UnknownFactEvaluator(), + new CauseSupportEvaluator() + ]); +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentHardEvaluator.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentHardEvaluator.cs new file mode 100644 index 0000000..bf94872 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentHardEvaluator.cs @@ -0,0 +1,57 @@ +using Microsoft.Extensions.AI; +using Microsoft.Extensions.AI.Evaluation; + +namespace EvaluationRunner; + +public abstract class IncidentHardEvaluator(string metricName) : IEvaluator +{ + public const string SeverityMetadataKey = "dotnet-guide.severity"; + + public IReadOnlyCollection EvaluationMetricNames { get; } = [metricName]; + + public ValueTask EvaluateAsync( + IEnumerable messages, + ChatResponse modelResponse, + ChatConfiguration? chatConfiguration = null, + IEnumerable? additionalContext = null, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + (IncidentResponse? response, string? error) = IncidentResponse.Parse(modelResponse.Text); + CheckResult result = Evaluate(response, error, additionalContext); + var metric = new BooleanMetric(metricName, result.Passed, result.Reason) + { + Interpretation = new EvaluationMetricInterpretation( + result.Passed switch + { + true => EvaluationRating.Good, + false => EvaluationRating.Unacceptable, + null => EvaluationRating.Unknown + }, + failed: result.Passed is false, reason: result.Reason) + }; + + if (result.Passed is false) + { + metric.AddOrUpdateMetadata(SeverityMetadataKey, result.Critical ? "critical" : "noncritical"); + } + + return ValueTask.FromResult(new EvaluationResult(metric)); + } + + private protected virtual CheckResult Evaluate( + IncidentResponse? response, string? error, IEnumerable? additionalContext) + { + IncidentCase incident = additionalContext?.OfType().SingleOrDefault()?.Incident + ?? throw new ArgumentException("Provide an IncidentEvaluationContext for the case.", nameof(additionalContext)); + + return response is null + ? new CheckResult(null, "Not evaluated because the response failed its contract.") + : EvaluateIncident(response, incident); + } + + private protected virtual CheckResult EvaluateIncident(IncidentResponse response, IncidentCase incident) => + throw new NotSupportedException("This evaluator does not perform a case-specific check."); + + private protected readonly record struct CheckResult(bool? Passed, string Reason, bool Critical = false); +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentResponse.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentResponse.cs new file mode 100644 index 0000000..211ed52 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/IncidentResponse.cs @@ -0,0 +1,50 @@ +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace EvaluationRunner; + +internal sealed record IncidentResponse( + string? Summary, string[]? EvidenceIds, string[]? Unknowns, string? CauseStatus, string? Cause) +{ + private static readonly Regex EvidenceId = new(@"\AE-[0-9]{3}\z"); + private static readonly Regex FactId = new(@"\A[a-z0-9]+(?:-[a-z0-9]+)*\z"); + private static readonly Regex CauseId = new(@"\ACAUSE-[A-Z0-9]+(?:-[A-Z0-9]+)*\z"); + + internal static (IncidentResponse? Response, string? Error) Parse(string json) + { + IncidentResponse? response; + try + { + response = JsonSerializer.Deserialize(json, IncidentJson.Options); + } + catch (JsonException) + { + return (null, "Expected one JSON object with exactly the five required response fields and their declared types."); + } + + if (response is null || string.IsNullOrWhiteSpace(response.Summary)) + return (null, "The summary must contain non-whitespace text."); + + if (!AreValidIds(response.EvidenceIds, EvidenceId)) + return (null, "Evidence IDs must be unique and use the format E-000."); + + if (!AreValidIds(response.Unknowns, FactId)) + return (null, "Unknown fact IDs must be unique, lowercase, hyphen-separated identifiers."); + + string? error = response.CauseStatus switch + { + "confirmed" when response.Cause is null || !CauseId.IsMatch(response.Cause) => + "A confirmed cause requires a valid CAUSE- identifier.", + "unconfirmed" or "not-applicable" when response.Cause is not null => + "The cause must be null for an unconfirmed or not-applicable cause status.", + "confirmed" or "unconfirmed" or "not-applicable" => null, + _ => "Expected a recognized cause status." + }; + return error is null ? (response, null) : (null, error); + } + + private static bool AreValidIds(string[]? values, Regex pattern) => + values is not null + && values.All(value => value is not null && pattern.IsMatch(value)) + && values.Distinct(StringComparer.Ordinal).Count() == values.Length; +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/OfflineReplay.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/OfflineReplay.cs new file mode 100644 index 0000000..c361ff1 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/OfflineReplay.cs @@ -0,0 +1,111 @@ +using Microsoft.Extensions.AI; +using Microsoft.Extensions.AI.Evaluation; + +namespace EvaluationRunner; + +public sealed record OfflineReplayResult( + PromptIdentity BaselinePrompt, + PromptIdentity CandidatePrompt, + IReadOnlyList Comparisons, + ReleaseAssessment Assessment, + IReadOnlyList Provenance); + +public sealed record OfflineCaseReplayResult( + PromptIdentity PreviousPrompt, + PromptIdentity ProposedPrompt, + IReadOnlyList Comparisons, + IReadOnlyList Provenance); + +public static class OfflineReplay +{ + public static async Task RunAsync( + string root, PromptIdentity baseline, PromptIdentity candidate, CancellationToken cancellationToken = default) + { + IncidentCase[] cases = IncidentDataset.LoadAll(root); + string baselineDirectory = Path.Combine(root, "responses", baseline.Id); + string candidateDirectory = Path.Combine(root, "responses", candidate.Id); + VerifyFixtureSet(baselineDirectory, cases); + VerifyFixtureSet(candidateDirectory, cases); + + var baselineChecks = new List(); + var candidateChecks = new List(); + var provenance = new List(); + foreach (IncidentCase incident in cases) + { + ReplaySide previous = await EvaluateFixtureAsync( + baselineDirectory, baseline, incident, cancellationToken); + ReplaySide proposed = await EvaluateFixtureAsync( + candidateDirectory, candidate, incident, cancellationToken); + baselineChecks.AddRange(previous.Checks); + candidateChecks.AddRange(proposed.Checks); + provenance.Add(previous.Provenance); + provenance.Add(proposed.Provenance); + } + + IReadOnlyList comparisons = HardCheckComparer.Compare(baselineChecks, candidateChecks); + IEnumerable expected = from incident in cases + from evaluator in IncidentHardChecks.All + from name in evaluator.EvaluationMetricNames + select new HardCheckKey(incident.Id, name); + ReleaseAssessment assessment = ReleasePolicy.Evaluate(comparisons, expected); + return new OfflineReplayResult(baseline, candidate, comparisons, assessment, provenance.AsReadOnly()); + } + + public static async Task RunCaseAsync( + string root, string caseId, PromptIdentity previous, PromptIdentity proposed, + CancellationToken cancellationToken = default) + { + IncidentCase incident = IncidentDataset.LoadOne(root, caseId); + ReplaySide before = await EvaluateFixtureAsync( + Path.Combine(root, "responses", previous.Id), previous, incident, cancellationToken); + ReplaySide after = await EvaluateFixtureAsync( + Path.Combine(root, "responses", proposed.Id), proposed, incident, cancellationToken); + return new OfflineCaseReplayResult( + previous, proposed, HardCheckComparer.Compare(before.Checks, after.Checks), + [before.Provenance, after.Provenance]); + } + + private static async Task EvaluateFixtureAsync( + string directory, PromptIdentity prompt, IncidentCase incident, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + ResponseFixture fixture = ResponseFixture.Load( + Path.Combine(directory, incident.Id + ".json"), incident.Id, prompt); + return new ReplaySide( + fixture.Provenance, await EvaluateAsync(incident, fixture.ResponseText, cancellationToken)); + } + + private sealed record ReplaySide(ResponseProvenance Provenance, IReadOnlyList Checks); + + private static void VerifyFixtureSet(string directory, IEnumerable cases) + { + var expected = cases.Select(incident => incident.Id).ToHashSet(StringComparer.Ordinal); + var actual = Directory.GetFiles(directory, "*.json") + .Select(path => Path.GetFileNameWithoutExtension(path)).ToHashSet(StringComparer.Ordinal); + if (!expected.SetEquals(actual)) + { + string missing = string.Join(", ", expected.Except(actual).Order(StringComparer.Ordinal)); + string unexpected = string.Join(", ", actual.Except(expected).Order(StringComparer.Ordinal)); + throw new InvalidDataException( + $"Incomplete or unexpected fixtures in '{Path.GetFileName(directory)}'. " + + $"Missing: [{missing}]. Unexpected: [{unexpected}]."); + } + } + + private static async Task> EvaluateAsync( + IncidentCase incident, string responseText, CancellationToken cancellationToken) + { + var response = new ChatResponse(new ChatMessage(ChatRole.Assistant, responseText)); + EvaluationContext[] context = [new IncidentEvaluationContext(incident)]; + var checks = new List(IncidentHardChecks.All.Count); + foreach (IEvaluator evaluator in IncidentHardChecks.All) + { + EvaluationResult result = await evaluator.EvaluateAsync( + [], response, additionalContext: context, cancellationToken: cancellationToken); + foreach (string name in evaluator.EvaluationMetricNames) + checks.Add(HardCheckResult.FromMetric(incident.Id, result.Get(name))); + } + + return checks; + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/Program.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/Program.cs new file mode 100644 index 0000000..3590289 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/Program.cs @@ -0,0 +1,52 @@ +using System.Text.Json; +using EvaluationRunner; + +try +{ + if (args.FirstOrDefault() == "--case") + { + if (args.Length is < 2 or > 3) + return Usage(); + + string root = Path.GetFullPath(args.Length == 3 ? args[2] : "."); + PromptIdentity candidate = LoadPrompt(root, "candidate", "v2"); + PromptIdentity repaired = LoadPrompt(root, "repaired", "v3"); + OfflineCaseReplayResult diagnostic = await OfflineReplay.RunCaseAsync(root, args[1], candidate, repaired); + Console.Write(ReplayScorecard.Render(diagnostic)); + return 0; + } + + bool compareRepaired = args.FirstOrDefault() == "--repaired"; + string[] paths = compareRepaired ? args[1..] : args; + if (paths.Length > 2 || paths.FirstOrDefault()?.StartsWith("--", StringComparison.Ordinal) == true) + return Usage(); + + string sampleRoot = Path.GetFullPath(paths.Length == 0 ? "." : paths[0]); + PromptIdentity baseline = LoadPrompt(sampleRoot, "baseline", "v1"); + PromptIdentity proposed = compareRepaired + ? LoadPrompt(sampleRoot, "repaired", "v3") + : LoadPrompt(sampleRoot, "candidate", "v2"); + OfflineReplayResult result = await OfflineReplay.RunAsync(sampleRoot, baseline, proposed); + string scorecard = ReplayScorecard.Render(result); + if (paths.Length == 2) + File.WriteAllText(paths[1], scorecard); + else + Console.Write(scorecard); + + return 0; +} +catch (Exception error) when (error is IOException or InvalidDataException or JsonException or ArgumentException) +{ + Console.Error.WriteLine($"Offline replay failed: {error.Message}"); + return 1; +} + +static PromptIdentity LoadPrompt(string root, string id, string version) => + PromptIdentity.Load(id, version, Path.Combine(root, "prompts", id + ".txt")); + +static int Usage() +{ + Console.Error.WriteLine("Usage: EvaluationRunner [--repaired] [sample-root] [scorecard-output]"); + Console.Error.WriteLine(" EvaluationRunner --case [sample-root]"); + return 2; +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/PromptIdentity.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/PromptIdentity.cs new file mode 100644 index 0000000..88cc671 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/PromptIdentity.cs @@ -0,0 +1,33 @@ +using System.Security.Cryptography; +using System.Text; + +namespace EvaluationRunner; + +public sealed class PromptIdentity +{ + private static readonly UTF8Encoding Utf8 = new(false, true); + + private PromptIdentity(string id, string version, string text) + { + Id = id; + Version = version; + Text = text; + Hash = Convert.ToHexStringLower(SHA256.HashData(Utf8.GetBytes(text))); + } + + public string Id { get; } + public string Version { get; } + public string Text { get; } + public string Hash { get; } + + public static PromptIdentity FromText(string id, string version, string text) + { + ArgumentException.ThrowIfNullOrWhiteSpace(id); + ArgumentException.ThrowIfNullOrWhiteSpace(version); + ArgumentException.ThrowIfNullOrWhiteSpace(text); + return new PromptIdentity(id, version, text); + } + + public static PromptIdentity Load(string id, string version, string path) => + FromText(id, version, Utf8.GetString(File.ReadAllBytes(path))); +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/ReleasePolicy.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/ReleasePolicy.cs new file mode 100644 index 0000000..0e0b104 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/ReleasePolicy.cs @@ -0,0 +1,77 @@ +namespace EvaluationRunner; + +public enum ReleaseDecision +{ + Ship, + Review, + Block +} + +public sealed record ReleaseIssue(ReleaseDecision Impact, HardCheckKey? Key, string Reason); + +public sealed record ReleaseAssessment(ReleaseDecision Decision, IReadOnlyList Issues); + +public static class ReleasePolicy +{ + public static ReleaseAssessment Evaluate( + IEnumerable comparisons, + IEnumerable expectedChecks, + string? qualityConcern = null) + { + ArgumentNullException.ThrowIfNull(comparisons); + ArgumentNullException.ThrowIfNull(expectedChecks); + + var missingChecks = new HashSet(); + foreach (HardCheckKey key in expectedChecks) + { + if (!missingChecks.Add(key)) + throw new ArgumentException($"Duplicate expected hard check: {key}.", nameof(expectedChecks)); + } + + if (missingChecks.Count == 0) + throw new ArgumentException("At least one expected hard check is required.", nameof(expectedChecks)); + + var issues = new List(); + foreach (HardCheckComparison row in comparisons) + { + if (!missingChecks.Remove(row.Key)) + throw new ArgumentException($"Duplicate or unexpected hard-check result: {row.Key}.", nameof(comparisons)); + + ReleaseIssue? issue = AssessCheck(row); + if (issue is not null) + issues.Add(issue); + } + + foreach (HardCheckKey key in missingChecks.OrderBy(key => key.CaseId, StringComparer.Ordinal) + .ThenBy(key => key.CheckName, StringComparer.Ordinal)) + issues.Add(new ReleaseIssue(ReleaseDecision.Review, key, "An expected hard-check result is missing.")); + + if (!string.IsNullOrWhiteSpace(qualityConcern)) + issues.Add(new ReleaseIssue(ReleaseDecision.Review, null, qualityConcern)); + + ReleaseDecision decision = issues.Any(issue => issue.Impact == ReleaseDecision.Block) + ? ReleaseDecision.Block + : issues.Count > 0 ? ReleaseDecision.Review : ReleaseDecision.Ship; + return new ReleaseAssessment(decision, issues.AsReadOnly()); + } + + private static ReleaseIssue? AssessCheck(HardCheckComparison row) + { + if (row.Candidate.Passed is true) + return null; + + if (row.Candidate.Passed is null) + return new ReleaseIssue(ReleaseDecision.Review, row.Key, "The candidate hard check was not evaluated."); + + if (row.Transition == HardCheckTransition.Regression) + return new ReleaseIssue(ReleaseDecision.Block, row.Key, "A previously passing hard check now fails."); + + if (row.Candidate.Severity == HardCheckSeverity.Critical) + return new ReleaseIssue(ReleaseDecision.Block, row.Key, "The candidate has a critical hard-check failure."); + + return new ReleaseIssue(ReleaseDecision.Review, row.Key, + row.Transition == HardCheckTransition.ExistingFailure + ? "An existing noncritical hard-check failure remains." + : "The candidate failed a noncritical check without a comparable baseline result."); + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/ReplayScorecard.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/ReplayScorecard.cs new file mode 100644 index 0000000..7154ba0 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/ReplayScorecard.cs @@ -0,0 +1,102 @@ +namespace EvaluationRunner; + +public static class ReplayScorecard +{ + public static string Render(OfflineReplayResult replay) + { + string origins = string.Join(", ", replay.Provenance.GroupBy(item => item.ResponseOrigin) + .OrderBy(group => group.Key, StringComparer.Ordinal) + .Select(group => $"{group.Count()} `{group.Key}`")); + var lines = new List + { + "# Offline evaluation scorecard", + "", + $"Baseline: `{replay.BaselinePrompt.Id} {replay.BaselinePrompt.Version}`. " + + $"Proposed: `{replay.CandidatePrompt.Id} {replay.CandidatePrompt.Version}`.", + "", + $"Evidence: offline fixture replay ({origins}).", + "", + $"**Release decision: {replay.Assessment.Decision.ToString().ToUpperInvariant()}**", + "", + "| Case | Baseline | Proposed | Changed or failing checks |", + "|---|---|---|---|" + }; + + foreach (IGrouping group in replay.Comparisons.GroupBy(row => row.Key.CaseId)) + { + string previous = CaseStatus(group.Select(row => row.Baseline)); + string proposed = CaseStatus(group.Select(row => row.Candidate)); + string changes = string.Join("; ", group.Where(row => row.Transition != HardCheckTransition.UnchangedPass) + .Select(DescribeTransition)); + lines.Add($"| `{group.Key}` | {previous} | {proposed} | {(changes.Length == 0 ? "—" : changes)} |"); + } + + lines.AddRange(["", "## Release findings", ""]); + if (replay.Assessment.Issues.Count == 0) + lines.Add("All expected proposed hard checks passed."); + foreach (ReleaseIssue issue in replay.Assessment.Issues) + { + string check = issue.Key is HardCheckKey key ? $" `{key.CaseId}` / {key.CheckName}." : ""; + lines.Add($"- **{issue.Impact.ToString().ToUpperInvariant()}**{check} {issue.Reason}"); + } + + lines.Add(""); + return string.Join('\n', lines); + } + + public static string Render(OfflineCaseReplayResult diagnostic) + { + string caseId = diagnostic.Comparisons[0].Key.CaseId; + string origins = string.Join(", ", diagnostic.Provenance.Select(item => item.ResponseOrigin) + .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)); + var lines = new List + { + $"# Single-case diagnostic: {caseId}", + "", + $"Evidence: offline fixture replay ({origins}).", + "A release decision requires the full 12-case replay against the original baseline.", + "", + $"| Hard check | {diagnostic.PreviousPrompt.Id} {diagnostic.PreviousPrompt.Version} | " + + $"{diagnostic.ProposedPrompt.Id} {diagnostic.ProposedPrompt.Version} | Change |", + "|---|---|---|---|" + }; + + foreach (HardCheckComparison row in diagnostic.Comparisons) + { + string change = row.Transition == HardCheckTransition.UnchangedPass ? "unchanged pass" : DescribeTransition(row); + lines.Add($"| {row.Key.CheckName} | {CheckStatus(row.Baseline.Passed)} | " + + $"{CheckStatus(row.Candidate.Passed)} | {change} |"); + } + + lines.Add(""); + return string.Join('\n', lines); + } + + private static string CheckStatus(bool? passed) => passed switch + { + true => "PASS", + false => "FAIL", + null => "UNEVALUATED" + }; + + private static string CaseStatus(IEnumerable checks) + { + if (checks.Any(check => check.Passed is false)) + return "FAIL"; + + return checks.All(check => check.Passed is true) ? "PASS" : "UNEVALUATED"; + } + + private static string DescribeTransition(HardCheckComparison row) + { + string transition = row.Transition switch + { + HardCheckTransition.Regression => "regression", + HardCheckTransition.Improvement => "improvement", + HardCheckTransition.ExistingFailure => "existing failure", + _ => "not comparable" + }; + string severity = row.Candidate.Severity == HardCheckSeverity.Critical ? "critical " : ""; + return $"{row.Key.CheckName}: {severity}{transition}"; + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/ResponseContractEvaluator.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/ResponseContractEvaluator.cs new file mode 100644 index 0000000..a238544 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/ResponseContractEvaluator.cs @@ -0,0 +1,14 @@ +using Microsoft.Extensions.AI.Evaluation; + +namespace EvaluationRunner; + +public sealed class ResponseContractEvaluator() : IncidentHardEvaluator(MetricName) +{ + public const string MetricName = "Response contract"; + + private protected override CheckResult Evaluate( + IncidentResponse? response, string? error, IEnumerable? additionalContext) => + response is not null + ? new CheckResult(true, "The response satisfies the JSON contract.") + : new CheckResult(false, error!, Critical: true); +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/ResponseFixture.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/ResponseFixture.cs new file mode 100644 index 0000000..62bd6c8 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/ResponseFixture.cs @@ -0,0 +1,102 @@ +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace EvaluationRunner; + +public static class ResponseOrigins +{ + public const string CapturedLive = "captured-live"; + public const string HandAuthoredFixture = "hand-authored-fixture"; +} + +public sealed record ResponseProvenance( + string CaseId, + string PromptId, + string PromptVersion, + string PromptHash, + string ResponseOrigin, + DateTimeOffset CreatedAt, + string? Model = null, + JsonElement? GenerationSettings = null); + +public sealed class ResponseFixture +{ + private static readonly Regex Sha256Hex = new(@"\A[a-f0-9]{64}\z"); + private static readonly JsonSerializerOptions OutputOptions = new(IncidentJson.Options) { WriteIndented = true }; + + private ResponseFixture(ResponseProvenance provenance, string responseText) + { + Provenance = provenance; + ResponseText = responseText; + } + + public ResponseProvenance Provenance { get; } + public string ResponseText { get; } + + public static ResponseFixture Create( + string caseId, PromptIdentity prompt, string responseText, string responseOrigin, + DateTimeOffset createdAt, string? model = null, JsonElement? generationSettings = null) + { + ArgumentNullException.ThrowIfNull(prompt); + ArgumentNullException.ThrowIfNull(responseText); + var provenance = new ResponseProvenance( + caseId, prompt.Id, prompt.Version, prompt.Hash, responseOrigin, createdAt, + model, generationSettings?.Clone()); + ValidateMetadata(provenance); + return new ResponseFixture(provenance, responseText); + } + + public string ToJson() => JsonSerializer.Serialize(new FixtureDocument(Provenance, ResponseText), OutputOptions); + + public static ResponseFixture Load(string path, string expectedCaseId, PromptIdentity expectedPrompt) => + Parse(File.ReadAllText(path), expectedCaseId, expectedPrompt); + + public static ResponseFixture Parse(string json, string expectedCaseId, PromptIdentity expectedPrompt) + { + ArgumentException.ThrowIfNullOrWhiteSpace(expectedCaseId); + ArgumentNullException.ThrowIfNull(expectedPrompt); + FixtureDocument? fixture = JsonSerializer.Deserialize(json, IncidentJson.Options); + if (fixture?.Provenance is null || fixture.ResponseText is null) + throw new InvalidDataException("A response fixture requires metadata and a responseText string."); + + ResponseProvenance provenance = fixture.Provenance; + ValidateMetadata(provenance); + if (provenance.CaseId != expectedCaseId) + throw new InvalidDataException($"Fixture belongs to case '{provenance.CaseId}', expected '{expectedCaseId}'."); + + if (provenance.PromptId != expectedPrompt.Id || provenance.PromptVersion != expectedPrompt.Version) + throw new InvalidDataException( + $"Fixture belongs to prompt '{provenance.PromptId}' ({provenance.PromptVersion}), " + + $"expected '{expectedPrompt.Id}' ({expectedPrompt.Version})."); + + if (provenance.PromptHash != expectedPrompt.Hash) + throw new InvalidDataException($"Stale fixture for case '{expectedCaseId}': prompt content has changed."); + + return new ResponseFixture(provenance, fixture.ResponseText); + } + + private static void ValidateMetadata(ResponseProvenance metadata) + { + if (string.IsNullOrWhiteSpace(metadata.CaseId) || string.IsNullOrWhiteSpace(metadata.PromptId) + || string.IsNullOrWhiteSpace(metadata.PromptVersion) + || metadata.PromptHash is null || !Sha256Hex.IsMatch(metadata.PromptHash) + || metadata.CreatedAt == default) + throw new InvalidDataException("Expected case and prompt identity, a lowercase SHA-256 hash, and a creation timestamp."); + + switch (metadata.ResponseOrigin) + { + case ResponseOrigins.CapturedLive: + if (string.IsNullOrWhiteSpace(metadata.Model) || metadata.GenerationSettings?.ValueKind != JsonValueKind.Object) + throw new InvalidDataException("A captured-live fixture requires a model and a generation-settings object."); + break; + case ResponseOrigins.HandAuthoredFixture: + if (metadata.Model is not null || metadata.GenerationSettings is not null) + throw new InvalidDataException("A hand-authored fixture cannot claim a model or generation settings."); + break; + default: + throw new InvalidDataException($"Unsupported response origin '{metadata.ResponseOrigin}'."); + } + } + + private sealed record FixtureDocument(ResponseProvenance Provenance, string ResponseText); +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/UnknownFactEvaluator.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/UnknownFactEvaluator.cs new file mode 100644 index 0000000..958f855 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/EvaluationRunner/UnknownFactEvaluator.cs @@ -0,0 +1,24 @@ +namespace EvaluationRunner; + +public sealed class UnknownFactEvaluator() : IncidentHardEvaluator(MetricName) +{ + public const string MetricName = "Unknown preservation"; + + private protected override CheckResult EvaluateIncident(IncidentResponse response, IncidentCase incident) + { + string[] reported = response.Unknowns!; + string[] missing = incident.RequiredUnknowns.Except(reported, StringComparer.Ordinal).ToArray(); + string[] unexpected = reported.Except(incident.RequiredUnknowns, StringComparer.Ordinal).ToArray(); + if (missing.Length == 0 && unexpected.Length == 0) + return new CheckResult(true, "Unknowns match the expected unknown facts."); + + var reasons = new List(2); + if (missing.Length > 0) + reasons.Add($"Missing expected unknowns: {string.Join(", ", missing)}."); + if (unexpected.Length > 0) + reasons.Add($"Unexpected unknowns: {string.Join(", ", unexpected)}."); + + bool critical = missing.Intersect(incident.CriticalUnknownIds, StringComparer.Ordinal).Any(); + return new CheckResult(false, string.Join(" ", reasons), critical); + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/LiveEvaluation/LiveEvaluation.csproj b/dotnet-ai/microsoft-extensions-ai-evaluation/src/LiveEvaluation/LiveEvaluation.csproj new file mode 100644 index 0000000..a45f3a8 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/LiveEvaluation/LiveEvaluation.csproj @@ -0,0 +1,15 @@ + + + Exe + net10.0 + enable + enable + true + + + + + + + + diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/LiveEvaluation/LiveEvaluationRun.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/LiveEvaluation/LiveEvaluationRun.cs new file mode 100644 index 0000000..bf5b7c8 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/LiveEvaluation/LiveEvaluationRun.cs @@ -0,0 +1,137 @@ +using System.Text.Json; +using EvaluationRunner; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.AI.Evaluation; +using Microsoft.Extensions.AI.Evaluation.Quality; +using Microsoft.Extensions.AI.Evaluation.Reporting; +using Microsoft.Extensions.AI.Evaluation.Reporting.Storage; + +namespace LiveEvaluation; + +public sealed record LiveEvaluationSummary( + string OutputDirectory, int Cases, int FreshResponses, int CacheHits, + int CoherenceEvaluations, int CoherenceScores, string ResponseOrigin); + +public static class LiveEvaluationRun +{ + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + + public static async Task RunAsync( + string sampleRoot, string outputParent, IChatClient generator, string generationModel, + IChatClient? judge = null, string? caseId = null, + string responseOrigin = ResponseOrigins.CapturedLive, CancellationToken cancellationToken = default) + { + IncidentCase[] cases = caseId is null ? IncidentDataset.LoadAll(sampleRoot) : [IncidentDataset.LoadOne(sampleRoot, caseId)]; + PromptIdentity[] prompts = + [ + PromptIdentity.Load("baseline", "v1", Path.Combine(sampleRoot, "prompts", "baseline.txt")), + PromptIdentity.Load("candidate", "v2", Path.Combine(sampleRoot, "prompts", "candidate.txt")) + ]; + string output = Path.Combine(Path.GetFullPath(outputParent), $"evaluation-{Guid.NewGuid():N}"); + Directory.CreateDirectory(output); + + var counted = new CountingChatClient(generator); + ReportingConfiguration cache = DiskBasedReportingConfiguration.Create( + Path.Combine(output, "generation-cache"), [new ResponseContractEvaluator()], new ChatConfiguration(counted), + enableResponseCaching: true); + string reportRoot = Path.Combine(output, "reports"); + ReportingConfiguration hardChecks = DiskBasedReportingConfiguration.Create( + reportRoot, IncidentHardChecks.All, enableResponseCaching: false, executionName: "hard-checks"); + ReportingConfiguration? coherence = judge is null ? null : DiskBasedReportingConfiguration.Create( + reportRoot, [new CoherenceEvaluator()], new ChatConfiguration(judge), + enableResponseCaching: false, executionName: "coherence"); + + var generation = new ChatOptions { Temperature = 0.0f, MaxOutputTokens = 384, ResponseFormat = ChatResponseFormat.Json }; + JsonElement settings = JsonSerializer.SerializeToElement(new + { + generation.Temperature, generation.MaxOutputTokens, ResponseFormat = "json_object" + }, JsonOptions); + int cacheHits = 0; + int coherenceEvaluations = 0; + int coherenceScores = 0; + foreach (PromptIdentity prompt in prompts) + { + string responses = Path.Combine(output, "responses", prompt.Id); + Directory.CreateDirectory(responses); + foreach (IncidentCase incident in cases) + { + string scenario = $"{prompt.Id}-{incident.Id}"; + ChatMessage[] messages = + [ + new(ChatRole.System, prompt.Text), + new(ChatRole.User, JsonSerializer.Serialize(new + { + incident.Question, incident.RequestedFactIds, incident.Evidence + }, JsonOptions)) + ]; + int beforeFresh = counted.CallCount; + ChatResponse response = await FetchAsync(cache, scenario, messages, generation, cancellationToken); + if (counted.CallCount != beforeFresh + 1) + throw new InvalidOperationException("The first request did not reach the generation client."); + ResponseFixture fixture = ResponseFixture.Create(incident.Id, prompt, response.Text, responseOrigin, + DateTimeOffset.UtcNow, + responseOrigin == ResponseOrigins.CapturedLive ? generationModel : null, + responseOrigin == ResponseOrigins.CapturedLive ? settings : null); + await File.WriteAllTextAsync(Path.Combine(responses, incident.Id + ".json"), fixture.ToJson(), cancellationToken); + + EvaluationResult result; + await using (ScenarioRun run = await hardChecks.CreateScenarioRunAsync( + scenario, cancellationToken: cancellationToken)) + { + result = await run.EvaluateAsync( + messages, response, [new IncidentEvaluationContext(incident)], cancellationToken); + } + + if (coherence is not null + && result.Get(ResponseContractEvaluator.MetricName).Value is true) + { + using JsonDocument body = JsonDocument.Parse(response.Text); + var summary = new ChatResponse(new ChatMessage(ChatRole.Assistant, + body.RootElement.GetProperty("summary").GetString())); + await using ScenarioRun run = await coherence.CreateScenarioRunAsync( + scenario, cancellationToken: cancellationToken); + EvaluationResult review = await run.EvaluateAsync( + [new ChatMessage(ChatRole.User, incident.Question)], summary, cancellationToken: cancellationToken); + coherenceEvaluations++; + if (review.Get(CoherenceEvaluator.CoherenceMetricName).Value is not null) + coherenceScores++; + } + + if (cacheHits == 0) + { + int before = counted.CallCount; + ChatResponse replay = await FetchAsync(cache, scenario, messages, generation, cancellationToken); + if (counted.CallCount != before || replay.Text != response.Text) + throw new InvalidOperationException("The identical verification request did not produce a cache hit."); + + cacheHits++; + } + } + } + + var summaryResult = new LiveEvaluationSummary(output, cases.Length, counted.CallCount, cacheHits, + coherenceEvaluations, coherenceScores, responseOrigin); + await File.WriteAllTextAsync(Path.Combine(output, "run-summary.json"), + JsonSerializer.Serialize(summaryResult, JsonOptions), cancellationToken); + return summaryResult; + } + + private static async Task FetchAsync(ReportingConfiguration cache, string scenario, + ChatMessage[] messages, ChatOptions options, CancellationToken cancellationToken) + { + await using ScenarioRun run = await cache.CreateScenarioRunAsync(scenario, cancellationToken: cancellationToken); + return await run.ChatConfiguration!.ChatClient.GetResponseAsync(messages, options, cancellationToken); + } + + private sealed class CountingChatClient(IChatClient inner) : DelegatingChatClient(inner) + { + public int CallCount { get; private set; } + + public override Task GetResponseAsync(IEnumerable messages, + ChatOptions? options = null, CancellationToken cancellationToken = default) + { + CallCount++; + return base.GetResponseAsync(messages, options, cancellationToken); + } + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/src/LiveEvaluation/Program.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/src/LiveEvaluation/Program.cs new file mode 100644 index 0000000..89707f0 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/src/LiveEvaluation/Program.cs @@ -0,0 +1,55 @@ +using System.ClientModel; +using LiveEvaluation; +using Microsoft.Extensions.AI; +using OpenAI; + +if (args.Length is < 2 or > 3) +{ + Console.Error.WriteLine("Usage: LiveEvaluation [incident-id]"); + return 2; +} + +string? endpoint = Environment.GetEnvironmentVariable("DOTNET_EVAL_ENDPOINT"); +string? model = Environment.GetEnvironmentVariable("DOTNET_EVAL_MODEL"); +if (!Uri.TryCreate(endpoint, UriKind.Absolute, out Uri? uri) || string.IsNullOrWhiteSpace(model) + || (uri.Scheme != Uri.UriSchemeHttps && !(uri.IsLoopback && uri.Scheme == Uri.UriSchemeHttp))) +{ + Console.Error.WriteLine("Set DOTNET_EVAL_ENDPOINT to the provider's HTTPS API base URL or an HTTP loopback URL, and set DOTNET_EVAL_MODEL."); + return 2; +} + +string? key = Environment.GetEnvironmentVariable("DOTNET_EVAL_API_KEY"); +if (string.IsNullOrWhiteSpace(key)) +{ + if (!uri.IsLoopback) + { + Console.Error.WriteLine("Set DOTNET_EVAL_API_KEY to use an external model endpoint."); + return 2; + } + + key = "local"; +} + +string? judgeModel = Environment.GetEnvironmentVariable("DOTNET_EVAL_JUDGE_MODEL"); +using IChatClient generator = CreateClient(uri, key, model); +using IChatClient? judge = string.IsNullOrWhiteSpace(judgeModel) ? null : CreateClient(uri, key, judgeModel); + +try +{ + LiveEvaluationSummary result = await LiveEvaluationRun.RunAsync( + args[0], args[1], generator, model, judge, args.Length == 3 ? args[2] : null); + Console.WriteLine($"Fresh responses: {result.FreshResponses}. Verified cache hits: {result.CacheHits}."); + Console.WriteLine($"Coherence scores: {result.CoherenceScores}/{result.CoherenceEvaluations}."); + Console.WriteLine($"Output: {result.OutputDirectory}"); + return 0; +} +catch (Exception error) when (error is ClientResultException or IOException or InvalidDataException or InvalidOperationException + || error is AggregateException aggregate && aggregate.Flatten().InnerExceptions.All(inner => inner is ClientResultException)) +{ + Console.Error.WriteLine($"Live evaluation failed ({error.GetType().Name}). Check the endpoint, model, and run output."); + return 1; +} + +static IChatClient CreateClient(Uri endpoint, string key, string model) => + new OpenAIClient(new ApiKeyCredential(key), new OpenAIClientOptions { Endpoint = endpoint }) + .GetChatClient(model).AsIChatClient(); diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/EvaluationRunner.Tests.csproj b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/EvaluationRunner.Tests.csproj new file mode 100644 index 0000000..6bd5c85 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/EvaluationRunner.Tests.csproj @@ -0,0 +1,22 @@ + + + net10.0 + enable + enable + true + false + + + + + + + + + + + + + + + diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/HardCheckComparerTests.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/HardCheckComparerTests.cs new file mode 100644 index 0000000..6df0ca4 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/HardCheckComparerTests.cs @@ -0,0 +1,148 @@ +using Microsoft.Extensions.AI; +using Microsoft.Extensions.AI.Evaluation; +using Xunit; + +namespace EvaluationRunner.Tests; + +public sealed class HardCheckComparerTests +{ + private const string CaseOne = "incident-01-temporal-correlation"; + private const string CaseTwo = "incident-02-queue-and-scheduled-export"; + private const string Cause = CauseSupportEvaluator.MetricName; + private const string Citations = EvidenceCitationEvaluator.MetricName; + + [Theory] + [InlineData(true, true, HardCheckTransition.UnchangedPass)] + [InlineData(true, false, HardCheckTransition.Regression)] + [InlineData(false, true, HardCheckTransition.Improvement)] + [InlineData(false, false, HardCheckTransition.ExistingFailure)] + [InlineData(null, true, HardCheckTransition.NotComparable)] + [InlineData(null, false, HardCheckTransition.NotComparable)] + [InlineData(true, null, HardCheckTransition.NotComparable)] + [InlineData(false, null, HardCheckTransition.NotComparable)] + [InlineData(null, null, HardCheckTransition.NotComparable)] + public void EachStatusPairHasAnExplicitTransition( + bool? baselinePassed, bool? candidatePassed, HardCheckTransition expected) + { + HardCheckResult baseline = Result(CaseOne, Cause, baselinePassed); + HardCheckResult candidate = Result(CaseOne, Cause, candidatePassed); + HardCheckComparison comparison = Assert.Single(HardCheckComparer.Compare([baseline], [candidate])); + + Assert.Equal(new HardCheckKey(CaseOne, Cause), comparison.Key); + Assert.Equal(expected, comparison.Transition); + Assert.Same(baseline, comparison.Baseline); + Assert.Same(candidate, comparison.Candidate); + } + + [Fact] + public void ResultsMatchByBothCaseAndCheckRegardlessOfRowOrder() + { + HardCheckResult[] baseline = + [ + Result(CaseTwo, Cause, true), + Result(CaseOne, Citations, false), + Result(CaseOne, Cause, true) + ]; + HardCheckResult[] candidate = + [ + Result(CaseOne, Cause, true), + Result(CaseTwo, Cause, false), + Result(CaseOne, Citations, true) + ]; + + IReadOnlyList comparisons = HardCheckComparer.Compare(baseline, candidate); + Assert.Collection(comparisons, + row => AssertRow(row, CaseOne, Cause, HardCheckTransition.UnchangedPass), + row => AssertRow(row, CaseOne, Citations, HardCheckTransition.Improvement), + row => AssertRow(row, CaseTwo, Cause, HardCheckTransition.Regression)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DuplicateRowsAreRejectedOnEitherSide(bool duplicateBaseline) + { + HardCheckResult entry = Result(CaseOne, Cause, true); + HardCheckResult[] baseline = duplicateBaseline ? [entry, entry] : [entry]; + HardCheckResult[] candidate = duplicateBaseline ? [entry] : [entry, entry]; + + ArgumentException error = Assert.Throws(() => HardCheckComparer.Compare(baseline, candidate)); + Assert.Equal(duplicateBaseline ? "baseline" : "candidate", error.ParamName); + Assert.Contains(CaseOne, error.Message); + Assert.Contains(Cause, error.Message); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void MissingRowsAreRejectedOnEitherSide(bool missingBaseline) + { + HardCheckResult shared = Result(CaseOne, Cause, true); + HardCheckResult extra = Result(CaseOne, Citations, true); + HardCheckResult[] baseline = missingBaseline ? [shared] : [shared, extra]; + HardCheckResult[] candidate = missingBaseline ? [shared, extra] : [shared]; + + ArgumentException error = Assert.Throws(() => HardCheckComparer.Compare(baseline, candidate)); + Assert.Equal(missingBaseline ? "baseline" : "candidate", error.ParamName); + Assert.Contains(Citations, error.Message); + } + + [Fact] + public void EmptyComparisonIsRejected() + { + Assert.Throws(() => HardCheckComparer.Compare([], [])); + } + + [Theory] + [InlineData(null)] + [InlineData("unexpected")] + public void FailedMetricsRequireRecognizedSeverity(string? severity) + { + var metric = new BooleanMetric(Cause, false); + if (severity is not null) + metric.AddOrUpdateMetadata(IncidentHardEvaluator.SeverityMetadataKey, severity); + + Assert.Throws(() => HardCheckResult.FromMetric(CaseOne, metric)); + } + + [Fact] + public async Task RealEvaluatorMetricsPreserveSeverityAndTheReasonsForARegression() + { + string directory = AppContext.BaseDirectory; + IncidentCase incident = IncidentCase.Parse(File.ReadAllText(Path.Combine(directory, "cases", CaseOne + ".json"))); + var evaluator = new CauseSupportEvaluator(); + HardCheckResult baseline = await ReadFixture("incident-01-unconfirmed"); + HardCheckResult candidate = await ReadFixture("incident-01-unsupported-cause"); + + HardCheckComparison comparison = Assert.Single(HardCheckComparer.Compare([baseline], [candidate])); + AssertRow(comparison, CaseOne, Cause, HardCheckTransition.Regression); + Assert.Null(comparison.Baseline.Severity); + Assert.Equal(HardCheckSeverity.Critical, comparison.Candidate.Severity); + Assert.Contains("match", comparison.Baseline.Reason); + Assert.Contains("CAUSE-DEPLOYMENT", comparison.Candidate.Reason); + + async Task ReadFixture(string filename) + { + string json = File.ReadAllText(Path.Combine(directory, "examples", filename + ".json")); + ChatResponse response = new(new ChatMessage(ChatRole.Assistant, json)); + EvaluationResult evaluation = await evaluator.EvaluateAsync( + [], response, additionalContext: [new IncidentEvaluationContext(incident)]); + return HardCheckResult.FromMetric(incident.Id, evaluation.Get(Cause)); + } + } + + private static HardCheckResult Result(string caseId, string check, bool? passed) + { + var metric = new BooleanMetric(check, passed); + if (passed is false) + metric.AddOrUpdateMetadata(IncidentHardEvaluator.SeverityMetadataKey, "noncritical"); + + return HardCheckResult.FromMetric(caseId, metric); + } + + private static void AssertRow(HardCheckComparison row, string caseId, string check, HardCheckTransition transition) + { + Assert.Equal(new HardCheckKey(caseId, check), row.Key); + Assert.Equal(transition, row.Transition); + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/IncidentEvaluatorTests.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/IncidentEvaluatorTests.cs new file mode 100644 index 0000000..84b7338 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/IncidentEvaluatorTests.cs @@ -0,0 +1,212 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.AI.Evaluation; +using Xunit; + +namespace EvaluationRunner.Tests; + +public sealed class IncidentEvaluatorTests +{ + private static readonly IEvaluator[] Evaluators = + [ + new ResponseContractEvaluator(), + new EvidenceCitationEvaluator(), + new CitationValidityEvaluator(), + new UnknownFactEvaluator(), + new CauseSupportEvaluator() + ]; + + [Theory] + [InlineData(1, "incident-01-unconfirmed")] + [InlineData(4, "incident-04-not-applicable")] + [InlineData(10, "incident-10-confirmed")] + public async Task ValidExamplesPassEveryCheck(int caseNumber, string fixture) + { + IncidentCase incident = LoadCase(caseNumber); + string response = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "examples", fixture + ".json")); + foreach (IEvaluator evaluator in Evaluators) + Check(await Evaluate(evaluator, response, incident), passed: true); + } + + [Fact] + public async Task AllTwelveCasesAcceptAResponseThatMatchesTheirContract() + { + for (int number = 1; number <= 12; number++) + { + IncidentCase incident = LoadCase(number); + string response = MakeResponse(incident).ToJsonString(); + foreach (IEvaluator evaluator in Evaluators) + Check(await Evaluate(evaluator, response, incident), passed: true); + } + } + + [Fact] + public async Task UnsupportedCauseFixtureHasValidShapeAndCitationsButFailsTwoCriticalChecks() + { + IncidentCase incident = LoadCase(1); + string response = File.ReadAllText(Path.Combine( + AppContext.BaseDirectory, "examples", "incident-01-unsupported-cause.json")); + + Check(await Evaluate(new ResponseContractEvaluator(), response), true); + Check(await Evaluate(new EvidenceCitationEvaluator(), response, incident), true); + Check(await Evaluate(new CitationValidityEvaluator(), response, incident), true); + Check(await Evaluate(new UnknownFactEvaluator(), response, incident), false, "critical"); + Check(await Evaluate(new CauseSupportEvaluator(), response, incident), false, "critical"); + } + + [Theory] + [InlineData(1, "critical")] + [InlineData(4, "noncritical")] + public async Task MissingCitationUsesCaseSeverity(int number, string severity) + { + IncidentCase incident = LoadCase(number); + JsonObject response = MakeResponse(incident); + response["evidenceIds"]!.AsArray().RemoveAt(0); + + BooleanMetric metric = await Evaluate(new EvidenceCitationEvaluator(), response.ToJsonString(), incident); + Check(metric, false, severity); + Assert.Contains(incident.RequiredEvidenceIds[0], metric.Reason); + Check(await Evaluate(new CitationValidityEvaluator(), response.ToJsonString(), incident), true); + } + + [Fact] + public async Task CitationFromAnotherCaseIsAnInventedCitation() + { + IncidentCase incident = LoadCase(4); + JsonObject response = MakeResponse(incident); + response["evidenceIds"]!.AsArray().Add(LoadCase(1).Evidence[0].Id); + + Check(await Evaluate(new EvidenceCitationEvaluator(), response.ToJsonString(), incident), true); + Check(await Evaluate(new CitationValidityEvaluator(), response.ToJsonString(), incident), false, "critical"); + } + + [Theory] + [InlineData(7, "noncritical")] + [InlineData(8, "critical")] + public async Task MissingUnknownUsesTheFactSeverity(int number, string severity) + { + IncidentCase incident = LoadCase(number); + JsonObject response = MakeResponse(incident); + response["unknowns"] = new JsonArray(); + Check(await Evaluate(new UnknownFactEvaluator(), response.ToJsonString(), incident), false, severity); + } + + [Fact] + public async Task KnownRequestedFactCannotBeListedAsUnknown() + { + IncidentCase incident = LoadCase(6); + JsonObject response = MakeResponse(incident); + response["unknowns"]!.AsArray().Add("affected-request-count"); + + Check(await Evaluate(new UnknownFactEvaluator(), response.ToJsonString(), incident), false, "noncritical"); + } + + [Theory] + [InlineData("confirmed", "CAUSE-WRONG", "critical")] + [InlineData("unconfirmed", null, "noncritical")] + [InlineData("not-applicable", null, "noncritical")] + public async Task ConfirmedCaseRequiresTheExactSupportedCause(string status, string? cause, string severity) + { + IncidentCase incident = LoadCase(10); + JsonObject response = MakeResponse(incident); + response["causeStatus"] = status; + response["cause"] = cause; + + Check(await Evaluate(new ResponseContractEvaluator(), response.ToJsonString()), true); + Check(await Evaluate(new CauseSupportEvaluator(), response.ToJsonString(), incident), false, severity); + } + + [Theory] + [InlineData("unconfirmed", "CAUSE-DEPLOYMENT")] + [InlineData("not-applicable", "CAUSE-DEPLOYMENT")] + [InlineData("confirmed", null)] + [InlineData("confirmed", "deployment")] + [InlineData("unknown", null)] + public async Task ResponseContractRejectsInvalidCauseFields(string status, string? cause) + { + JsonObject response = MakeResponse(LoadCase(1)); + response["causeStatus"] = status; + response["cause"] = cause; + Check(await Evaluate(new ResponseContractEvaluator(), response.ToJsonString()), false, "critical"); + } + + [Theory] + [InlineData("not json")] + [InlineData("null")] + [InlineData("[]")] + [InlineData("""{"summary":"A","evidenceIds":[],"unknowns":[],"causeStatus":"unconfirmed"}""")] + [InlineData("""{"summary":" ","evidenceIds":[],"unknowns":[],"causeStatus":"unconfirmed","cause":null}""")] + [InlineData("""{"summary":"A","evidenceIds":["E-101","E-101"],"unknowns":[],"causeStatus":"unconfirmed","cause":null}""")] + [InlineData("""{"summary":"A","evidenceIds":["E-101\n"],"unknowns":[],"causeStatus":"unconfirmed","cause":null}""")] + [InlineData("""{"summary":"A","evidenceIds":[null],"unknowns":[],"causeStatus":"unconfirmed","cause":null}""")] + [InlineData("""{"summary":"A","evidenceIds":[],"unknowns":null,"causeStatus":"unconfirmed","cause":null}""")] + [InlineData("""{"summary":"A","evidenceIds":[],"unknowns":["root-cause","root-cause"],"causeStatus":"unconfirmed","cause":null}""")] + [InlineData("""{"summary":"A","evidenceIds":[],"unknowns":[],"causeStatus":"unconfirmed","cause":null,"extra":true}""")] + [InlineData("""{"summary":"A","summary":"B","evidenceIds":[],"unknowns":[],"causeStatus":"unconfirmed","cause":null}""")] + public async Task ResponseContractRejectsMalformedOrAmbiguousJson(string response) + { + Check(await Evaluate(new ResponseContractEvaluator(), response), false, "critical"); + } + + [Fact] + public async Task OtherChecksReportNotEvaluatedWhenTheResponseIsMalformed() + { + foreach (IEvaluator evaluator in Evaluators.Skip(1)) + { + BooleanMetric metric = await Evaluate(evaluator, "{}", LoadCase(1)); + Check(metric, null); + Assert.Equal(EvaluationRating.Unknown, metric.Interpretation?.Rating); + } + } + + [Fact] + public async Task SummaryCanContainAClaimOutsideTheStructuredChecks() + { + IncidentCase incident = LoadCase(1); + JsonObject response = MakeResponse(incident); + response["summary"] = "The deployment definitely caused the outage."; + + foreach (IEvaluator evaluator in Evaluators) + Check(await Evaluate(evaluator, response.ToJsonString(), incident), true); + } + + [Fact] + public async Task MissingCaseContextIsAHarnessError() + { + string response = MakeResponse(LoadCase(1)).ToJsonString(); + await Assert.ThrowsAsync(() => Evaluate(new CauseSupportEvaluator(), response)); + } + + private static IncidentCase LoadCase(int number) + { + string path = Directory.GetFiles(Path.Combine(AppContext.BaseDirectory, "cases"), $"incident-{number:00}-*.json").Single(); + return IncidentCase.Parse(File.ReadAllText(path)); + } + + private static JsonObject MakeResponse(IncidentCase incident) => new() + { + ["summary"] = "Synthetic response generated from test expectations for contract testing.", + ["evidenceIds"] = JsonSerializer.SerializeToNode(incident.RequiredEvidenceIds), + ["unknowns"] = JsonSerializer.SerializeToNode(incident.RequiredUnknowns), + ["causeStatus"] = incident.ExpectedCauseStatus, + ["cause"] = incident.ExpectedCauseId + }; + + private static async Task Evaluate(IEvaluator evaluator, string json, IncidentCase? incident = null) + { + EvaluationContext[]? context = incident is null ? null : [new IncidentEvaluationContext(incident)]; + ChatResponse response = new(new ChatMessage(ChatRole.Assistant, json)); + EvaluationResult result = await evaluator.EvaluateAsync([], response, additionalContext: context); + return result.Get(evaluator.EvaluationMetricNames.Single()); + } + + private static void Check(BooleanMetric metric, bool? passed, string? severity = null) + { + Assert.Equal(passed, metric.Value); + Assert.Equal(passed is false, metric.Interpretation?.Failed); + string? actualSeverity = null; + metric.Metadata?.TryGetValue(IncidentHardEvaluator.SeverityMetadataKey, out actualSeverity); + Assert.Equal(severity, actualSeverity); + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/LiveEvaluationTests.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/LiveEvaluationTests.cs new file mode 100644 index 0000000..3708cef --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/LiveEvaluationTests.cs @@ -0,0 +1,86 @@ +using LiveEvaluation; +using Microsoft.Extensions.AI; +using Xunit; + +namespace EvaluationRunner.Tests; + +public sealed class LiveEvaluationTests +{ + [Fact] + public async Task ScriptedSmokeExercisesCacheReportingAndCoherenceWithoutModelCalls() + { + const string caseId = "incident-01-temporal-correlation"; + const string body = """ + {"summary":"The error spike followed the deployment. The cause remains unconfirmed.","evidenceIds":["E-101","E-201"],"unknowns":["root-cause"],"causeStatus":"unconfirmed","cause":null} + """; + DirectoryInfo root = Directory.CreateTempSubdirectory("dotnet-eval-stage10-"); + using var generator = new ScriptedChatClient("generator", body); + using var judge = new ScriptedChatClient("judge", + "Brief review.The summary follows the incident timeline.4"); + try + { + LiveEvaluationSummary result = await LiveEvaluationRun.RunAsync( + AppContext.BaseDirectory, root.FullName, generator, "scripted-generator", judge, caseId, + responseOrigin: ResponseOrigins.HandAuthoredFixture); + + Assert.Equal(1, result.Cases); + Assert.Equal(2, result.FreshResponses); + Assert.Equal(2, generator.Calls.Count); + Assert.Equal(1, result.CacheHits); + Assert.Equal(2, judge.Calls.Count); + Assert.Equal(2, result.CoherenceEvaluations); + Assert.Equal(2, result.CoherenceScores); + Assert.Equal(ResponseOrigins.HandAuthoredFixture, result.ResponseOrigin); + Assert.All(generator.Calls, call => + { + Assert.Contains("\"requestedFactIds\"", call); + Assert.DoesNotContain("\"expectedCauseId\"", call); + Assert.DoesNotContain("\"requiredEvidenceIds\"", call); + }); + Assert.All(judge.Calls, call => Assert.Contains("The error spike followed the deployment.", call)); + + foreach ((string id, string version) in new[] { ("baseline", "v1"), ("candidate", "v2") }) + { + PromptIdentity prompt = PromptIdentity.Load( + id, version, Path.Combine(AppContext.BaseDirectory, "prompts", id + ".txt")); + ResponseFixture fixture = ResponseFixture.Load( + Path.Combine(result.OutputDirectory, "responses", id, caseId + ".json"), caseId, prompt); + Assert.Equal(ResponseOrigins.HandAuthoredFixture, fixture.Provenance.ResponseOrigin); + Assert.Equal(body, fixture.ResponseText); + } + + string reports = Path.Combine(result.OutputDirectory, "reports", "results"); + Assert.Equal(2, Directory.GetFiles(Path.Combine(reports, "hard-checks"), "*.json", SearchOption.AllDirectories).Length); + Assert.Equal(2, Directory.GetFiles(Path.Combine(reports, "coherence"), "*.json", SearchOption.AllDirectories).Length); + } + finally + { + root.Delete(recursive: true); + } + } + + private sealed class ScriptedChatClient(string name, string response) : IChatClient + { + private readonly ChatClientMetadata metadata = new(name); + public List Calls { get; } = []; + + public Task GetResponseAsync(IEnumerable messages, + ChatOptions? options = null, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + Calls.Add(string.Join("\n", messages.Select(message => message.Text))); + return Task.FromResult(new ChatResponse(new ChatMessage(ChatRole.Assistant, response))); + } + + 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() { } + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/MixedFailureCaseTests.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/MixedFailureCaseTests.cs new file mode 100644 index 0000000..1b937d5 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/MixedFailureCaseTests.cs @@ -0,0 +1,78 @@ +using Microsoft.Extensions.AI; +using Microsoft.Extensions.AI.Evaluation; +using Xunit; + +namespace EvaluationRunner.Tests; + +public sealed class MixedFailureCaseTests +{ + [Fact] + public async Task FixingCitationsDoesNotHideARegressedCauseOrPreventBlock() + { + string casePath = Path.Combine(AppContext.BaseDirectory, "cases", "incident-03-latency-and-feature-flag.json"); + IncidentCase incident = IncidentCase.Parse(await File.ReadAllTextAsync(casePath)); + IEvaluator[] evaluators = + [ + new ResponseContractEvaluator(), + new EvidenceCitationEvaluator(), + new CitationValidityEvaluator(), + new UnknownFactEvaluator(), + new CauseSupportEvaluator() + ]; + + HardCheckResult[] baseline = await EvaluateFixtureAsync("incident-03-baseline.json"); + HardCheckResult[] candidate = await EvaluateFixtureAsync("incident-03-candidate.json"); + IReadOnlyList comparisons = HardCheckComparer.Compare(baseline, candidate); + Dictionary byCheck = comparisons.ToDictionary(row => row.Key.CheckName); + + Assert.Contains(baseline, check => check.Passed is false); + Assert.Contains(candidate, check => check.Passed is false); + Assert.Equal(5, comparisons.Count); + + AssertTransition(ResponseContractEvaluator.MetricName, true, true, HardCheckTransition.UnchangedPass); + AssertTransition(CitationValidityEvaluator.MetricName, true, true, HardCheckTransition.UnchangedPass); + AssertTransition(EvidenceCitationEvaluator.MetricName, false, true, HardCheckTransition.Improvement); + AssertTransition(UnknownFactEvaluator.MetricName, true, false, HardCheckTransition.Regression); + AssertTransition(CauseSupportEvaluator.MetricName, true, false, HardCheckTransition.Regression); + + Assert.Equal(HardCheckSeverity.Noncritical, byCheck[EvidenceCitationEvaluator.MetricName].Baseline.Severity); + Assert.Contains("E-205", byCheck[EvidenceCitationEvaluator.MetricName].Baseline.Reason); + Assert.Equal(HardCheckSeverity.Critical, byCheck[CauseSupportEvaluator.MetricName].Candidate.Severity); + Assert.Contains("CAUSE-RANKING-FLAG", byCheck[CauseSupportEvaluator.MetricName].Candidate.Reason); + Assert.DoesNotContain(comparisons, row => row.Transition == HardCheckTransition.ExistingFailure); + + IEnumerable expectedChecks = evaluators.SelectMany(evaluator => evaluator.EvaluationMetricNames) + .Select(name => new HardCheckKey(incident.Id, name)); + ReleaseAssessment assessment = ReleasePolicy.Evaluate(comparisons, expectedChecks); + Assert.Equal(ReleaseDecision.Block, assessment.Decision); + Assert.Contains(assessment.Issues, issue => + issue.Key?.CheckName == CauseSupportEvaluator.MetricName && issue.Impact == ReleaseDecision.Block); + Assert.DoesNotContain(assessment.Issues, issue => issue.Key?.CheckName == EvidenceCitationEvaluator.MetricName); + + async Task EvaluateFixtureAsync(string filename) + { + string fixturePath = Path.Combine(AppContext.BaseDirectory, "examples", filename); + string json = await File.ReadAllTextAsync(fixturePath); + var response = new ChatResponse(new ChatMessage(ChatRole.Assistant, json)); + EvaluationContext[] context = [new IncidentEvaluationContext(incident)]; + var results = new List(evaluators.Length); + + foreach (IEvaluator evaluator in evaluators) + { + EvaluationResult evaluation = await evaluator.EvaluateAsync([], response, additionalContext: context); + BooleanMetric metric = evaluation.Get(evaluator.EvaluationMetricNames.Single()); + results.Add(HardCheckResult.FromMetric(incident.Id, metric)); + } + + return results.ToArray(); + } + + void AssertTransition(string check, bool before, bool after, HardCheckTransition transition) + { + HardCheckComparison row = byCheck[check]; + Assert.Equal(before, row.Baseline.Passed); + Assert.Equal(after, row.Candidate.Passed); + Assert.Equal(transition, row.Transition); + } + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/OfflineReplayTests.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/OfflineReplayTests.cs new file mode 100644 index 0000000..6dec6cd --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/OfflineReplayTests.cs @@ -0,0 +1,180 @@ +using System.Text; +using Xunit; + +namespace EvaluationRunner.Tests; + +public sealed class OfflineReplayTests +{ + [Fact] + public async Task AllTwelveCasesReproduceTheBlockedCandidateAndCanonicalScorecard() + { + string root = AppContext.BaseDirectory; + OfflineReplayResult replay = await RunAsync(root); + + Assert.Equal(ReleaseDecision.Block, replay.Assessment.Decision); + Assert.Equal(60, replay.Comparisons.Count); + Assert.Equal(12, replay.Comparisons.Select(row => row.Key.CaseId).Distinct().Count()); + Assert.Equal(24, replay.Provenance.Count); + Assert.All(replay.Provenance, item => Assert.Equal(ResponseOrigins.HandAuthoredFixture, item.ResponseOrigin)); + Assert.All(replay.Provenance.GroupBy(item => item.PromptId), group => Assert.Equal(12, group.Count())); + + var expectedChanges = new Dictionary<(string CaseNumber, string Check), HardCheckTransition> + { + [("01", CauseSupportEvaluator.MetricName)] = HardCheckTransition.Regression, + [("01", UnknownFactEvaluator.MetricName)] = HardCheckTransition.Regression, + [("03", CauseSupportEvaluator.MetricName)] = HardCheckTransition.Regression, + [("03", UnknownFactEvaluator.MetricName)] = HardCheckTransition.Regression, + [("03", EvidenceCitationEvaluator.MetricName)] = HardCheckTransition.Improvement, + [("07", EvidenceCitationEvaluator.MetricName)] = HardCheckTransition.ExistingFailure, + [("11", EvidenceCitationEvaluator.MetricName)] = HardCheckTransition.Improvement + }; + + foreach (HardCheckComparison row in replay.Comparisons) + { + var key = (row.Key.CaseId.Split('-')[1], row.Key.CheckName); + Assert.Equal(expectedChanges.GetValueOrDefault(key, HardCheckTransition.UnchangedPass), row.Transition); + expectedChanges.Remove(key); + } + + Assert.Empty(expectedChanges); + Assert.Equal(4, replay.Assessment.Issues.Count(issue => issue.Impact == ReleaseDecision.Block)); + Assert.Single(replay.Assessment.Issues, issue => issue.Impact == ReleaseDecision.Review); + byte[] approved = await File.ReadAllBytesAsync(Path.Combine(root, "reports", "candidate-scorecard.md")); + Assert.Equal(approved, Encoding.UTF8.GetBytes(ReplayScorecard.Render(replay))); + } + + [Theory] + [InlineData("missing", "Missing: [incident-01")] + [InlineData("extra", "Unexpected: [surplus]")] + [InlineData("stale", "Stale fixture")] + [InlineData("wrong-case", "Fixture belongs to case")] + public async Task InvalidFixtureSetsCannotProduceAScorecard(string change, string errorText) + { + DirectoryInfo copy = Directory.CreateTempSubdirectory("dotnet-eval-stage8-"); + try + { + CopyData(AppContext.BaseDirectory, copy.FullName); + string candidate = Path.Combine(copy.FullName, "responses", "candidate"); + string firstCase = Path.Combine(candidate, "incident-01-temporal-correlation.json"); + switch (change) + { + case "missing": + File.Delete(firstCase); + break; + case "extra": + File.Copy(firstCase, Path.Combine(candidate, "surplus.json")); + break; + case "stale": + await File.AppendAllTextAsync(Path.Combine(copy.FullName, "prompts", "candidate.txt"), "\n"); + break; + case "wrong-case": + File.Copy(Path.Combine(candidate, "incident-02-queue-and-scheduled-export.json"), firstCase, overwrite: true); + break; + } + + InvalidDataException error = await Assert.ThrowsAsync(() => RunAsync(copy.FullName)); + Assert.Contains(errorText, error.Message); + } + finally + { + copy.Delete(recursive: true); + } + } + + [Fact] + public async Task RepairedFixtureReplayPassesAllSixtyChecksAgainstTheOriginalBaseline() + { + string root = AppContext.BaseDirectory; + PromptIdentity baseline = LoadPrompt(root, "baseline", "v1"); + PromptIdentity repaired = LoadPrompt(root, "repaired", "v3"); + OfflineReplayResult replay = await OfflineReplay.RunAsync(root, baseline, repaired); + + Assert.Equal("baseline", replay.BaselinePrompt.Id); + Assert.Equal("repaired", replay.CandidatePrompt.Id); + Assert.Equal(ReleaseDecision.Ship, replay.Assessment.Decision); + Assert.Empty(replay.Assessment.Issues); + Assert.Equal(60, replay.Comparisons.Count); + Assert.Equal(12, replay.Comparisons.Select(row => row.Key.CaseId).Distinct().Count()); + Assert.All(replay.Comparisons, row => Assert.True(row.Candidate.Passed)); + Assert.Equal(57, replay.Comparisons.Count(row => row.Transition == HardCheckTransition.UnchangedPass)); + Assert.All(replay.Comparisons.Where(row => row.Transition == HardCheckTransition.Improvement), + row => Assert.Equal(EvidenceCitationEvaluator.MetricName, row.Key.CheckName)); + Assert.Equal(3, replay.Comparisons.Count(row => row.Transition == HardCheckTransition.Improvement)); + + Assert.Equal(24, replay.Provenance.Count); + Assert.Equal(12, replay.Provenance.Count(item => item.PromptId == "repaired" + && item.PromptHash == repaired.Hash && item.ResponseOrigin == ResponseOrigins.HandAuthoredFixture)); + byte[] canonical = await File.ReadAllBytesAsync(Path.Combine(root, "reports", "repaired-scorecard.md")); + Assert.Equal(canonical, Encoding.UTF8.GetBytes(ReplayScorecard.Render(replay))); + } + + [Fact] + public async Task SingleCaseDiagnosticComparesCandidateWithRepairWithoutIssuingAReleaseDecision() + { + const string caseId = "incident-01-temporal-correlation"; + string root = AppContext.BaseDirectory; + OfflineCaseReplayResult diagnostic = await OfflineReplay.RunCaseAsync( + root, caseId, LoadPrompt(root, "candidate", "v2"), LoadPrompt(root, "repaired", "v3")); + + Assert.Equal(5, diagnostic.Comparisons.Count); + Assert.All(diagnostic.Comparisons, row => + { + Assert.Equal(caseId, row.Key.CaseId); + Assert.True(row.Candidate.Passed); + }); + string[] improved = diagnostic.Comparisons.Where(row => row.Transition == HardCheckTransition.Improvement) + .Select(row => row.Key.CheckName).ToArray(); + Assert.Equal([CauseSupportEvaluator.MetricName, UnknownFactEvaluator.MetricName], improved); + string rendered = ReplayScorecard.Render(diagnostic); + Assert.Contains("full 12-case replay against the original baseline", rendered); + Assert.DoesNotContain("Release decision:", rendered); + } + + [Fact] + public async Task APassingDiagnosticCannotReplaceMissingRepairedResponses() + { + DirectoryInfo copy = Directory.CreateTempSubdirectory("dotnet-eval-stage9-"); + try + { + CopyData(AppContext.BaseDirectory, copy.FullName); + const string missing = "incident-12-confirmed-config-mismatch"; + File.Delete(Path.Combine(copy.FullName, "responses", "repaired", missing + ".json")); + PromptIdentity repaired = LoadPrompt(copy.FullName, "repaired", "v3"); + + OfflineCaseReplayResult diagnostic = await OfflineReplay.RunCaseAsync( + copy.FullName, "incident-01-temporal-correlation", LoadPrompt(copy.FullName, "candidate", "v2"), repaired); + Assert.All(diagnostic.Comparisons, row => Assert.True(row.Candidate.Passed)); + + InvalidDataException error = await Assert.ThrowsAsync(() => + OfflineReplay.RunAsync(copy.FullName, LoadPrompt(copy.FullName, "baseline", "v1"), repaired)); + Assert.Contains($"Missing: [{missing}]", error.Message); + } + finally + { + copy.Delete(recursive: true); + } + } + + private static PromptIdentity LoadPrompt(string root, string id, string version) => + PromptIdentity.Load(id, version, Path.Combine(root, "prompts", id + ".txt")); + + private static Task RunAsync(string root) + { + PromptIdentity baseline = LoadPrompt(root, "baseline", "v1"); + PromptIdentity candidate = LoadPrompt(root, "candidate", "v2"); + return OfflineReplay.RunAsync(root, baseline, candidate); + } + + private static void CopyData(string source, string target) + { + foreach (string directory in new[] { "cases", "prompts", "responses" }) + { + foreach (string file in Directory.EnumerateFiles(Path.Combine(source, directory), "*", SearchOption.AllDirectories)) + { + string destination = Path.Combine(target, Path.GetRelativePath(source, file)); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + File.Copy(file, destination); + } + } + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/ReleasePolicyTests.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/ReleasePolicyTests.cs new file mode 100644 index 0000000..df9ba19 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/ReleasePolicyTests.cs @@ -0,0 +1,130 @@ +using Microsoft.Extensions.AI.Evaluation; +using Xunit; + +namespace EvaluationRunner.Tests; + +public sealed class ReleasePolicyTests +{ + private static readonly HardCheckKey Citation = new("incident-03", EvidenceCitationEvaluator.MetricName); + private static readonly HardCheckKey Cause = new("incident-03", CauseSupportEvaluator.MetricName); + + [Theory] + [InlineData(true, true, false, ReleaseDecision.Ship)] + [InlineData(false, true, false, ReleaseDecision.Ship)] + [InlineData(true, false, false, ReleaseDecision.Block)] + [InlineData(true, false, true, ReleaseDecision.Block)] + [InlineData(false, false, true, ReleaseDecision.Block)] + [InlineData(false, false, false, ReleaseDecision.Review)] + [InlineData(null, true, false, ReleaseDecision.Ship)] + [InlineData(null, false, true, ReleaseDecision.Block)] + [InlineData(null, false, false, ReleaseDecision.Review)] + [InlineData(true, null, false, ReleaseDecision.Review)] + [InlineData(null, null, false, ReleaseDecision.Review)] + public void PolicyAppliesToIndividualHardChecks( + bool? baseline, bool? candidate, bool criticalCandidateFailure, ReleaseDecision expected) + { + HardCheckComparison row = Compare(Cause, baseline, candidate, criticalCandidateFailure); + ReleaseAssessment assessment = ReleasePolicy.Evaluate([row], [Cause]); + + Assert.Equal(expected, assessment.Decision); + if (expected == ReleaseDecision.Ship) + { + Assert.Empty(assessment.Issues); + return; + } + + ReleaseIssue issue = Assert.Single(assessment.Issues); + Assert.Equal(Cause, issue.Key); + Assert.Equal(expected, issue.Impact); + Assert.False(string.IsNullOrWhiteSpace(issue.Reason)); + } + + [Fact] + public void OptionalQualityConcernCanRequireReviewAfterAllHardChecksPass() + { + const string concern = "The reviewer flagged a material coherence drop."; + HardCheckComparison row = Compare(Citation, true, true); + ReleaseAssessment assessment = ReleasePolicy.Evaluate([row], [Citation], concern); + + Assert.Equal(ReleaseDecision.Review, assessment.Decision); + ReleaseIssue issue = Assert.Single(assessment.Issues); + Assert.Null(issue.Key); + Assert.Equal(concern, issue.Reason); + } + + [Fact] + public void BlockTakesPrecedenceOverBothHardCheckAndQualityReview() + { + HardCheckComparison existingFailure = Compare(Citation, false, false); + HardCheckComparison regression = Compare(Cause, true, false); + + ReleaseAssessment assessment = ReleasePolicy.Evaluate( + [existingFailure, regression], [Citation, Cause], "Review the coherence score."); + + Assert.Equal(ReleaseDecision.Block, assessment.Decision); + Assert.Contains(assessment.Issues, issue => issue.Key == Cause && issue.Impact == ReleaseDecision.Block); + Assert.Contains(assessment.Issues, issue => issue.Key == Citation && issue.Impact == ReleaseDecision.Review); + Assert.Contains(assessment.Issues, issue => issue.Key is null && issue.Impact == ReleaseDecision.Review); + } + + [Fact] + public void MissingExpectedResultPreventsShip() + { + ReleaseAssessment assessment = ReleasePolicy.Evaluate([Compare(Citation, true, true)], [Citation, Cause]); + + Assert.Equal(ReleaseDecision.Review, assessment.Decision); + ReleaseIssue issue = Assert.Single(assessment.Issues); + Assert.Equal(Cause, issue.Key); + Assert.Contains("missing", issue.Reason); + } + + [Fact] + public void KnownBlockStillTakesPrecedenceWithIncompleteCoverage() + { + ReleaseAssessment assessment = ReleasePolicy.Evaluate([Compare(Cause, true, false)], [Citation, Cause]); + + Assert.Equal(ReleaseDecision.Block, assessment.Decision); + Assert.Contains(assessment.Issues, issue => issue.Key == Citation && issue.Impact == ReleaseDecision.Review); + } + + [Fact] + public void EmptyResultsRequireReviewWhenChecksAreExpected() + { + ReleaseAssessment assessment = ReleasePolicy.Evaluate([], [Citation]); + + Assert.Equal(ReleaseDecision.Review, assessment.Decision); + Assert.Equal(Citation, Assert.Single(assessment.Issues).Key); + } + + [Fact] + public void EmptyOrDuplicatedExpectedKeysAreRejected() + { + Assert.Throws(() => ReleasePolicy.Evaluate([], [])); + Assert.Throws(() => ReleasePolicy.Evaluate([], [Citation, Citation])); + } + + [Fact] + public void UnexpectedOrDuplicatedResultRowsAreRejected() + { + HardCheckComparison row = Compare(Citation, true, true); + Assert.Throws(() => ReleasePolicy.Evaluate([row], [Cause])); + Assert.Throws(() => ReleasePolicy.Evaluate([row, row], [Citation])); + } + + private static HardCheckComparison Compare( + HardCheckKey key, bool? baseline, bool? candidate, bool criticalCandidateFailure = false) + { + HardCheckResult previous = ReadMetric(baseline, critical: false); + HardCheckResult proposed = ReadMetric(candidate, criticalCandidateFailure); + return Assert.Single(HardCheckComparer.Compare([previous], [proposed])); + + HardCheckResult ReadMetric(bool? passed, bool critical) + { + var metric = new BooleanMetric(key.CheckName, passed); + if (passed is false) + metric.AddOrUpdateMetadata(IncidentHardEvaluator.SeverityMetadataKey, critical ? "critical" : "noncritical"); + + return HardCheckResult.FromMetric(key.CaseId, metric); + } + } +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/ResponseFixtureTests.cs b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/ResponseFixtureTests.cs new file mode 100644 index 0000000..06a7899 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/tests/EvaluationRunner.Tests/ResponseFixtureTests.cs @@ -0,0 +1,159 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.AI.Evaluation; +using Xunit; + +namespace EvaluationRunner.Tests; + +public sealed class ResponseFixtureTests +{ + private const string CaseId = "incident-01-temporal-correlation"; + private const string PromptText = "abc"; + private static readonly DateTimeOffset CreatedAt = new(2026, 11, 29, 12, 0, 0, TimeSpan.Zero); + private static readonly PromptIdentity Prompt = PromptIdentity.FromText("candidate", "v2", PromptText); + + [Fact] + public void HashIsLowercaseSha256OfTheExactUtf8Text() + { + Assert.Equal("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", Prompt.Hash); + Assert.NotEqual(Prompt.Hash, PromptIdentity.FromText(Prompt.Id, Prompt.Version, PromptText + "\n").Hash); + } + + [Fact] + public async Task PackagedFixtureLoadsAndItsRawResponseReachesTheEvaluator() + { + string sample = Path.Combine(AppContext.BaseDirectory, "examples", "provenance"); + PromptIdentity expected = PromptIdentity.Load("provenance-demo", "v1", Path.Combine(sample, "prompt.txt")); + ResponseFixture fixture = ResponseFixture.Load(Path.Combine(sample, "incident-01-fixture.json"), CaseId, expected); + Assert.Equal(ResponseOrigins.HandAuthoredFixture, fixture.Provenance.ResponseOrigin); + Assert.Equal(expected.Hash, fixture.Provenance.PromptHash); + Assert.Equal(expected.Id, fixture.Provenance.PromptId); + Assert.Equal(expected.Version, fixture.Provenance.PromptVersion); + Assert.Equal(CaseId, fixture.Provenance.CaseId); + + IncidentCase incident = IncidentCase.Parse(await File.ReadAllTextAsync( + Path.Combine(AppContext.BaseDirectory, "cases", CaseId + ".json"))); + IEvaluator evaluator = new CauseSupportEvaluator(); + var response = new ChatResponse(new ChatMessage(ChatRole.Assistant, fixture.ResponseText)); + EvaluationResult result = await evaluator.EvaluateAsync( + [], response, additionalContext: [new IncidentEvaluationContext(incident)]); + Assert.True(result.Get(CauseSupportEvaluator.MetricName).Value); + } + + [Theory] + [InlineData("not even JSON")] + [InlineData("")] + [InlineData("\r\n")] + public void RawResponseIsPreservedEvenWhenTheResponseContractWouldFail(string body) + { + ResponseFixture original = ResponseFixture.Create( + CaseId, Prompt, body, ResponseOrigins.HandAuthoredFixture, CreatedAt); + ResponseFixture parsed = ResponseFixture.Parse(original.ToJson(), CaseId, Prompt); + + Assert.Equal(body, parsed.ResponseText); + Assert.Equal(CreatedAt, parsed.Provenance.CreatedAt); + Assert.Null(parsed.Provenance.Model); + Assert.Null(parsed.Provenance.GenerationSettings); + } + + [Fact] + public void CapturedFixtureRoundTripsModelAndSettingsAfterTheOriginalJsonIsDisposed() + { + ResponseFixture original; + using (JsonDocument document = JsonDocument.Parse("""{"temperature":0.2,"maxOutputTokens":400}""")) + { + original = ResponseFixture.Create(CaseId, Prompt, "sample body", + ResponseOrigins.CapturedLive, CreatedAt, "example-model", document.RootElement); + } + + ResponseFixture parsed = ResponseFixture.Parse(original.ToJson(), CaseId, Prompt); + Assert.Equal(ResponseOrigins.CapturedLive, parsed.Provenance.ResponseOrigin); + Assert.Equal("example-model", parsed.Provenance.Model); + Assert.Equal(0.2, parsed.Provenance.GenerationSettings?.GetProperty("temperature").GetDouble()); + Assert.Equal(400, parsed.Provenance.GenerationSettings?.GetProperty("maxOutputTokens").GetInt32()); + } + + [Fact] + public void EditedPromptWithUnchangedIdAndVersionMakesFixtureStale() + { + PromptIdentity edited = PromptIdentity.FromText(Prompt.Id, Prompt.Version, PromptText + "!"); + InvalidDataException error = Assert.Throws(() => + ResponseFixture.Parse(CreateExample().ToJson(), CaseId, edited)); + Assert.Contains("Stale fixture", error.Message); + } + + [Theory] + [InlineData("baseline", "v2")] + [InlineData("candidate", "v3")] + public void DifferentPromptIdentityIsRejectedEvenIfTextMatches(string id, string version) + { + PromptIdentity other = PromptIdentity.FromText(id, version, PromptText); + Assert.Equal(Prompt.Hash, other.Hash); + + InvalidDataException error = Assert.Throws(() => + ResponseFixture.Parse(CreateExample().ToJson(), CaseId, other)); + Assert.Contains("belongs to prompt", error.Message); + } + + [Fact] + public void WrongCaseIsRejectedEvenWithTheExpectedPrompt() + { + InvalidDataException error = Assert.Throws(() => + ResponseFixture.Parse(CreateExample().ToJson(), "incident-02", Prompt)); + Assert.Contains("belongs to case", error.Message); + } + + [Theory] + [InlineData("cached")] + [InlineData("fixture")] + [InlineData("")] + public void ReplayModesAndUnknownValuesCannotBeRecordedAsOrigins(string origin) + { + Assert.Throws(() => ResponseFixture.Create(CaseId, Prompt, "body", origin, CreatedAt)); + } + + [Theory] + [InlineData(null, "{}")] + [InlineData("example-model", null)] + [InlineData("example-model", "[]")] + public void CapturedOriginRequiresModelAndObjectSettings(string? model, string? settings) + { + using JsonDocument? document = settings is null ? null : JsonDocument.Parse(settings); + Assert.Throws(() => ResponseFixture.Create( + CaseId, Prompt, "body", ResponseOrigins.CapturedLive, CreatedAt, model, document?.RootElement)); + } + + [Fact] + public void LoaderRejectsHandAuthoredFixtureClaimingAModel() + { + JsonNode document = JsonNode.Parse(CreateExample().ToJson())!; + document["provenance"]!["model"] = "example-model"; + Assert.Throws(() => ResponseFixture.Parse(document.ToJsonString(), CaseId, Prompt)); + } + + [Theory] + [InlineData("caseId")] + [InlineData("promptId")] + [InlineData("promptVersion")] + [InlineData("promptHash")] + [InlineData("responseOrigin")] + [InlineData("createdAt")] + public void RequiredMetadataCannotBeOmitted(string field) + { + JsonNode document = JsonNode.Parse(CreateExample().ToJson())!; + document["provenance"]!.AsObject().Remove(field); + Assert.Throws(() => ResponseFixture.Parse(document.ToJsonString(), CaseId, Prompt)); + } + + [Fact] + public void LoaderRejectsAnInvalidHash() + { + JsonNode document = JsonNode.Parse(CreateExample().ToJson())!; + document["provenance"]!["promptHash"] = "not-a-sha256"; + Assert.Throws(() => ResponseFixture.Parse(document.ToJsonString(), CaseId, Prompt)); + } + + private static ResponseFixture CreateExample() => ResponseFixture.Create( + CaseId, Prompt, "test body", ResponseOrigins.HandAuthoredFixture, CreatedAt); +} diff --git a/dotnet-ai/microsoft-extensions-ai-evaluation/verified-environment.json b/dotnet-ai/microsoft-extensions-ai-evaluation/verified-environment.json new file mode 100644 index 0000000..82ec667 --- /dev/null +++ b/dotnet-ai/microsoft-extensions-ai-evaluation/verified-environment.json @@ -0,0 +1,27 @@ +{ + "sdk": "10.0.404", + "targetFramework": "net10.0", + "platform": "Linux", + "evaluationPackagesVersion": "10.11.1", + "offline": { + "restore": "PASS", + "releaseBuild": "PASS", + "testsPassed": 104, + "cases": 12, + "hardChecksPerCase": 5, + "fixtureCount": 36, + "fixtureOrigin": "hand-authored-fixture", + "candidateDecision": "BLOCK", + "repairedDecision": "SHIP", + "modelCalls": 0 + }, + "optionalLive": { + "generationModel": "qwen2.5-0.5b-instruct", + "cases": 12, + "freshResponses": 24, + "cacheHits": 1, + "responseContractPasses": 5, + "htmlReport": "PASS", + "usableLiveCoherenceScoresVerified": false + } +}