mirror of
https://github.com/okieselbach/AutopilotMonitor.git
synced 2026-10-25 05:00:07 +00:00
Compare commits
95 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e33d85c01d | |||
| 4e73ba8900 | |||
| 4df52b3da9 | |||
| 844d86410c | |||
| 9514e1033d | |||
| b2236bf65f | |||
| 31535b07e0 | |||
| 066b6e6f04 | |||
| a1e2b76a9f | |||
| 29e5b8251d | |||
| 02168a5c55 | |||
| a6b6661320 | |||
| 0c72666a7a | |||
| 9023321db9 | |||
| 7ef097529c | |||
| e7df69efe4 | |||
| 2c7efa2733 | |||
| 2742549827 | |||
| 3c45f5cb09 | |||
| d5d1d7bfbd | |||
| f4e2088b69 | |||
| 55425058a8 | |||
| eec0d17607 | |||
| 43f5304ba4 | |||
| b21472dd8c | |||
| e3991d55be | |||
| 864d1ed31e | |||
| 76ef1e53ca | |||
| 7dd298f04e | |||
| 66452621c6 | |||
| 0b23d93957 | |||
| 4281a6d81b | |||
| fe919a51aa | |||
| 0dcf0eb503 | |||
| e2fb99d5d8 | |||
| a3ee613b60 | |||
| d2197c6a57 | |||
| e5997bc50e | |||
| 75138016ce | |||
| fc4772efb0 | |||
| 0bde428fa0 | |||
| 16ca3a059c | |||
| 1bfc80e6db | |||
| fa705a2ef6 | |||
| 81f807e124 | |||
| a4f7c88785 | |||
| 54259f070f | |||
| 26cef3ab06 | |||
| 00ad230ffe | |||
| 3d920a8113 | |||
| f6eac1964a | |||
| e1b5b9d163 | |||
| 094833f831 | |||
| 3579ce0add | |||
| 0188860d1c | |||
| 871a1ac059 | |||
| 298a182fbb | |||
| e71223507c | |||
| 02187f0f3c | |||
| 3e2f62daeb | |||
| c8b8a8dbb4 | |||
| 9e4c5f11c5 | |||
| b16e72c10e | |||
| 5cb9b0b30b | |||
| c925001a8a | |||
| e494334720 | |||
| 1554540431 | |||
| fef09690d2 | |||
| 3a975fa74f | |||
| 69c6353fb1 | |||
| 2b9bf3cd3f | |||
| d99e16314b | |||
| e4203e0f15 | |||
| 2a5366d9c3 | |||
| 9c9cf24ddc | |||
| ec0d8ad735 | |||
| fc9e9d13e6 | |||
| d0cb7e66f4 | |||
| bd66480ccc | |||
| b05f1f6bcf | |||
| 12ad9c9436 | |||
| c8ce7cdb37 | |||
| 56d4dd8b84 | |||
| 86fdc5aca9 | |||
| 87c5bc59dc | |||
| 21b30b21c2 | |||
| f94f1c0c4e | |||
| a6a9883451 | |||
| 03116a97d1 | |||
| 2abc78ab6d | |||
| 6e54b52376 | |||
| 7cef2ea361 | |||
| 5b5ee0e8fd | |||
| 7bcc4f00b1 | |||
| 34ec44e3d4 |
+1
-1
Submodule .claude/commands updated: 6b39d14ed0...e57da4e431
@@ -40,6 +40,23 @@ jobs:
|
||||
lfs: false
|
||||
fetch-depth: 0 # Full history needed for git-based sitemap lastmod dates
|
||||
|
||||
# The customer docs repo is the single source of the "What's new" panel: the prebuild
|
||||
# step (scripts/whats-new/build-whats-new.js) turns changelog/*.md into
|
||||
# public/whats-new.json and dates every bullet via git blame — hence the full history.
|
||||
# Public repo, no token. Editing the docs does NOT update the live panel until this
|
||||
# workflow runs again (push under src/Web/** or a manual dispatch); versions/web.json
|
||||
# records which docs commit is live.
|
||||
- name: Check out documentation bundle
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
repository: autopilotmonitor/autopilotmonitor-docs
|
||||
path: whats-new-docs
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Resolve docs commit
|
||||
id: docs
|
||||
run: echo "sha=$(git -C whats-new-docs rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '22'
|
||||
@@ -51,7 +68,7 @@ jobs:
|
||||
run: npm ci
|
||||
|
||||
# next.config output:'export' -- `next build` writes the static site to out/
|
||||
# (prebuild: sync-error-codes, generate-lastmod, generate-version).
|
||||
# (prebuild: sync-error-codes, generate-lastmod, generate-version, whats-new).
|
||||
- name: Build
|
||||
working-directory: ${{ env.WEB_DIR }}
|
||||
env:
|
||||
@@ -68,9 +85,12 @@ jobs:
|
||||
# Build stamp for public/version.json (scripts/generate-version.js in prebuild);
|
||||
# the verify step below polls the deployed file for exactly this commit.
|
||||
GITHUB_SHA: ${{ github.sha }}
|
||||
# Docs checkout for public/whats-new.json; the prebuild fails in CI without it.
|
||||
WHATS_NEW_DOCS_DIR: ${{ github.workspace }}/whats-new-docs
|
||||
run: |
|
||||
npm run build
|
||||
test -f out/version.json || { echo "out/version.json missing - export did not run"; exit 1; }
|
||||
test -f out/whats-new.json || { echo "out/whats-new.json missing - whats-new prebuild did not run"; exit 1; }
|
||||
|
||||
# One archive of the exact bytes that get uploaded, so the attestation has a single subject.
|
||||
- name: Package export
|
||||
@@ -136,7 +156,8 @@ jobs:
|
||||
throw "Portal did not serve commit $expectedCommit within 5 minutes -- deployment not verified, version manifest NOT published"
|
||||
|
||||
# Cross-component deploy record, written last and only on a verified deploy --
|
||||
# same contract as versions/backend.json and versions/mcp.json.
|
||||
# same contract as versions/backend.json and versions/mcp.json. docsCommit says which
|
||||
# docs revision the live What's new panel was generated from (as for the MCP corpus).
|
||||
- name: Publish version manifest
|
||||
shell: pwsh
|
||||
run: |
|
||||
@@ -145,6 +166,7 @@ jobs:
|
||||
commit = '${{ github.sha }}'.Substring(0, 7)
|
||||
deployedUtc = [DateTime]::UtcNow.ToString('o')
|
||||
runId = '${{ github.run_id }}'
|
||||
docsCommit = '${{ steps.docs.outputs.sha }}'.Substring(0, 7)
|
||||
} | ConvertTo-Json
|
||||
|
||||
$sas = '${{ secrets.AZURE_BLOB_VERSIONS_SAS_TOKEN }}'.TrimStart('?')
|
||||
|
||||
@@ -145,6 +145,10 @@ internal/docs/~$Introduction-AutopilotMonitor.pptx
|
||||
# changes each run) and served at /version.json from the static export.
|
||||
src/Web/autopilot-monitor-web/public/version.json
|
||||
|
||||
# What's new payload: generated by scripts/whats-new/build-whats-new.js from the docs
|
||||
# checkout on every build and served at /whats-new.json from the static export.
|
||||
src/Web/autopilot-monitor-web/public/whats-new.json
|
||||
|
||||
|
||||
# Local IME installer scratch (MSI + extracted payload per version, for grepping
|
||||
# in binaries). Operator-only, never committed.
|
||||
|
||||
@@ -1,33 +1,63 @@
|
||||
# <img src=".github/assets/logo.svg" height="28" alt="" /> Autopilot Monitor
|
||||
# <img src=".github/assets/logo.svg" height="28" alt="Autopilot Monitor logo" /> Autopilot Monitor
|
||||
|
||||
[](https://www.autopilotmonitor.com)
|
||||
[](LICENSE)
|
||||
[](https://www.autopilotmonitor.com)
|
||||
|
||||
Advanced monitoring and troubleshooting solution for Windows Autopilot deployments. Gain full visibility into every enrollment session with a detailed event timeline, fleet health dashboards, and session reporting. Define custom analysis rules to automatically detect issues and gather rules to collect targeted evidence. Retrieve diagnostics packages on demand, configure agent settings like auto-reboot behavior and automatic timezone adjustment — all managed centrally from the web dashboard.
|
||||
Autopilot Monitor is an open-source, real-time monitoring and troubleshooting platform for **Windows Autopilot** and **Microsoft Intune** enrollment. It records enrollment events, application installations, policies, device state, and diagnostics while provisioning is still running, instead of collecting logs by hand after a failure. Administrators get live enrollment tracking, Enrollment Status Page (ESP) visibility, detailed session timelines, automated issue detection, on-demand diagnostics, fleet health analytics, and AI-assisted troubleshooting through a hosted Model Context Protocol (MCP) server.
|
||||
|
||||
The platform supports classic Windows Autopilot and modern Intune provisioning scenarios, including **Windows Autopilot Device Preparation**.
|
||||
|
||||
## Availability
|
||||
|
||||
Autopilot Monitor is **publicly available** — the Community plan is free. Sign in with your work account at **[autopilotmonitor.com](https://www.autopilotmonitor.com)**; new organizations complete a short activation step after first sign-in.
|
||||
|
||||
<p align="center">
|
||||
<img src=".github/assets/SessionList.png" width="45%" />
|
||||
<img src=".github/assets/FleetHealth.png" width="45%" />
|
||||
<img src=".github/assets/SessionList.png" width="45%" alt="Autopilot Monitor dashboard showing live Windows Autopilot and Intune enrollment sessions" />
|
||||
<img src=".github/assets/FleetHealth.png" width="45%" alt="Autopilot Monitor fleet health dashboard with Windows Autopilot enrollment analytics and success metrics" />
|
||||
</p>
|
||||
<p align="center">
|
||||
<img src=".github/assets/SessionDetails.png" width="45%" />
|
||||
<img src=".github/assets/SessionTimeline.png" width="45%" />
|
||||
<img src=".github/assets/SessionDetails.png" width="45%" alt="Autopilot Monitor session details showing device information, diagnostics, apps, policies, and enrollment status" />
|
||||
<img src=".github/assets/SessionTimeline.png" width="45%" alt="Windows Autopilot enrollment timeline showing ESP phases, application installs, policies, events, and errors" />
|
||||
</p>
|
||||
|
||||
## Overview
|
||||
## Key Features
|
||||
|
||||
Autopilot Monitor provides real-time tracking, intelligent diagnostics, and automated troubleshooting for Windows Autopilot enrollment processes. It consists of:
|
||||
- **Real-time Windows Autopilot monitoring** — follow device provisioning while enrollment is still running
|
||||
- **Detailed enrollment timelines** — correlate Autopilot, ESP, Intune Management Extension, apps, policies, device state, and system events
|
||||
- **Enrollment Status Page visibility** — see which phase, application, or policy is delaying provisioning
|
||||
- **Automated issue detection** — define custom analysis rules that identify known failure patterns
|
||||
- **Targeted evidence collection** — gather registry values, event log entries, files, log-parser matches, and allow-listed commands when specific conditions are detected
|
||||
- **On-demand diagnostics** — request diagnostics packages from enrolled devices remotely
|
||||
- **Fleet health analytics** — success rates, deployment duration, device models, applications, errors, and recurring issues
|
||||
- **Session reporting** — inspect and share detailed enrollment information for individual devices
|
||||
- **Windows Autopilot Device Preparation support** — monitor Device Preparation deployments alongside classic Autopilot scenarios
|
||||
- **Centralized agent configuration** — control diagnostic behavior, automatic reboots, timezone adjustment, and other monitoring settings from the web dashboard
|
||||
- **AI-assisted troubleshooting** — query enrollment data through the built-in Model Context Protocol server
|
||||
|
||||
- **Bootstrap Script** — PowerShell script deployed via Intune that starts monitoring early in the enrollment process
|
||||
- **Monitoring Agent** — Lightweight .NET application that collects telemetry and evidence during enrollment
|
||||
## How it works
|
||||
|
||||
Autopilot Monitor consists of several components working together throughout Windows enrollment:
|
||||
|
||||
- **Bootstrap Script** — PowerShell script deployed through Microsoft Intune that starts monitoring early in the provisioning process
|
||||
- **Monitoring Agent** — lightweight .NET application that collects telemetry and evidence during enrollment
|
||||
- **Backend API** — Azure Functions-based ingestion and processing pipeline
|
||||
- **Web Dashboard** — Next.js application for real-time monitoring and fleet analytics
|
||||
- **MCP Server** — Model Context Protocol server that lets AI assistants query and troubleshoot enrollments in natural language
|
||||
- **Web Dashboard** — Next.js application for real-time monitoring, troubleshooting, and fleet analytics
|
||||
- **MCP Server** — Model Context Protocol server that lets AI assistants query Autopilot Monitor data in natural language
|
||||
|
||||
## Windows Autopilot and Intune Troubleshooting
|
||||
|
||||
Autopilot Monitor helps investigate common Windows provisioning and enrollment problems such as:
|
||||
|
||||
- Windows Autopilot deployments that fail or appear stuck
|
||||
- Enrollment Status Page (ESP) delays and unusually long deployment phases
|
||||
- Win32 application installation failures and slow application downloads
|
||||
- Intune Management Extension problems
|
||||
- Microsoft Entra join, Hybrid Join, and device registration issues
|
||||
- policies that block or delay provisioning
|
||||
- inconsistent behavior across hardware models and recurring failures affecting multiple devices
|
||||
|
||||
Because telemetry is collected during enrollment, many problems can be investigated without reproducing the issue or manually collecting logs from the affected device.
|
||||
|
||||
## AI Integration (MCP)
|
||||
|
||||
@@ -35,13 +65,19 @@ Autopilot Monitor ships a hosted **[Model Context Protocol](https://modelcontext
|
||||
|
||||
- *"Show me all failed enrollments from the last 24 hours and group them by failure reason."*
|
||||
- *"Why did session X fail, and which app install caused the delay?"*
|
||||
- *"Which devices had unusually long ESP application phases this week?"*
|
||||
- *"Which device models have the highest Autopilot failure rate?"*
|
||||
- *"Which devices in my fleet are affected by CVE-2024-30078?"*
|
||||
|
||||
Server URL: `https://mcp.autopilotmonitor.com/mcp` — sign-in runs through your existing work account, access is scoped to your tenant exactly like in the portal, and no credentials are stored. Setup guide: **[AI Integration (MCP)](https://docs.autopilotmonitor.com/integrations/ai-integration-mcp)**.
|
||||
Server URL: `https://mcp.autopilotmonitor.com/mcp` — sign-in runs through your existing work account, access is scoped to your tenant exactly like in the portal, and the MCP server stores no credentials. Setup guide: **[AI Integration (MCP)](https://docs.autopilotmonitor.com/integrations/ai-integration-mcp)**.
|
||||
|
||||
## Documentation
|
||||
|
||||
Full admin documentation is available at **[docs.autopilotmonitor.com](https://docs.autopilotmonitor.com)**
|
||||
Full admin documentation is available at **[docs.autopilotmonitor.com](https://docs.autopilotmonitor.com)** — deployment, configuration, monitoring, diagnostics, troubleshooting, analysis and gather rules, integrations, and AI-assisted troubleshooting.
|
||||
|
||||
## Open Source
|
||||
|
||||
Autopilot Monitor is developed openly on GitHub. The source is published so that customers and security reviewers can see what runs on their devices and with their data: the repository contains the device agent, shared library, backend, web dashboard, and MCP server.
|
||||
|
||||
## Feedback
|
||||
|
||||
|
||||
+1
-1
Submodule internal updated: 9f75da246a...41d3f15126
@@ -5,7 +5,7 @@
|
||||
"description": "Detects when the Enrollment Status Page failed on the Apps subcategory and the agent's AppX deployment log scan identified a suspected MSIX/Store package. Store/MSIX apps install outside the Win32 pipeline, so the regular per-app tracking sees nothing — this correlation names the likely culprit.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
@@ -93,7 +93,7 @@
|
||||
"steps": [
|
||||
"Open Event Viewer → Applications and Services Logs → Microsoft → Windows → AppXDeploymentServer → Operational on the device (or in the diagnostics archive if uploaded)",
|
||||
"Filter for Error-level events around the ESP failure time and confirm the package name and HRESULT match this finding",
|
||||
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = invalid/corrupt package, 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
|
||||
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = package could not be opened (unsigned, publisher mismatch, or not found), 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"$schema": "../schema/analyze-rule.schema.json",
|
||||
"ruleId": "ANALYZE-APP-018",
|
||||
"title": "App Return Code Requested a Reboot During Enrollment",
|
||||
"description": "Detects Win32 apps whose installer exit code maps to Soft reboot or Hard reboot in the app's Intune return-code table (the '[Win32App] lpExitCode is defined as ...' line). Hard reboot stops app processing and restarts the device in Device Setup - the mid-enrollment restart and second sign-in; Soft reboot leaves the app pending until the next restart while the ESP moves on. Confidence rises for Hard reboot and when a reboot was actually observed in the session.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
"whiteglove_sealed"
|
||||
],
|
||||
"trigger": "single",
|
||||
"baseConfidence": 60,
|
||||
"conditions": [
|
||||
{
|
||||
"signal": "reboot_return_code",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_completed",
|
||||
"dataField": "exitCodeClass",
|
||||
"operator": "in",
|
||||
"value": "SoftReboot,HardReboot",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "hard_reboot_return_code",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_completed",
|
||||
"dataField": "exitCodeClass",
|
||||
"operator": "equals",
|
||||
"value": "HardReboot",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"signal": "reboot_observed",
|
||||
"source": "event_count",
|
||||
"eventType": "system_reboot_detected",
|
||||
"operator": "count_gte",
|
||||
"value": "1",
|
||||
"required": false
|
||||
}
|
||||
],
|
||||
"confidenceFactors": [
|
||||
{
|
||||
"signal": "hard_reboot_return_code",
|
||||
"condition": "exists",
|
||||
"weight": 25
|
||||
},
|
||||
{
|
||||
"signal": "reboot_observed",
|
||||
"condition": "exists",
|
||||
"weight": 15
|
||||
}
|
||||
],
|
||||
"confidenceThreshold": 60,
|
||||
"explanation": "App **{{appName}}** returned exit code **{{exitCode}}**, which its Intune return-code table maps to **{{exitCodeClass}}** - the installer asked for a restart before its work is complete.\n\n- **SoftReboot**: the Intune Management Extension reports the app as *pending reboot*. The Enrollment Status Page treats it as completed and moves on, and Intune only marks the app installed after the next restart re-evaluates the detection rule. Until then the app may be unusable or half-configured, and the user sees a restart notification.\n- **HardReboot**: the Intune Management Extension stops processing further apps and, in Device Setup, restarts the device right away (the restart grace period does not apply during the ESP) - the same mid-enrollment restart and second sign-in that ANALYZE-ESP-005 attributes to reboot-required policies. In Account Setup the extension does not restart the device itself and the app stays pending.\n\nA restart requested by an installer is normal for many MSI packages (exit codes 3010 and 1641), but during Autopilot it lengthens the ESP, can surprise the user with a restart, and hides the app's real state until after the reboot. The return-code class is the app's own configuration in Intune, not a device fault.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Check the app's return-code mapping",
|
||||
"steps": [
|
||||
"Open the app in the Intune admin center > Properties > Program and review the return codes table: exit code {{exitCode}} is currently mapped to {{exitCodeClass}}",
|
||||
"If the installer only recommends a restart (MSI 3010 ERROR_SUCCESS_REBOOT_REQUIRED, 1641 ERROR_SUCCESS_REBOOT_INITIATED), map the code to Soft reboot instead of Hard reboot so the next app can install before the restart",
|
||||
"If the app works without an immediate restart, suppress the installer's own reboot (for MSI: REBOOT=ReallySuppress on the install command) so it returns 0 and the restart happens on your schedule",
|
||||
"Keep Hard reboot only when the following apps genuinely cannot install before the restart - and then expect the mid-ESP restart in every enrollment"
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "Take the app out of the ESP critical path",
|
||||
"steps": [
|
||||
"If the app is not needed for first use, remove it from the ESP blocking-app list so the restart happens after the user reaches the desktop",
|
||||
"If it must stay blocking, order it last in Device Setup (dependencies or install order) so a hard reboot does not interrupt the remaining apps",
|
||||
"For Soft reboot apps, plan a restart at the end of enrollment or accept that the app finishes on the user's first restart"
|
||||
]
|
||||
}
|
||||
],
|
||||
"relatedDocs": [
|
||||
{
|
||||
"title": "Microsoft Learn: Add a Win32 app - Program step (device restart behavior and return codes)",
|
||||
"url": "https://learn.microsoft.com/en-us/intune/app-management/deployment/add-win32#step-2-program"
|
||||
},
|
||||
{
|
||||
"title": "Microsoft Learn: Enrollment Status Page tracking",
|
||||
"url": "https://learn.microsoft.com/en-us/autopilot/enrollment-status"
|
||||
}
|
||||
],
|
||||
"markSessionAsFailedDefault": false,
|
||||
"tags": [
|
||||
"apps",
|
||||
"reboot",
|
||||
"return-code",
|
||||
"soft-reboot",
|
||||
"hard-reboot",
|
||||
"esp",
|
||||
"second-sign-in"
|
||||
]
|
||||
}
|
||||
+99
-2
@@ -615,7 +615,7 @@
|
||||
"description": "Detects when the Enrollment Status Page failed on the Apps subcategory and the agent's AppX deployment log scan identified a suspected MSIX/Store package. Store/MSIX apps install outside the Win32 pipeline, so the regular per-app tracking sees nothing — this correlation names the likely culprit.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
@@ -703,7 +703,7 @@
|
||||
"steps": [
|
||||
"Open Event Viewer → Applications and Services Logs → Microsoft → Windows → AppXDeploymentServer → Operational on the device (or in the diagnostics archive if uploaded)",
|
||||
"Filter for Error-level events around the ESP failure time and confirm the package name and HRESULT match this finding",
|
||||
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = invalid/corrupt package, 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
|
||||
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = package could not be opened (unsigned, publisher mismatch, or not found), 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -1034,6 +1034,103 @@
|
||||
"esp"
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "ANALYZE-APP-018",
|
||||
"title": "App Return Code Requested a Reboot During Enrollment",
|
||||
"description": "Detects Win32 apps whose installer exit code maps to Soft reboot or Hard reboot in the app's Intune return-code table (the '[Win32App] lpExitCode is defined as ...' line). Hard reboot stops app processing and restarts the device in Device Setup - the mid-enrollment restart and second sign-in; Soft reboot leaves the app pending until the next restart while the ESP moves on. Confidence rises for Hard reboot and when a reboot was actually observed in the session.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
"whiteglove_sealed"
|
||||
],
|
||||
"trigger": "single",
|
||||
"baseConfidence": 60,
|
||||
"conditions": [
|
||||
{
|
||||
"signal": "reboot_return_code",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_completed",
|
||||
"dataField": "exitCodeClass",
|
||||
"operator": "in",
|
||||
"value": "SoftReboot,HardReboot",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "hard_reboot_return_code",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_completed",
|
||||
"dataField": "exitCodeClass",
|
||||
"operator": "equals",
|
||||
"value": "HardReboot",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"signal": "reboot_observed",
|
||||
"source": "event_count",
|
||||
"eventType": "system_reboot_detected",
|
||||
"operator": "count_gte",
|
||||
"value": "1",
|
||||
"required": false
|
||||
}
|
||||
],
|
||||
"confidenceFactors": [
|
||||
{
|
||||
"signal": "hard_reboot_return_code",
|
||||
"condition": "exists",
|
||||
"weight": 25
|
||||
},
|
||||
{
|
||||
"signal": "reboot_observed",
|
||||
"condition": "exists",
|
||||
"weight": 15
|
||||
}
|
||||
],
|
||||
"confidenceThreshold": 60,
|
||||
"explanation": "App **{{appName}}** returned exit code **{{exitCode}}**, which its Intune return-code table maps to **{{exitCodeClass}}** - the installer asked for a restart before its work is complete.\n\n- **SoftReboot**: the Intune Management Extension reports the app as *pending reboot*. The Enrollment Status Page treats it as completed and moves on, and Intune only marks the app installed after the next restart re-evaluates the detection rule. Until then the app may be unusable or half-configured, and the user sees a restart notification.\n- **HardReboot**: the Intune Management Extension stops processing further apps and, in Device Setup, restarts the device right away (the restart grace period does not apply during the ESP) - the same mid-enrollment restart and second sign-in that ANALYZE-ESP-005 attributes to reboot-required policies. In Account Setup the extension does not restart the device itself and the app stays pending.\n\nA restart requested by an installer is normal for many MSI packages (exit codes 3010 and 1641), but during Autopilot it lengthens the ESP, can surprise the user with a restart, and hides the app's real state until after the reboot. The return-code class is the app's own configuration in Intune, not a device fault.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Check the app's return-code mapping",
|
||||
"steps": [
|
||||
"Open the app in the Intune admin center > Properties > Program and review the return codes table: exit code {{exitCode}} is currently mapped to {{exitCodeClass}}",
|
||||
"If the installer only recommends a restart (MSI 3010 ERROR_SUCCESS_REBOOT_REQUIRED, 1641 ERROR_SUCCESS_REBOOT_INITIATED), map the code to Soft reboot instead of Hard reboot so the next app can install before the restart",
|
||||
"If the app works without an immediate restart, suppress the installer's own reboot (for MSI: REBOOT=ReallySuppress on the install command) so it returns 0 and the restart happens on your schedule",
|
||||
"Keep Hard reboot only when the following apps genuinely cannot install before the restart - and then expect the mid-ESP restart in every enrollment"
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "Take the app out of the ESP critical path",
|
||||
"steps": [
|
||||
"If the app is not needed for first use, remove it from the ESP blocking-app list so the restart happens after the user reaches the desktop",
|
||||
"If it must stay blocking, order it last in Device Setup (dependencies or install order) so a hard reboot does not interrupt the remaining apps",
|
||||
"For Soft reboot apps, plan a restart at the end of enrollment or accept that the app finishes on the user's first restart"
|
||||
]
|
||||
}
|
||||
],
|
||||
"relatedDocs": [
|
||||
{
|
||||
"title": "Microsoft Learn: Add a Win32 app - Program step (device restart behavior and return codes)",
|
||||
"url": "https://learn.microsoft.com/en-us/intune/app-management/deployment/add-win32#step-2-program"
|
||||
},
|
||||
{
|
||||
"title": "Microsoft Learn: Enrollment Status Page tracking",
|
||||
"url": "https://learn.microsoft.com/en-us/autopilot/enrollment-status"
|
||||
}
|
||||
],
|
||||
"markSessionAsFailedDefault": false,
|
||||
"tags": [
|
||||
"apps",
|
||||
"reboot",
|
||||
"return-code",
|
||||
"soft-reboot",
|
||||
"hard-reboot",
|
||||
"esp",
|
||||
"second-sign-in"
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "ANALYZE-CORR-003",
|
||||
"title": "Proxy Configuration Causing Download Failure",
|
||||
|
||||
+11
@@ -339,6 +339,17 @@
|
||||
"description": "Captures the installer exit code (lpExitCode) for the current app.",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"patternId": "IME-EXITCODE-CLASS",
|
||||
"category": "currentPhase",
|
||||
"pattern": "^\\[Win32App\\] lpExitCode is defined as (?<exitCodeClass>Success|SoftReboot|HardReboot|Retry|Failed)$",
|
||||
"action": "captureExitCodeClass",
|
||||
"parameters": {
|
||||
"useCurrentApp": "true"
|
||||
},
|
||||
"description": "Captures the admin-defined return-code class of the installer exit code for the current app ('[Win32App] lpExitCode is defined as <Failed|Success|SoftReboot|HardReboot|Retry>', Win32AppInstaller.cs, enum AppReturnCodeType - literal identical from IME 1.50 through 1.105). Stored as exitCodeClass on the app and emitted on its terminal events; the last value wins, so a Retry loop that ends in Success reports Success. Anchored on both ends on purpose: the no-mapping warning ('... defined as <n>, fall into default now.') and an unparsable numeric type print a raw number and must not match. Companion of IME-EXITCODE (the number, logged just before) and IME-EXITCODE-MAPPED-FAILED (the Failed state transition), which still owns the error path.",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"patternId": "IME-EXITCODE-MAPPED-FAILED",
|
||||
"category": "currentPhase",
|
||||
|
||||
@@ -282,5 +282,25 @@
|
||||
"log_entry",
|
||||
"agent_trace",
|
||||
"stall_probe_check"
|
||||
],
|
||||
"imeLogDerivedEventTypes": [
|
||||
"app_install_started",
|
||||
"app_install_completed",
|
||||
"app_install_failed",
|
||||
"app_install_skipped",
|
||||
"app_download_started",
|
||||
"app_tracking_summary",
|
||||
"download_progress",
|
||||
"do_telemetry",
|
||||
"script_started",
|
||||
"script_completed",
|
||||
"script_failed",
|
||||
"script_timeout_suspected",
|
||||
"esp_phase_changed",
|
||||
"ime_agent_version",
|
||||
"ime_token_failure",
|
||||
"ime_user_session_completed",
|
||||
"ime_process_exited",
|
||||
"ime_user_token_acquired"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "../schema/ime-log-pattern.schema.json",
|
||||
"patternId": "IME-EXITCODE-CLASS",
|
||||
"category": "currentPhase",
|
||||
"pattern": "^\\[Win32App\\] lpExitCode is defined as (?<exitCodeClass>Success|SoftReboot|HardReboot|Retry|Failed)$",
|
||||
"action": "captureExitCodeClass",
|
||||
"parameters": { "useCurrentApp": "true" },
|
||||
"description": "Captures the admin-defined return-code class of the installer exit code for the current app ('[Win32App] lpExitCode is defined as <Failed|Success|SoftReboot|HardReboot|Retry>', Win32AppInstaller.cs, enum AppReturnCodeType - literal identical from IME 1.50 through 1.105). Stored as exitCodeClass on the app and emitted on its terminal events; the last value wins, so a Retry loop that ends in Success reports Success. Anchored on both ends on purpose: the no-mapping warning ('... defined as <n>, fall into default now.') and an unparsable numeric type print a raw number and must not match. Companion of IME-EXITCODE (the number, logged just before) and IME-EXITCODE-MAPPED-FAILED (the Failed state transition), which still owns the error path.",
|
||||
"enabled": true
|
||||
}
|
||||
@@ -168,7 +168,7 @@
|
||||
},
|
||||
"source": {
|
||||
"type": "string",
|
||||
"description": "Source of the signal. phase_duration and app_install_duration never derive a duration from an IME-log timestamp whose sourceOffsetOrigin is reader-zone-fallback (writer timezone unknown to the agent): such a condition evaluates false with evidence timestampProvenance=reader-zone-fallback.",
|
||||
"description": "Source of the signal. phase_duration and app_install_duration never derive a duration from a span with mixed timestamp provenance (exactly one IME-log endpoint with sourceOffsetOrigin=reader-zone-fallback, i.e. the writer timezone was unknown to the agent for one endpoint only): such a condition evaluates false with evidence timestampProvenance=reader-zone-fallback. Two fallback endpoints share the same error and stay measurable.",
|
||||
"enum": ["event_type", "event_data", "event_data_array", "phase_duration", "event_count", "app_install_duration", "event_correlation", "clock_skew"]
|
||||
},
|
||||
"skewMetric": {
|
||||
|
||||
@@ -114,6 +114,11 @@
|
||||
"description": "Emit behavior: \"always\" (default — emit on every collection) or \"on_change\" (poll on the trigger cadence but emit only when the collected result changes; the first in-scope result always emits).",
|
||||
"enum": ["always", "on_change"]
|
||||
},
|
||||
"enrichErrorCodes": {
|
||||
"type": "boolean",
|
||||
"description": "Opt-in: let the backend explain error-code fields in this rule's output (exitCode, errorCode, hresult, ...) with the Windows/MSI/Intune error-code catalog, attaching the same *Info siblings built-in events get. Default false because gather-rule codes usually come from third-party logs or commands (HP Image Assistant, Dell Command Update, custom scripts) with their own exit-code numbering, where the catalog meaning would be wrong. Enable only when the parsed source really uses Windows codes (e.g. an msiexec or IME log).",
|
||||
"default": false
|
||||
},
|
||||
"outputEventType": {
|
||||
"type": "string",
|
||||
"description": "EventType for the emitted event (e.g., \"gather_proxy_settings\")."
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"blockedFilePrefixes": { "$ref": "#/$defs/stringList" },
|
||||
"blockedCommandPatterns": { "$ref": "#/$defs/stringList" },
|
||||
"blockedInterimTriggerEventTypes": { "$ref": "#/$defs/stringList" },
|
||||
"imeLogDerivedEventTypes": { "$ref": "#/$defs/stringList" },
|
||||
"maxCommandLength": { "type": "integer", "minimum": 1, "maximum": 100000 }
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -79,7 +79,8 @@
|
||||
"captureAppTypeWinGet",
|
||||
"captureAppTypeMsi",
|
||||
"captureAttemptNumber",
|
||||
"captureDetectionResult"
|
||||
"captureDetectionResult",
|
||||
"captureExitCodeClass"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
|
||||
@@ -142,6 +142,7 @@ if (fs.existsSync(guardrailsPath)) {
|
||||
assertStringList(guardrails[key], key);
|
||||
}
|
||||
assertStringList(guardrails.blockedInterimTriggerEventTypes ?? [], 'blockedInterimTriggerEventTypes');
|
||||
assertStringList(guardrails.imeLogDerivedEventTypes ?? [], 'imeLogDerivedEventTypes');
|
||||
if (!Number.isInteger(guardrails.maxCommandLength) || guardrails.maxCommandLength < 1) {
|
||||
fail(`maxCommandLength: expected a positive integer, got ${JSON.stringify(guardrails.maxCommandLength)}`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# Error-code catalog generator
|
||||
|
||||
`generate.mjs` rebuilds `src/Shared/AutopilotMonitor.Shared/Resources/error-codes.json`
|
||||
(schemaVersion 2) from primary sources and refreshes the web copy through
|
||||
`src/Web/autopilot-monitor-web/scripts/sync-error-codes.js`. The catalog is never edited by
|
||||
hand: a wrong or missing entry is fixed in the generator (a source, a pin, a family rule) and
|
||||
regenerated, so the next regeneration cannot lose the fix.
|
||||
|
||||
```
|
||||
IME_ENUMS_JSON=<path> node scripts/error-codes/generate.mjs [--cache-dir DIR] [--check]
|
||||
```
|
||||
|
||||
- `IME_ENUMS_JSON` — enum extract of one Intune Management Extension build (`imeVersion`,
|
||||
`customErrorCodes`, `enforcementStates`, `msiRetriableErrorCodes`, `deliveryOptimization`).
|
||||
Produced by operator tooling; the generator only reads the JSON.
|
||||
- `--cache-dir DIR` — keeps the fetched pages as files for offline reruns.
|
||||
- `--check` — exits 1 when the committed catalog differs from the generator output.
|
||||
|
||||
## Entry shape
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| key | lowercase 8-digit hex (`0x80070005`) or a decimal MSI exit code (`1603`). Decimal keys exist only for `0`, `1601`–`1654` and `3010`: exit codes of other installers are author-defined. Win32 codes live only as `0x8007xxxx`; a `HRESULT_FROM_WIN32` value whose low word is in the MSI range resolves to the decimal entry at lookup time (`derivedFromWin32`). |
|
||||
| `description` | one line, taken from the source (see rules below) |
|
||||
| `confidence` | `high` = MS Learn table/page or the IME build named in `source`; `medium` = paraphrase of an enum member name or of an analysis rule; `low` = carried over from the v1 catalog without a primary source |
|
||||
| `source` | `msdoc:<learn.microsoft.com URL>` · `ime:<version>` · `winerror.h` · `rule:<RULE-ID>` · `legacy-catalog-v1` |
|
||||
| `category` | `msi` `win32` `com` `appx` `windows-update` `cbs` `intune-win32` `intune-mobile` `mdm-enrollment` `autopilot` `entra-join` `delivery-optimization` |
|
||||
| `symbol` | optional: the `winerror.h`/WU/AppX symbol, or the IME enum member name |
|
||||
| `imeRetriesDuringEsp` | optional: one of the MSI return codes the IME retries automatically during the Autopilot ESP |
|
||||
|
||||
`enforcementStates` is a second map: IME app enforcement state number → `{ name, description }`.
|
||||
|
||||
## Sources and family rules
|
||||
|
||||
Families are processed in this order; the first family that yields a key wins and later
|
||||
duplicates are reported on stderr.
|
||||
|
||||
| Family | Source | Rule |
|
||||
|---|---|---|
|
||||
| win32 | [System Error Codes](https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes) (per-range pages), [WinHTTP error messages](https://learn.microsoft.com/en-us/windows/win32/winhttp/error-messages) | Seed = codes seen in the field (`WIN32_FIELD_SEEN`) ∪ the IME MSI-retry list ∪ every `0x8007xxxx` code another family names, minus the MSI decimal range and the AppX page's own range. Symbol and text verbatim. A seed code the reference does not list fails the run. |
|
||||
| msi | [Windows Installer error codes](https://learn.microsoft.com/en-us/windows/win32/msi/error-codes) | Rows in the MSI decimal range only; verbatim. |
|
||||
| com | `winerror.h` | Hand-listed HRESULTs that are not Win32-derived (`S_OK`, `E_FAIL`, `E_UNEXPECTED`, HTTP/RPC status HRESULTs the Delivery Optimization client names). |
|
||||
| appx | [Troubleshooting packaging, deployment, and query of Windows apps](https://learn.microsoft.com/en-us/windows/win32/appxpkg/troubleshooting) | Whole table; first sentence of the cell. Authority for its own `0x80073Cxx`/`0x80073Dxx` range. |
|
||||
| windows-update | [Windows Update error codes by component](https://learn.microsoft.com/en-us/windows/deployment/update/windows-update-error-reference) | Sections an enrollment can meet (agent core, handlers, download manager, protocol talker, data store, drivers, MSI handler, agent setup, AU client); verbatim. |
|
||||
| windows-update / cbs | [Windows Update common errors](https://learn.microsoft.com/en-us/windows/deployment/update/windows-update-errors) | One table per single-code heading; symbol = text before `;` in the Message cell, description = text after it, else the Description cell. `0x800F…` → `cbs`. |
|
||||
| intune-mobile / intune-win32 | [Intune app installation error codes](https://learn.microsoft.com/en-us/troubleshoot/mem/intune/app-management/app-install-error-codes) | iOS/iPadOS and Windows tables (Android skipped); description = the message cell. |
|
||||
| mdm-enrollment / autopilot / entra-join | [Windows enrollment errors](https://learn.microsoft.com/en-us/troubleshoot/mem/intune/device-enrollment/troubleshoot-windows-enrollment-errors), [Autopilot known issues](https://learn.microsoft.com/en-us/autopilot/known-issues) | Prose pages: one-sentence paraphrase listed in `PROSE_ENTRIES`; the generator asserts the code appears on the page. Codes only our analysis rules name carry `rule:` and `medium`. |
|
||||
| intune-win32 (`0x87D3xxxx`) | IME `CustomErrorCodes` enum | Member name as symbol, humanised as description, `medium`. Two known sign/digit defects in the enum source are corrected by `IME_ENUM_FIXUPS`; a build that fixes them makes the run fail so the fixup is removed. |
|
||||
| delivery-optimization (`0x80D0xxxx`) | IME `DeliveryOptimizationConstants` | Member name as symbol, humanised, `medium`. |
|
||||
| legacy | v1 catalog | Entries no primary source covers, `low`. |
|
||||
|
||||
Description rules: whole sentences up to 200 characters, cross-reference sentences
|
||||
("For more information, see …") dropped, no trailing period. `DESCRIPTION_PINS` holds the
|
||||
few wordings consumers depend on (each says the same as the source row it replaces).
|
||||
|
||||
## Regeneration checklist
|
||||
|
||||
1. Run the generator (with `--cache-dir` when iterating).
|
||||
2. Read the stderr summary: entry count per family, dropped duplicates.
|
||||
3. `git diff` the catalog; a removed key needs a reason (the C#, web and MCP tests pin the
|
||||
keys the product relies on).
|
||||
4. Spot-check ten random entries per family against the source page.
|
||||
5. Build and run the Backend, Web and MCP test suites.
|
||||
@@ -0,0 +1,563 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Error-code catalog generator (schemaVersion 2).
|
||||
*
|
||||
* Rebuilds src/Shared/AutopilotMonitor.Shared/Resources/error-codes.json from primary
|
||||
* sources and writes the web copy through the web sync script. Every entry carries the
|
||||
* source it was taken from; nothing is typed in from memory.
|
||||
*
|
||||
* node scripts/error-codes/generate.mjs [--cache-dir DIR] [--check]
|
||||
*
|
||||
* IME_ENUMS_JSON required — path to the enum extract of one Intune Management Extension
|
||||
* build (customErrorCodes, enforcementStates, msiRetriableErrorCodes,
|
||||
* deliveryOptimization). Produced by operator tooling; the generator has
|
||||
* no notion of where the enums come from.
|
||||
* --cache-dir DIR read/write the fetched MS Learn pages as files in DIR (offline reruns).
|
||||
* --check do not write; exit 1 when the committed catalog differs from the output.
|
||||
*
|
||||
* Families, in precedence order (the first family that yields a key wins; later duplicates
|
||||
* are reported and dropped):
|
||||
* win32 MS "System Error Codes" + WinHTTP error page, keyed 0x8007xxxx
|
||||
* msi MS "Windows Installer error codes", decimal keys 0 / 1601-1654 / 3010
|
||||
* com winerror.h HRESULTs that are not Win32-derived (S_OK, E_FAIL, ...)
|
||||
* appx MS "Troubleshooting packaging, deployment, and query of Windows apps"
|
||||
* windows-update MS "Windows Update error codes by component" (reference tables)
|
||||
* cbs / windows-update MS "Windows Update common errors and mitigation" (per-code tables)
|
||||
* intune-* MS "Intune app installation error codes" (iOS + Windows tables)
|
||||
* mdm-enrollment/ MS enrollment troubleshooting + Autopilot known-issues pages (prose:
|
||||
* autopilot/entra-join one-sentence paraphrase, presence-checked against the page)
|
||||
* intune-win32 IME CustomErrorCodes enum (0x87D3xxxx), member name paraphrased
|
||||
* delivery-optimization IME DeliveryOptimizationConstants (0x80D0xxxx), member name paraphrased
|
||||
* legacy v1 entries without a primary source, kept at confidence "low"
|
||||
*
|
||||
* See README.md next to this file for the source list and the description rules.
|
||||
*/
|
||||
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO_ROOT = path.resolve(HERE, "..", "..");
|
||||
const TARGET = path.join(REPO_ROOT, "src", "Shared", "AutopilotMonitor.Shared", "Resources", "error-codes.json");
|
||||
const WEB_SYNC = path.join(REPO_ROOT, "src", "Web", "autopilot-monitor-web", "scripts", "sync-error-codes.js");
|
||||
|
||||
// ── CLI ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const cacheDir = args.includes("--cache-dir") ? args[args.indexOf("--cache-dir") + 1] : undefined;
|
||||
const checkOnly = args.includes("--check");
|
||||
const imeEnumsPath = process.env.IME_ENUMS_JSON;
|
||||
if (!imeEnumsPath || !existsSync(imeEnumsPath)) {
|
||||
console.error("IME_ENUMS_JSON must point to the IME enum extract (see README.md).");
|
||||
process.exit(2);
|
||||
}
|
||||
const ime = JSON.parse(readFileSync(imeEnumsPath, "utf8"));
|
||||
if (!/^\d+(\.\d+)+$/.test(String(ime.imeVersion ?? ""))) {
|
||||
console.error("IME enum extract has no imeVersion.");
|
||||
process.exit(2);
|
||||
}
|
||||
const IME_SOURCE = `ime:${ime.imeVersion}`;
|
||||
|
||||
// ── Vocabulary (mirrored by the C#, web and MCP tests) ───────────────────────
|
||||
|
||||
export const CATEGORIES = [
|
||||
"msi", "win32", "com", "appx", "windows-update", "cbs", "intune-win32", "intune-mobile",
|
||||
"mdm-enrollment", "autopilot", "entra-join", "delivery-optimization",
|
||||
];
|
||||
export const CONFIDENCES = ["high", "medium", "low"];
|
||||
export const SOURCE_PATTERN = /^(msdoc:https:\/\/learn\.microsoft\.com\/[^\s]+|ime:\d+(\.\d+)+|winerror\.h|rule:[A-Z]+-[A-Z]+-\d{3}|legacy-catalog-v1)$/;
|
||||
export const KEY_PATTERN = /^(0x[0-9a-f]{8}|\d+)$/;
|
||||
// winerror-style (ERROR_INSTALL_FAILURE) or an enum member (UnzipError); never a phrase.
|
||||
const SYMBOL_PATTERN = /^[A-Za-z][A-Za-z0-9_]{2,}$/;
|
||||
const MAX_DESCRIPTION = 200;
|
||||
|
||||
// ── Sources ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const URL = {
|
||||
msi: "https://learn.microsoft.com/en-us/windows/win32/msi/error-codes",
|
||||
appx: "https://learn.microsoft.com/en-us/windows/win32/appxpkg/troubleshooting",
|
||||
wuReference: "https://learn.microsoft.com/en-us/windows/deployment/update/windows-update-error-reference",
|
||||
wuErrors: "https://learn.microsoft.com/en-us/windows/deployment/update/windows-update-errors",
|
||||
intuneApps: "https://learn.microsoft.com/en-us/troubleshoot/mem/intune/app-management/app-install-error-codes",
|
||||
enrollErrors: "https://learn.microsoft.com/en-us/troubleshoot/mem/intune/device-enrollment/troubleshoot-windows-enrollment-errors",
|
||||
knownIssues: "https://learn.microsoft.com/en-us/autopilot/known-issues",
|
||||
winhttp: "https://learn.microsoft.com/en-us/windows/win32/winhttp/error-messages",
|
||||
win32: (range) => `https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--${range}-`,
|
||||
};
|
||||
const WIN32_RANGES = [[0, 499], [500, 999], [1000, 1299], [1300, 1699], [1700, 3999], [4000, 5999], [6000, 8199], [8200, 8999], [9000, 11999], [12000, 15999]];
|
||||
const WINHTTP_RANGE = [12000, 12200];
|
||||
|
||||
const msdoc = (url) => `msdoc:${url}`;
|
||||
|
||||
const pageCache = new Map();
|
||||
async function fetchPage(url) {
|
||||
if (pageCache.has(url)) return pageCache.get(url);
|
||||
const cacheFile = cacheDir ? path.join(cacheDir, url.replace(/^https?:\/\//, "").replace(/[^a-z0-9.-]+/gi, "_") + ".html") : null;
|
||||
let html;
|
||||
if (cacheFile && existsSync(cacheFile)) {
|
||||
html = readFileSync(cacheFile, "utf8");
|
||||
} else {
|
||||
const res = await fetch(url, { headers: { "user-agent": "Mozilla/5.0 (error-code catalog generator)" } });
|
||||
if (!res.ok) throw new Error(`GET ${url} → ${res.status}`);
|
||||
html = await res.text();
|
||||
if (cacheFile) {
|
||||
mkdirSync(path.dirname(cacheFile), { recursive: true });
|
||||
writeFileSync(cacheFile, html, "utf8");
|
||||
}
|
||||
}
|
||||
pageCache.set(url, html);
|
||||
return html;
|
||||
}
|
||||
|
||||
// ── HTML helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
const ENTITIES = { nbsp: " ", amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'", "#x27": "'" };
|
||||
|
||||
/**
|
||||
* Cell markup → plain text. Tags are stripped until none remain (a nested "<scr<b>ipt>" cannot
|
||||
* survive), and entities are decoded in ONE pass so "&lt;" yields "<", never "<".
|
||||
*/
|
||||
const decode = (s) => {
|
||||
let text = s.replace(/<br\s*\/?>/gi, " ").replace(/<\/(p|li|div)>/gi, " ");
|
||||
let previous;
|
||||
do {
|
||||
previous = text;
|
||||
text = text.replace(/<[^>]*>/g, "");
|
||||
} while (text !== previous);
|
||||
return text
|
||||
.replace(/&(nbsp|amp|lt|gt|quot|#39|#x27);/g, (_, name) => ENTITIES[name])
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
};
|
||||
|
||||
/** Every <table> of a page as rows of decoded cell strings, in document order. */
|
||||
function parseTables(html) {
|
||||
return [...html.matchAll(/<table[\s\S]*?<\/table>/gi)].map((t) =>
|
||||
[...t[0].matchAll(/<tr[\s\S]*?<\/tr>/gi)]
|
||||
.map((r) => [...r[0].matchAll(/<t[hd][^>]*>([\s\S]*?)<\/t[hd]>/gi)].map((c) => decode(c[1])))
|
||||
.filter((cells) => cells.length > 0));
|
||||
}
|
||||
|
||||
/** h2/h3 headings and the table that follows each, in order (the "one table per code" pages). */
|
||||
function parseHeadedTables(html) {
|
||||
const out = [];
|
||||
const seq = [...html.matchAll(/<h([23])[^>]*>([\s\S]*?)<\/h\1>|<table[\s\S]*?<\/table>/gi)];
|
||||
let heading = null;
|
||||
for (const m of seq) {
|
||||
if (m[0].startsWith("<h")) { heading = decode(m[2]); continue; }
|
||||
if (!heading) continue;
|
||||
const rows = [...m[0].matchAll(/<tr[\s\S]*?<\/tr>/gi)]
|
||||
.map((r) => [...r[0].matchAll(/<t[hd][^>]*>([\s\S]*?)<\/t[hd]>/gi)].map((c) => decode(c[1])));
|
||||
out.push({ heading, rows });
|
||||
heading = null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* winerror.h-style reference pages: `<strong>SYMBOL</strong>` followed by a paragraph with the
|
||||
* decimal value (optionally "(0x…)") and a paragraph with the text. Shape shared by the
|
||||
* System Error Codes pages and the WinHTTP error page.
|
||||
*/
|
||||
function parseSymbolPage(html) {
|
||||
const map = new Map();
|
||||
const re = /<strong>([A-Z][A-Z0-9_]+)<\/strong><\/p>(?:\s|<\/?(?:dt|dd|dl)>)*<p>(\d+)(?:\s*\(0x[0-9A-Fa-f]+\))?<\/p>(?:\s|<\/?(?:dt|dd|dl)>)*<p>([\s\S]*?)<\/p>/g;
|
||||
for (const m of html.matchAll(re)) {
|
||||
const value = Number(m[2]);
|
||||
if (!map.has(value)) map.set(value, { symbol: m[1], text: decode(m[3]) });
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
// ── Description shaping ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* One short line per code: whole sentences from the source text up to MAX_DESCRIPTION
|
||||
* characters (at least one sentence; a single over-long sentence is cut with an ellipsis).
|
||||
* Cross-reference sentences ("For more information, see …", "See …") are dropped. Pages whose
|
||||
* cell continues with troubleshooting prose pass `firstSentence` and keep only the first one.
|
||||
*/
|
||||
export function shapeDescription(text, { firstSentence = false } = {}) {
|
||||
const clean = String(text).replace(/\s+/g, " ").trim();
|
||||
const sentences = clean.split(/(?<=[.!?])\s+(?=[A-Z0-9("'])/)
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s && !/^(For (more )?information|See |Refer to)/i.test(s));
|
||||
const kept = [];
|
||||
let length = 0;
|
||||
for (const s of sentences) {
|
||||
if (kept.length > 0 && (firstSentence || length + 1 + s.length > MAX_DESCRIPTION)) break;
|
||||
kept.push(s);
|
||||
length += (kept.length > 1 ? 1 : 0) + s.length;
|
||||
}
|
||||
let result = kept.join(" ") || clean;
|
||||
if (result.length > MAX_DESCRIPTION + 20) result = result.slice(0, MAX_DESCRIPTION).trimEnd() + "…";
|
||||
result = result.replace(/\.$/, "");
|
||||
return result.charAt(0).toUpperCase() + result.slice(1);
|
||||
}
|
||||
|
||||
/** "InvalidDetectionRuleUnknownDetectionType" → "Invalid detection rule: unknown detection type". */
|
||||
export function humanizeMember(name) {
|
||||
const PREFIXES = ["InvalidDetectionRule", "InvalidRequirementRule", "AppLogUpload", "NotAttempted", "InProgress", "SuccessBut", "Success", "Error", "ResumeJobFailure"];
|
||||
const ACRONYMS = { CDN: "CDN", DO: "DO", SAS: "SAS", MSI: "MSI", VPP: "VPP", IOS: "iOS", TPM: "TPM", MDM: "MDM", HTTP: "HTTP", URL: "URL", COM: "COM", APK: "APK", CP: "CP", ID: "ID" };
|
||||
const words = (s) => s
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
|
||||
.split(" ")
|
||||
.map((w) => ACRONYMS[w.toUpperCase()] ?? w.toLowerCase());
|
||||
const prefix = PREFIXES.find((p) => name.startsWith(p) && name.length > p.length);
|
||||
if (prefix) {
|
||||
const head = words(prefix);
|
||||
const tail = words(name.slice(prefix.length));
|
||||
return capitalize(head.join(" ")) + ": " + tail.join(" ");
|
||||
}
|
||||
return capitalize(words(name).join(" "));
|
||||
}
|
||||
const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
|
||||
|
||||
// ── Key helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
const hexKey = (n) => "0x" + ((n >>> 0).toString(16)).padStart(8, "0");
|
||||
const fromSigned = (n) => hexKey(n < 0 ? n + 0x100000000 : n);
|
||||
const normalizeHex = (raw) => hexKey(parseInt(raw.replace(/^0x/i, ""), 16));
|
||||
const isFacility7 = (key) => key.startsWith("0x8007");
|
||||
const MSI_DECIMAL = (n) => n === 0 || (n >= 1601 && n <= 1654) || n === 3010;
|
||||
|
||||
// ── Families ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Win32 codes that the field has shown as 0x8007xxxx HRESULTs (beyond what other families name). */
|
||||
const WIN32_FIELD_SEEN = [
|
||||
1, 2, 3, 4, 5, 6, 8, 13, 14, 23, 32, 50, 53, 64, 67, 87, 112, 120, 122, 258, 314, 995, 1053, 1058, 1067,
|
||||
1114, 1168, 1203, 1219, 1220, 1222, 1223, 1231, 1232, 1235, 1259, 1311, 1312, 1326, 1327, 1355, 1385,
|
||||
1392, 1450, 1460, 1717, 1722, 1726, 1780, 1784, 1789, 1908, 1909, 3017, 8239,
|
||||
12002, 12007, 12029, 12030, 12152, 12175, 14081, 14107,
|
||||
];
|
||||
|
||||
/** HRESULTs that are not Win32-derived; text as in winerror.h. */
|
||||
const COM_ENTRIES = [
|
||||
["0x00000000", "S_OK", "Success"],
|
||||
["0x80004001", "E_NOTIMPL", "Not implemented"],
|
||||
["0x80004002", "E_NOINTERFACE", "No such interface supported"],
|
||||
["0x80004003", "E_POINTER", "Invalid pointer"],
|
||||
["0x80004004", "E_ABORT", "Operation aborted"],
|
||||
["0x80004005", "E_FAIL", "Unspecified error"],
|
||||
["0x8000ffff", "E_UNEXPECTED", "Catastrophic failure"],
|
||||
["0x80010108", "RPC_E_DISCONNECTED", "The object invoked has disconnected from its clients"],
|
||||
["0x80020005", "DISP_E_TYPEMISMATCH", "Type mismatch"],
|
||||
["0x80190193", "HTTP_E_STATUS_FORBIDDEN", "Forbidden (403)"],
|
||||
["0x80190194", "HTTP_E_STATUS_NOT_FOUND", "Not found (404)"],
|
||||
];
|
||||
|
||||
/**
|
||||
* Codes documented on prose pages (no table to parse). The generator asserts that the code
|
||||
* appears on the named page; the description is a one-sentence paraphrase of that page.
|
||||
*/
|
||||
const PROSE_ENTRIES = [
|
||||
{ key: "0x80180014", category: "mdm-enrollment", page: URL.enrollErrors,
|
||||
description: "Your organization does not support this version of Windows: MDM enrollment is disabled or restricted in the tenant, or an Autopilot device record still exists on redeploy" },
|
||||
{ key: "0x80180022", category: "autopilot", page: URL.enrollErrors,
|
||||
description: "Autopilot device enrollment failed: the device runs Windows Home edition (Pro or higher is required)" },
|
||||
{ key: "0x8018002b", category: "mdm-enrollment", page: URL.enrollErrors,
|
||||
description: "Automatic MDM enrollment failed: the user's UPN has an unverified or non-routable domain, or the MDM user scope is set to None" },
|
||||
{ key: "0x801c03ea", category: "entra-join", page: URL.enrollErrors,
|
||||
description: "Registering the device for mobile management failed: the TPM supports 2.0 but has not been upgraded to 2.0, or the device is in two groups with different Autopilot profiles" },
|
||||
{ key: "0x801c03f3", category: "entra-join", page: URL.knownIssues,
|
||||
description: "Microsoft Entra ID has no device object for the device being deployed (the object was deleted); remove the device from Entra ID, Intune and Autopilot and re-register it" },
|
||||
{ key: "0x81039001", category: "autopilot", page: URL.knownIssues, symbol: "E_AUTOPILOT_CLIENT_TPM_MAX_ATTESTATION_RETRY_EXCEEDED",
|
||||
description: "TPM attestation failed intermittently during self-deploying or pre-provisioning (Securing your hardware); a subsequent provisioning attempt often succeeds" },
|
||||
{ key: "0x81039023", category: "autopilot", page: URL.knownIssues,
|
||||
description: "TPM attestation failed on Windows 11 during self-deploying or pre-provisioning; fixed by the May 2022 cumulative update (KB5013943) or later" },
|
||||
{ key: "0x81039024", category: "autopilot", page: URL.knownIssues,
|
||||
description: "TPM attestation failed because known vulnerabilities were detected in the TPM; update the TPM firmware from the PC manufacturer" },
|
||||
{ key: "0xc1036501", category: "mdm-enrollment", page: URL.knownIssues,
|
||||
description: "The device cannot do an automatic MDM enrollment because there are multiple MDM configurations in Microsoft Entra ID" },
|
||||
// Named only in our own analysis rule, no MS page found: confidence medium.
|
||||
{ key: "0x80180018", category: "mdm-enrollment", source: "rule:ANALYZE-ENRL-004", confidence: "medium",
|
||||
description: "MDM enrollment refused for the user: missing Intune, EMS or Microsoft 365 license, or the device enrollment limit was exceeded" },
|
||||
];
|
||||
|
||||
/** v1 entries that no primary source covers — kept, marked low. */
|
||||
const LEGACY_ENTRIES = [
|
||||
["0x87d00213", "intune-win32", "App not applicable"],
|
||||
["0x87d00215", "intune-win32", "App dependency failed"],
|
||||
["0x87d00216", "intune-win32", "App supersedence conflict"],
|
||||
["0x87d00324", "intune-win32", "App installation failed"],
|
||||
["0x87d00607", "intune-win32", "App download failed"],
|
||||
["0x87d00651", "intune-win32", "Detection rules not met after install"],
|
||||
["0x87d13b88", "intune-mobile", "License assignment failed with token expired (VPP)"],
|
||||
["0x87d1fde8", "intune-win32", "Remediation failed"],
|
||||
["0x800f0991", "cbs", "A payload file is missing from the component store", "PSFX_E_MISSING_PAYLOAD_FILE"],
|
||||
];
|
||||
|
||||
/**
|
||||
* Wording pins: consumers (tests, rule explanations) depend on these exact phrases. Each pin
|
||||
* says the same thing as the source row it replaces; the confidence stays with the source.
|
||||
*/
|
||||
const DESCRIPTION_PINS = {
|
||||
"0x87d1041c": { description: "Application not detected after installation completed successfully" },
|
||||
// The MS row describes one dated incident ("The July cumulative update failed…"); the code itself is generic.
|
||||
"0x800f0922": { description: "Windows servicing: a package installer failed during update installation", confidence: "medium" },
|
||||
};
|
||||
|
||||
/**
|
||||
* Known defects in the IME enum source (sign / digit typos). The fixup applies the intended
|
||||
* value and FAILS when the source no longer shows the defect, so a fixed build drops the fixup.
|
||||
*/
|
||||
const IME_ENUM_FIXUPS = {
|
||||
InvalidRequirementRuleUnknownRequirementType: { seen: 2016215026, intended: -2016215026 },
|
||||
AppLogUploadSasUrlExpired: { seen: -216214830, intended: -2016214830 },
|
||||
};
|
||||
|
||||
// ── Build ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const entries = new Map(); // key → entry
|
||||
const dropped = []; // { key, family, reason }
|
||||
function add(family, key, entry) {
|
||||
if (!KEY_PATTERN.test(key)) throw new Error(`${family}: bad key ${key}`);
|
||||
if (entries.has(key)) { dropped.push({ key, family, reason: `already defined by ${entries.get(key)._family}` }); return; }
|
||||
const description = shapeDescription(entry.description, { firstSentence: entry.firstSentence });
|
||||
if (!description) throw new Error(`${family}: empty description for ${key}`);
|
||||
const out = { description, confidence: entry.confidence, source: entry.source, category: entry.category };
|
||||
// Symbol cells may be wrapped with <br> ("ERROR_INSTALL_OPEN_ PACKAGE_FAILED"); the token has no spaces.
|
||||
const symbol = entry.symbol ? String(entry.symbol).replace(/\s+/g, "") : "";
|
||||
if (symbol && SYMBOL_PATTERN.test(symbol)) out.symbol = symbol;
|
||||
if (entry.imeRetriesDuringEsp) out.imeRetriesDuringEsp = true;
|
||||
const pin = DESCRIPTION_PINS[key];
|
||||
if (pin) { out.description = pin.description; if (pin.confidence) out.confidence = pin.confidence; }
|
||||
Object.defineProperty(out, "_family", { value: family, enumerable: false });
|
||||
entries.set(key, out);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const retriable = new Set(ime.msiRetriableErrorCodes.map(Number));
|
||||
|
||||
// Families other than Win32 are collected first so every 0x8007xxxx code they name can be
|
||||
// resolved against the Win32 reference, which then takes precedence.
|
||||
const pending = [];
|
||||
const queue = (family, key, entry) => pending.push({ family, key, entry });
|
||||
|
||||
// msi — decimal keys, MSI range only (other rows are plain Win32 codes and live as 0x8007xxxx).
|
||||
{
|
||||
const [table] = parseTables(await fetchPage(URL.msi));
|
||||
for (const [symbol, value, description] of table.slice(1)) {
|
||||
const n = Number(value);
|
||||
if (!Number.isInteger(n) || !MSI_DECIMAL(n)) continue;
|
||||
queue("msi", String(n), { symbol, description, confidence: "high", source: msdoc(URL.msi), category: "msi", imeRetriesDuringEsp: retriable.has(n) });
|
||||
}
|
||||
}
|
||||
|
||||
// com
|
||||
for (const [key, symbol, description] of COM_ENTRIES) queue("com", key, { symbol, description, confidence: "high", source: "winerror.h", category: "com" });
|
||||
|
||||
// appx
|
||||
{
|
||||
const [table] = parseTables(await fetchPage(URL.appx));
|
||||
for (const [symbol, value, description] of table.slice(1)) {
|
||||
if (!/^0x[0-9a-f]{8}$/i.test(value)) continue;
|
||||
queue("appx", normalizeHex(value), { symbol, description, firstSentence: true, confidence: "high", source: msdoc(URL.appx), category: "appx" });
|
||||
}
|
||||
}
|
||||
|
||||
// windows-update reference (Error code | Message | Description), the components an
|
||||
// enrollment can meet: agent core, handlers, download manager, protocol talker (HTTP),
|
||||
// data store, drivers, MSI handler, agent setup, AU client. Inventory / expression
|
||||
// evaluator / reporter / redirector are WSUS-internal and left out.
|
||||
const WU_SECTIONS = /^(Automatic Update Errors|Windows Update UI errors|Protocol Talker errors|Other Protocol Talker errors|Download Manager errors|Update Handler errors|Data Store errors|Driver Util errors|Windows Update error codes|Windows Update success codes|Windows Installer minor errors|Windows Update Agent update and setup errors)$/;
|
||||
for (const { heading, rows: table } of parseHeadedTables(await fetchPage(URL.wuReference))) {
|
||||
if (!WU_SECTIONS.test(heading)) continue;
|
||||
for (const [value, message, description] of table.slice(1)) {
|
||||
if (!/^0x[0-9a-f]{8}$/i.test(value)) continue;
|
||||
const key = normalizeHex(value);
|
||||
queue("windows-update", key, { symbol: message, description, confidence: "high", source: msdoc(URL.wuReference), category: categoryForWuKey(key) });
|
||||
}
|
||||
}
|
||||
|
||||
// windows-update common errors (one table per heading; Message | Description | Mitigation)
|
||||
for (const { heading, rows } of parseHeadedTables(await fetchPage(URL.wuErrors))) {
|
||||
// A heading that lumps several codes into one table ("0x80072EFD or 0x80072EFE or 0x80D02002")
|
||||
// describes a symptom, not the codes; only single-code sections are taken.
|
||||
const codes = [...heading.matchAll(/0x[0-9a-f]{8}/gi)].map((m) => normalizeHex(m[0]));
|
||||
if (codes.length !== 1 || rows.length < 2) continue;
|
||||
const [message, description] = rows[1];
|
||||
const [symbolPart, ...textParts] = message.split(";");
|
||||
const symbol = symbolPart.trim();
|
||||
const text = textParts.join(";").trim() || (description && description !== "NA" ? description : "");
|
||||
if (!text) continue;
|
||||
for (const key of codes) queue("windows-update", key, { symbol, description: text, firstSentence: true, confidence: "high", source: msdoc(URL.wuErrors), category: categoryForWuKey(key) });
|
||||
}
|
||||
|
||||
// intune — skip the Android table (heading order: Android, iOS/iPadOS, Other)
|
||||
{
|
||||
const tables = parseTables(await fetchPage(URL.intuneApps));
|
||||
for (const table of tables.slice(1)) {
|
||||
for (const [value, , message, description] of table.slice(1)) {
|
||||
if (!/^0x[0-9a-f]{8}$/i.test(value)) continue;
|
||||
const key = normalizeHex(value);
|
||||
const text = /^\(client error\)$/i.test(message) ? description : message;
|
||||
const category = key === "0x87d1041c" || key === "0x87d103e8" ? "intune-win32" : key.startsWith("0x87d1") ? "intune-mobile" : "appx";
|
||||
queue("intune", key, { description: text, firstSentence: true, confidence: "high", source: msdoc(URL.intuneApps), category });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// prose pages
|
||||
for (const e of PROSE_ENTRIES) {
|
||||
if (e.page) {
|
||||
const html = (await fetchPage(e.page)).toLowerCase();
|
||||
if (!html.includes(e.key.toLowerCase())) throw new Error(`prose: ${e.key} not found on ${e.page}`);
|
||||
}
|
||||
queue("prose", e.key, { symbol: e.symbol, description: e.description, confidence: e.confidence ?? "high", source: e.source ?? msdoc(e.page), category: e.category });
|
||||
}
|
||||
|
||||
// IME CustomErrorCodes (0x87D3xxxx)
|
||||
for (const [name, rawValue] of Object.entries(ime.customErrorCodes)) {
|
||||
if (name === "Undefined") continue;
|
||||
let value = Number(rawValue);
|
||||
const fix = IME_ENUM_FIXUPS[name];
|
||||
if (fix) {
|
||||
if (value !== fix.seen) throw new Error(`IME fixup for ${name} is stale: source shows ${value}, fixup expects ${fix.seen}`);
|
||||
value = fix.intended;
|
||||
}
|
||||
queue("ime-custom", fromSigned(value), { symbol: name, description: humanizeMember(name), confidence: "medium", source: IME_SOURCE, category: "intune-win32" });
|
||||
}
|
||||
for (const missing of Object.keys(IME_ENUM_FIXUPS).filter((n) => !(n in ime.customErrorCodes))) {
|
||||
throw new Error(`IME fixup names ${missing}, which the enum extract does not contain`);
|
||||
}
|
||||
|
||||
// IME Delivery Optimization constants
|
||||
const doc = ime.deliveryOptimization;
|
||||
for (const group of [doc.errorCodesDoSvc, doc.transientErrorCodesDoSvc]) {
|
||||
for (const [name, value] of Object.entries(group)) {
|
||||
queue("ime-do", fromSigned(Number(value)), { symbol: name, description: humanizeMember(name), confidence: "medium", source: IME_SOURCE, category: "delivery-optimization" });
|
||||
}
|
||||
}
|
||||
const doWindowsCodes = Object.values(doc.windowsErrorCodes).map((v) => fromSigned(Number(v)));
|
||||
|
||||
// legacy
|
||||
for (const [key, category, description, symbol] of LEGACY_ENTRIES) queue("legacy", key, { symbol, description, confidence: "low", source: "legacy-catalog-v1", category });
|
||||
|
||||
// win32 — seed: field list ∪ retriable ∪ every facility-7 code any family named, minus the MSI decimal range.
|
||||
const win32Seed = new Set(WIN32_FIELD_SEEN);
|
||||
for (const n of retriable) win32Seed.add(n);
|
||||
// The AppX page is the authority for its own facility-7 range (0x80073Cxx/0x80073Dxx): its rows
|
||||
// carry the packaging-specific wording, so those codes are not routed through the Win32 reference.
|
||||
const appxKeys = new Set(pending.filter((p) => p.family === "appx").map((p) => p.key));
|
||||
for (const key of [...pending.map((p) => p.key), ...doWindowsCodes]) {
|
||||
if (isFacility7(key) && !appxKeys.has(key)) win32Seed.add(parseInt(key.slice(6), 16));
|
||||
}
|
||||
for (const n of [...win32Seed]) if (MSI_DECIMAL(n)) win32Seed.delete(n);
|
||||
|
||||
const win32Pages = new Map();
|
||||
const resolveWin32 = async (n) => {
|
||||
const useWinHttp = n >= WINHTTP_RANGE[0] && n <= WINHTTP_RANGE[1];
|
||||
const range = WIN32_RANGES.find(([lo, hi]) => n >= lo && n <= hi);
|
||||
const candidates = useWinHttp ? [URL.winhttp] : [];
|
||||
if (range) candidates.push(URL.win32(`${range[0]}-${range[1]}`));
|
||||
for (const url of candidates) {
|
||||
if (!win32Pages.has(url)) win32Pages.set(url, parseSymbolPage(await fetchPage(url)));
|
||||
const hit = win32Pages.get(url).get(n);
|
||||
if (hit) return { ...hit, url };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
// A code another family names but the Win32 reference does not list (the AppX page carries
|
||||
// 0x80073Dxx symbols the System Error Codes pages omit) stays with that family; a code from
|
||||
// the explicit seed must resolve.
|
||||
const mustResolve = new Set([...WIN32_FIELD_SEEN, ...retriable]);
|
||||
const unresolved = [];
|
||||
for (const n of [...win32Seed].sort((a, b) => a - b)) {
|
||||
const hit = await resolveWin32(n);
|
||||
if (!hit) { if (mustResolve.has(n)) unresolved.push(n); continue; }
|
||||
add("win32", hexKey(0x80070000 + n), { symbol: hit.symbol, description: hit.text, confidence: "high", source: msdoc(hit.url), category: "win32", imeRetriesDuringEsp: retriable.has(n) });
|
||||
}
|
||||
if (unresolved.length > 0) throw new Error(`win32: no reference entry for ${unresolved.join(", ")}`);
|
||||
|
||||
for (const p of pending) add(p.family, p.key, p.entry);
|
||||
|
||||
// enforcement states
|
||||
const enforcementStates = {};
|
||||
for (const [name, value] of Object.entries(ime.enforcementStates)) {
|
||||
enforcementStates[String(value)] = { name, description: humanizeMember(name) };
|
||||
}
|
||||
|
||||
validate(entries, enforcementStates);
|
||||
|
||||
// ── Emit ──
|
||||
const keys = [...entries.keys()].sort((a, b) => {
|
||||
const ah = a.startsWith("0x"), bh = b.startsWith("0x");
|
||||
if (ah !== bh) return ah ? 1 : -1;
|
||||
return ah ? a.localeCompare(b) : Number(a) - Number(b);
|
||||
});
|
||||
const stateKeys = Object.keys(enforcementStates).sort((a, b) => Number(a) - Number(b));
|
||||
const header = {
|
||||
schemaVersion: 2,
|
||||
description:
|
||||
"Single-source catalog of Windows / MSI / Intune error codes, generated by scripts/error-codes/generate.mjs from primary sources — " +
|
||||
"never edit by hand. Consumed by the backend (ErrorCodeCatalog.cs, ErrorCodeEnricher.cs), the web app (utils/errorCodeMap.ts via the " +
|
||||
"sync-error-codes prebuild step) and the MCP server (lookup_error_code). Keys are lowercase 8-digit hex ('0x80070005') or decimal MSI exit " +
|
||||
"codes ('1603'; only 0, 1601-1654, 3010 — other decimal exit codes are installer-defined). Win32 codes live only as 0x8007xxxx entries; " +
|
||||
"HRESULT_FROM_WIN32 values in the MSI range resolve to the decimal entry at lookup time. confidence: high = MS Learn or the IME build named " +
|
||||
"in source; medium = paraphrase of an enum member name or of an analysis rule; low = carried over from the v1 catalog without a primary " +
|
||||
"source. category is one of: " + CATEGORIES.join(", ") + ". imeRetriesDuringEsp marks the MSI return codes the IME retries automatically " +
|
||||
"during the Autopilot ESP. enforcementStates maps the IME app enforcement state numbers to their names.",
|
||||
};
|
||||
const lines = [];
|
||||
lines.push("{");
|
||||
lines.push(` "schemaVersion": ${header.schemaVersion},`);
|
||||
lines.push(` "description": ${JSON.stringify(header.description)},`);
|
||||
lines.push(` "entries": {`);
|
||||
keys.forEach((k, i) => lines.push(` ${JSON.stringify(k)}: ${JSON.stringify(entries.get(k))}${i < keys.length - 1 ? "," : ""}`));
|
||||
lines.push(` },`);
|
||||
lines.push(` "enforcementStates": {`);
|
||||
stateKeys.forEach((k, i) => lines.push(` ${JSON.stringify(k)}: ${JSON.stringify(enforcementStates[k])}${i < stateKeys.length - 1 ? "," : ""}`));
|
||||
lines.push(` }`);
|
||||
lines.push("}");
|
||||
const output = lines.join("\n") + "\n";
|
||||
|
||||
const byFamily = {};
|
||||
for (const e of entries.values()) byFamily[e._family] = (byFamily[e._family] ?? 0) + 1;
|
||||
console.error(`entries: ${entries.size} (${Object.entries(byFamily).map(([f, n]) => `${f} ${n}`).join(", ")}), enforcementStates: ${stateKeys.length}`);
|
||||
if (dropped.length > 0) console.error(`dropped duplicates: ${dropped.map((d) => `${d.key}←${d.family} (${d.reason})`).join("; ")}`);
|
||||
|
||||
if (checkOnly) {
|
||||
const current = existsSync(TARGET) ? readFileSync(TARGET, "utf8") : "";
|
||||
if (current !== output) { console.error("catalog differs from generator output"); process.exit(1); }
|
||||
console.error("catalog is up to date");
|
||||
return;
|
||||
}
|
||||
writeFileSync(TARGET, output, "utf8");
|
||||
console.error(`wrote ${path.relative(REPO_ROOT, TARGET)}`);
|
||||
execFileSync(process.execPath, [WEB_SYNC], { stdio: "inherit" });
|
||||
}
|
||||
|
||||
function categoryForWuKey(key) {
|
||||
if (key.startsWith("0x800f")) return "cbs";
|
||||
if (key.startsWith("0x80d0")) return "delivery-optimization";
|
||||
return "windows-update";
|
||||
}
|
||||
|
||||
function validate(map, states) {
|
||||
const symbols = new Map();
|
||||
for (const [key, e] of map) {
|
||||
if (!KEY_PATTERN.test(key)) throw new Error(`bad key ${key}`);
|
||||
if (!e.description) throw new Error(`${key}: empty description`);
|
||||
if (e.description.length > MAX_DESCRIPTION + 21) throw new Error(`${key}: description too long`);
|
||||
if (!CONFIDENCES.includes(e.confidence)) throw new Error(`${key}: bad confidence ${e.confidence}`);
|
||||
if (!CATEGORIES.includes(e.category)) throw new Error(`${key}: bad category ${e.category}`);
|
||||
if (!SOURCE_PATTERN.test(e.source)) throw new Error(`${key}: bad source ${e.source}`);
|
||||
if (e.symbol) {
|
||||
if (symbols.has(e.symbol)) throw new Error(`symbol ${e.symbol} on both ${symbols.get(e.symbol)} and ${key}`);
|
||||
symbols.set(e.symbol, key);
|
||||
}
|
||||
}
|
||||
const names = new Set();
|
||||
for (const [k, s] of Object.entries(states)) {
|
||||
if (!/^-?\d+$/.test(k)) throw new Error(`enforcement state key ${k}`);
|
||||
if (names.has(s.name)) throw new Error(`enforcement state name ${s.name} twice`);
|
||||
names.add(s.name);
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
main().catch((err) => { console.error(err.stack ?? String(err)); process.exit(1); });
|
||||
}
|
||||
@@ -152,18 +152,6 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests
|
||||
.Where(p => !p.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}")
|
||||
&& !p.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}"));
|
||||
|
||||
private static string RepoRoot()
|
||||
{
|
||||
var dir = AppContext.BaseDirectory;
|
||||
for (int i = 0; i < 12; i++)
|
||||
{
|
||||
if (File.Exists(Path.Combine(dir, "AutopilotMonitor.sln"))) return dir;
|
||||
var parent = Directory.GetParent(dir)?.FullName;
|
||||
if (parent == null || parent == dir) break;
|
||||
dir = parent;
|
||||
}
|
||||
throw new DirectoryNotFoundException(
|
||||
"Could not locate repo root (AutopilotMonitor.sln) from " + AppContext.BaseDirectory);
|
||||
}
|
||||
private static string RepoRoot() => Harness.RepoPaths.Root();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Harness
|
||||
{
|
||||
/// <summary>Repository paths for tests that read or write checked-in files (guards, fixtures).</summary>
|
||||
internal static class RepoPaths
|
||||
{
|
||||
/// <summary>Walks up from the test binary to the directory holding <c>AutopilotMonitor.sln</c>.</summary>
|
||||
public static string Root()
|
||||
{
|
||||
var dir = AppContext.BaseDirectory;
|
||||
for (int i = 0; i < 12; i++)
|
||||
{
|
||||
if (File.Exists(Path.Combine(dir, "AutopilotMonitor.sln"))) return dir;
|
||||
var parent = Directory.GetParent(dir)?.FullName;
|
||||
if (parent == null || parent == dir) break;
|
||||
dir = parent;
|
||||
}
|
||||
throw new DirectoryNotFoundException(
|
||||
"Could not locate repo root (AutopilotMonitor.sln) from " + AppContext.BaseDirectory);
|
||||
}
|
||||
|
||||
/// <summary><c>tests/fixtures/<name></c> under the repo root.</summary>
|
||||
public static string Fixtures(string name) => Path.Combine(Root(), "tests", "fixtures", name);
|
||||
}
|
||||
}
|
||||
+1
@@ -13,6 +13,7 @@ using AutopilotMonitor.DecisionCore.Classifiers;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Integration
|
||||
{
|
||||
|
||||
@@ -5,6 +5,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using AutopilotMonitor.DecisionCore.Classifiers;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
#pragma warning disable xUnit1031 // SpinWait.SpinUntil for uploader-batch-arrival assertion
|
||||
|
||||
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
|
||||
{
|
||||
/// <summary>
|
||||
/// <see cref="GatherRule.EnrichErrorCodes"/> is an opt-in the backend honours at response time:
|
||||
/// the agent stamps <c>enrichErrorCodes: true</c> into the event data of a rule that set it and
|
||||
/// nothing at all otherwise (the default payload stays as it was).
|
||||
/// </summary>
|
||||
[Collection("SerialThreading")] // startup rules execute on the shared ThreadPool
|
||||
public sealed class GatherRuleExecutorEnrichErrorCodesTests : IDisposable
|
||||
{
|
||||
private readonly TempDirectory _tmp = new TempDirectory();
|
||||
private readonly List<EnrollmentEvent> _events = new List<EnrollmentEvent>();
|
||||
private readonly object _eventsGate = new object();
|
||||
private readonly GatherRuleExecutor _executor;
|
||||
|
||||
private const string AbsentPath =
|
||||
"HKLM\\SOFTWARE\\AutopilotMonitorTests\\DefinitelyAbsent_7e3a1f4b-0000-0000-0000-000000000000";
|
||||
|
||||
public GatherRuleExecutorEnrichErrorCodesTests()
|
||||
{
|
||||
var logger = new AgentLogger(_tmp.Path, AgentLogLevel.Info);
|
||||
_executor = new GatherRuleExecutor(
|
||||
"sess", "tenant",
|
||||
evt => { lock (_eventsGate) _events.Add(evt); },
|
||||
logger)
|
||||
{
|
||||
UnrestrictedMode = true
|
||||
};
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_executor.Dispose();
|
||||
_tmp.Dispose();
|
||||
}
|
||||
|
||||
private EnrollmentEvent SingleEvent()
|
||||
{
|
||||
lock (_eventsGate) return Assert.Single(_events);
|
||||
}
|
||||
|
||||
private bool WaitForEventCount(int count, int timeoutMs = 10000)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
while (sw.ElapsedMilliseconds < timeoutMs)
|
||||
{
|
||||
lock (_eventsGate) if (_events.Count >= count) return true;
|
||||
Thread.Sleep(25);
|
||||
}
|
||||
lock (_eventsGate) return _events.Count >= count;
|
||||
}
|
||||
|
||||
private static GatherRule StartupRule(bool enrichErrorCodes) => new GatherRule
|
||||
{
|
||||
RuleId = "GATHER-EEC-001",
|
||||
Title = "enrich test",
|
||||
CollectorType = "registry",
|
||||
Target = AbsentPath,
|
||||
Trigger = "startup",
|
||||
OutputEventType = "gather_test",
|
||||
Enabled = true,
|
||||
EnrichErrorCodes = enrichErrorCodes,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void StampRuleMarkers_AddsMarkerOnlyWhenOptedIn()
|
||||
{
|
||||
var optedIn = new Dictionary<string, object> { ["exitCode"] = "1603" };
|
||||
GatherRuleExecutor.StampRuleMarkers(StartupRule(enrichErrorCodes: true), optedIn);
|
||||
Assert.Equal(true, optedIn[Constants.GatherRuleDataKeys.EnrichErrorCodes]);
|
||||
|
||||
var defaultRule = new Dictionary<string, object> { ["exitCode"] = "1603" };
|
||||
GatherRuleExecutor.StampRuleMarkers(StartupRule(enrichErrorCodes: false), defaultRule);
|
||||
Assert.False(defaultRule.ContainsKey(Constants.GatherRuleDataKeys.EnrichErrorCodes));
|
||||
Assert.Single(defaultRule);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExecuteRule_StampsMarker_WhenRuleOptsIn()
|
||||
{
|
||||
_executor.UpdateRules(new List<GatherRule> { StartupRule(enrichErrorCodes: true) });
|
||||
|
||||
Assert.True(_executor.WaitForStartupRules(30));
|
||||
Assert.True(WaitForEventCount(1));
|
||||
var evt = SingleEvent();
|
||||
Assert.Equal(GatherRuleExecutor.SourceName, evt.Source);
|
||||
Assert.Equal(true, evt.Data[Constants.GatherRuleDataKeys.EnrichErrorCodes]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExecuteRule_LeavesPayloadUnchanged_ByDefault()
|
||||
{
|
||||
_executor.UpdateRules(new List<GatherRule> { StartupRule(enrichErrorCodes: false) });
|
||||
|
||||
Assert.True(_executor.WaitForStartupRules(30));
|
||||
Assert.True(WaitForEventCount(1));
|
||||
Assert.False(SingleEvent().Data.ContainsKey(Constants.GatherRuleDataKeys.EnrichErrorCodes));
|
||||
}
|
||||
}
|
||||
}
|
||||
+33
@@ -311,6 +311,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
"[Win32App] Admin did NOT set mapping for lpExitCode: 1603 of app: " + Guid1,
|
||||
new[] { "exitCode=1603", "id=" + Guid1 }
|
||||
};
|
||||
// Win32AppInstaller.cs "[Win32App] lpExitCode is defined as {0}", enum AppReturnCodeType
|
||||
// (identical 1.50–1.105).
|
||||
yield return new object[]
|
||||
{
|
||||
"IME-EXITCODE-CLASS",
|
||||
"[Win32App] lpExitCode is defined as SoftReboot",
|
||||
new[] { "exitCodeClass=SoftReboot" }
|
||||
};
|
||||
yield return new object[]
|
||||
{
|
||||
"IME-GRS-SKIP",
|
||||
@@ -361,6 +369,31 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Success")]
|
||||
[InlineData("SoftReboot")]
|
||||
[InlineData("HardReboot")]
|
||||
[InlineData("Retry")]
|
||||
[InlineData("Failed")]
|
||||
public void IME_EXITCODE_CLASS_captures_every_AppReturnCodeType_member(string member)
|
||||
{
|
||||
var m = Compile(Get("IME-EXITCODE-CLASS")).Match("[Win32App] lpExitCode is defined as " + member);
|
||||
Assert.True(m.Success);
|
||||
Assert.Equal(member, m.Groups["exitCodeClass"].Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IME_EXITCODE_CLASS_ignores_the_no_mapping_warning_and_raw_numeric_types()
|
||||
{
|
||||
// The default branch logs "... defined as {0}, fall into default now." and an admin
|
||||
// type outside the enum prints as a raw number; neither is a class the app carries.
|
||||
var regex = Compile(Get("IME-EXITCODE-CLASS"));
|
||||
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode is defined as 5, fall into default now.");
|
||||
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode is defined as SoftReboot, fall into default now.");
|
||||
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode is defined as 5");
|
||||
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode 3010");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PS_SCRIPT_CONTEXT_no_longer_fires_on_Win32App_detection_script_lines()
|
||||
{
|
||||
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Newtonsoft.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// Return-code class of the installer exit code (IME "[Win32App] lpExitCode is defined as
|
||||
/// {AppReturnCodeType}"): captured by the shipped IME-EXITCODE-CLASS pattern into
|
||||
/// <see cref="AppPackageState.ExitCodeClass"/>, last value wins across a Retry loop, the
|
||||
/// no-mapping/default-branch variants are ignored, and the value survives the agent
|
||||
/// restart that a SoftReboot/HardReboot app causes (persistence round trip).
|
||||
/// </summary>
|
||||
public sealed class ImeLogTrackerExitCodeClassTests
|
||||
{
|
||||
private const string AppId = "5c95bf94-1cf4-4629-88d1-3f616e7a405c";
|
||||
|
||||
// ---------------------------------------------------------------- AppPackageState
|
||||
|
||||
[Fact]
|
||||
public void UpdateExitCodeClass_last_value_wins_and_ignores_empty()
|
||||
{
|
||||
var pkg = new AppPackageState(AppId, 0);
|
||||
Assert.Null(pkg.ExitCodeClass);
|
||||
|
||||
Assert.True(pkg.UpdateExitCodeClass("Retry"));
|
||||
Assert.True(pkg.UpdateExitCodeClass(" Success "));
|
||||
Assert.Equal("Success", pkg.ExitCodeClass);
|
||||
Assert.False(pkg.UpdateExitCodeClass("Success"));
|
||||
Assert.False(pkg.UpdateExitCodeClass(""));
|
||||
Assert.False(pkg.UpdateExitCodeClass(null));
|
||||
Assert.Equal("Success", pkg.ExitCodeClass);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToEventData_carries_the_class_only_when_known()
|
||||
{
|
||||
var pkg = new AppPackageState(AppId, 0);
|
||||
Assert.False(pkg.ToEventData().ContainsKey("exitCodeClass"));
|
||||
|
||||
pkg.UpdateExitCode("3010");
|
||||
pkg.UpdateExitCodeClass("SoftReboot");
|
||||
var data = pkg.ToEventData();
|
||||
Assert.Equal("3010", data["exitCode"]);
|
||||
Assert.Equal("SoftReboot", data["exitCodeClass"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Restore_round_trips_the_class()
|
||||
{
|
||||
var pkg = AppPackageState.Restore(
|
||||
AppId, 0, "Contoso VPN",
|
||||
AppRunAs.System, AppIntent.Install, AppTargeted.Device,
|
||||
new HashSet<string>(),
|
||||
AppInstallationState.Installed, true, 100, 0, 0,
|
||||
exitCode: "3010", exitCodeClass: "SoftReboot");
|
||||
|
||||
Assert.Equal("SoftReboot", pkg.ExitCodeClass);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- shipped pack, end to end
|
||||
|
||||
private static string FindRulesPatternDir()
|
||||
{
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (dir != null)
|
||||
{
|
||||
var candidate = Path.Combine(dir.FullName, "rules", "ime-log-patterns");
|
||||
if (Directory.Exists(candidate)) return candidate;
|
||||
dir = dir.Parent;
|
||||
}
|
||||
throw new DirectoryNotFoundException($"Could not locate rules/ime-log-patterns walking up from {AppContext.BaseDirectory}");
|
||||
}
|
||||
|
||||
/// <summary>The shipped pack, exactly as combine.js embeds it (sorted by file name).</summary>
|
||||
private static List<ImeLogPattern> ShippedPack()
|
||||
=> Directory.GetFiles(FindRulesPatternDir(), "*.json")
|
||||
.OrderBy(f => f, StringComparer.Ordinal)
|
||||
.Select(f => JsonConvert.DeserializeObject<ImeLogPattern>(File.ReadAllText(f))!)
|
||||
.ToList();
|
||||
|
||||
private static string Entry(string message, DateTime utcInstant)
|
||||
{
|
||||
// CMTrace line with a zero writer offset: the tracker reads the local time and
|
||||
// resolves it against the reader zone; only freshness (< 24 h) matters here.
|
||||
return $"<![LOG[{message}]LOG]!><time=\"{utcInstant:HH:mm:ss.fffffff}\" date=\"{utcInstant:M-d-yyyy}\" " +
|
||||
"component=\"IntuneManagementExtension\" context=\"\" type=\"1\" thread=\"1\" file=\"\">";
|
||||
}
|
||||
|
||||
private sealed class Harness : IDisposable
|
||||
{
|
||||
private readonly TempDirectory _tmp = new TempDirectory();
|
||||
public ImeLogTracker Tracker { get; }
|
||||
public string StateDir { get; }
|
||||
public DateTime Now { get; } = new DateTime(2026, 9, 6, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
public Harness()
|
||||
{
|
||||
StateDir = Path.Combine(_tmp.Path, "State");
|
||||
Tracker = Build();
|
||||
}
|
||||
|
||||
public ImeLogTracker Build()
|
||||
{
|
||||
var tracker = new ImeLogTracker(
|
||||
logFolder: _tmp.Path,
|
||||
patterns: ShippedPack(),
|
||||
logger: new AgentLogger(_tmp.Path, AgentLogLevel.Info),
|
||||
stateDirectory: StateDir);
|
||||
// The historic-replay guard skips app-mutating actions for lines older than 24 h
|
||||
// relative to "now": pin both so the CMTrace entries below are always fresh.
|
||||
tracker.UtcNowProvider = () => Now;
|
||||
return tracker;
|
||||
}
|
||||
|
||||
public void Append(params string[] messages)
|
||||
{
|
||||
var lines = messages.Select((m, i) => Entry(m, Now.AddSeconds(-60 + i)));
|
||||
File.AppendAllText(Path.Combine(_tmp.Path, "IntuneManagementExtension.log"),
|
||||
string.Join(Environment.NewLine, lines) + Environment.NewLine);
|
||||
}
|
||||
|
||||
public Task Pass() => Tracker.CheckLogFilesAsync(CancellationToken.None);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Tracker.Dispose();
|
||||
_tmp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static string PhaseLine => "[Win32App] In EspPhase: DeviceSetup.";
|
||||
private static string CurrentAppLine => @"[Win32App] SetCurrentDirectory: C:\Windows\IMECache\" + AppId + "_1";
|
||||
|
||||
[Fact]
|
||||
public async Task Shipped_pattern_captures_the_class_for_the_current_app()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
|
||||
h.Append(
|
||||
PhaseLine, // activates the currentPhase pack (IME-EXITCODE, IME-EXITCODE-CLASS)
|
||||
CurrentAppLine, // IME-SET-CURRENT-4 → current app
|
||||
"[Win32App] lpExitCode 3010",
|
||||
"[Win32App] lpExitCode is defined as SoftReboot");
|
||||
|
||||
await h.Pass();
|
||||
|
||||
var pkg = h.Tracker.PackageStates.GetPackage(AppId);
|
||||
Assert.NotNull(pkg);
|
||||
Assert.Equal("3010", pkg!.ExitCode);
|
||||
Assert.Equal("SoftReboot", pkg.ExitCodeClass);
|
||||
Assert.NotEqual(AppInstallationState.Error, pkg.InstallationState);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Retry_loop_that_ends_in_success_reports_the_last_class()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
|
||||
h.Append(
|
||||
PhaseLine, CurrentAppLine,
|
||||
"[Win32App] lpExitCode 1618",
|
||||
"[Win32App] lpExitCode is defined as Retry",
|
||||
"[Win32App] lpExitCode 1618",
|
||||
"[Win32App] lpExitCode is defined as Retry",
|
||||
"[Win32App] lpExitCode 0",
|
||||
"[Win32App] lpExitCode is defined as Success");
|
||||
|
||||
await h.Pass();
|
||||
|
||||
var pkg = h.Tracker.PackageStates.GetPackage(AppId)!;
|
||||
Assert.Equal("0", pkg.ExitCode);
|
||||
Assert.Equal("Success", pkg.ExitCodeClass);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Failed_class_still_drives_the_error_transition_and_carries_the_class()
|
||||
{
|
||||
// IME-EXITCODE-CLASS and IME-EXITCODE-MAPPED-FAILED both match the Failed line: the
|
||||
// class is captured and the existing error path stays intact.
|
||||
using var h = new Harness();
|
||||
var pkg = new AppPackageState(AppId, 0);
|
||||
pkg.UpdateState(AppInstallationState.Installing);
|
||||
h.Tracker.PackageStates.Add(pkg);
|
||||
h.Append(
|
||||
PhaseLine, CurrentAppLine,
|
||||
"[Win32App] lpExitCode 1603",
|
||||
"[Win32App] lpExitCode is defined as Failed");
|
||||
|
||||
await h.Pass();
|
||||
|
||||
Assert.Equal(AppInstallationState.Error, pkg.InstallationState);
|
||||
Assert.Equal("Failed", pkg.ExitCodeClass);
|
||||
Assert.Equal("IME-EXITCODE-MAPPED-FAILED", pkg.ErrorPatternId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Default_branch_and_raw_numeric_types_leave_the_class_unset()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
|
||||
h.Append(
|
||||
PhaseLine, CurrentAppLine,
|
||||
"[Win32App] lpExitCode 5",
|
||||
"[Win32App] lpExitCode is defined as 5",
|
||||
"[Win32App] lpExitCode is defined as 5, fall into default now.",
|
||||
"[Win32App] Setting enforcementState as: Error with lpExitCode: 5 without mapping");
|
||||
|
||||
await h.Pass();
|
||||
|
||||
var pkg = h.Tracker.PackageStates.GetPackage(AppId)!;
|
||||
Assert.Equal("5", pkg.ExitCode);
|
||||
Assert.Null(pkg.ExitCodeClass);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Class_survives_the_state_round_trip_of_an_agent_restart()
|
||||
{
|
||||
// A SoftReboot/HardReboot app completes only after the reboot; the restarted agent
|
||||
// must still know the class when the post-reboot Success line arrives.
|
||||
using var h = new Harness();
|
||||
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
|
||||
h.Append(
|
||||
PhaseLine, CurrentAppLine,
|
||||
"[Win32App] lpExitCode 1641",
|
||||
"[Win32App] lpExitCode is defined as HardReboot");
|
||||
await h.Pass();
|
||||
h.Tracker.SaveStateForTest();
|
||||
|
||||
using var restarted = h.Build();
|
||||
restarted.LoadStateForTest();
|
||||
|
||||
var pkg = restarted.GetAllKnownPackageStates().Single(p => p.Id == AppId);
|
||||
Assert.Equal("1641", pkg.ExitCode);
|
||||
Assert.Equal("HardReboot", pkg.ExitCodeClass);
|
||||
}
|
||||
}
|
||||
}
|
||||
+82
@@ -903,5 +903,87 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Runtime
|
||||
NtfsLinks.RemoveLink(link);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================= packaging counters
|
||||
|
||||
[Fact]
|
||||
public void BuildArchiveBytes_records_packaging_counters_by_reason_and_kind_without_paths()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
File.WriteAllText(Path.Combine(rig.StateFolder, "small.json"), "{}");
|
||||
File.WriteAllText(Path.Combine(rig.StateFolder, "big-1.json"), new string('x', 64));
|
||||
File.WriteAllText(Path.Combine(rig.StateFolder, "big-2.json"), new string('y', 64));
|
||||
var blockedPath = @"C:\Windows\System32\config\SYSTEM";
|
||||
|
||||
var service = rig.Build(cfg => cfg.DiagnosticsLogPaths.Add(
|
||||
new AutopilotMonitor.Shared.Models.DiagnosticsLogPath { Path = blockedPath }));
|
||||
service.Budget = new DiagnosticsBudget { MaxSingleFileBytes = 16, MaxTotalUncompressedBytes = 1L << 30, MaxFileCount = 5000 };
|
||||
|
||||
Assert.Null(service.LastPackaging);
|
||||
var bytes = service.BuildArchiveBytes(enrollmentSucceeded: true);
|
||||
|
||||
var stats = service.LastPackaging;
|
||||
Assert.NotNull(stats);
|
||||
Assert.True(stats!.Truncated);
|
||||
Assert.Equal(2, stats.SkippedFiles);
|
||||
Assert.Equal(2, stats.SkippedByReason["size"]);
|
||||
Assert.Single(stats.SkippedByReason);
|
||||
Assert.Equal(1, stats.ProblemsByKind["path-guard"]);
|
||||
Assert.Single(stats.ProblemsByKind);
|
||||
Assert.True(stats.IncludedFiles >= 1, "the small file must have been included");
|
||||
Assert.True(stats.IncludedBytes >= 2);
|
||||
|
||||
// The ZIP still carries the per-file list; the counters never do.
|
||||
Assert.NotNull(ReadZipEntryText(bytes, "_TRUNCATED.txt"));
|
||||
foreach (var key in stats.SkippedByReason.Keys.Concat(stats.ProblemsByKind.Keys))
|
||||
{
|
||||
Assert.DoesNotContain("\\", key);
|
||||
Assert.DoesNotContain(":", key);
|
||||
Assert.DoesNotContain("/", key);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildArchiveBytes_reports_a_clean_build_as_not_truncated_with_empty_maps()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
File.WriteAllText(Path.Combine(rig.StateFolder, "snapshot.json"), "{}");
|
||||
|
||||
var service = rig.Build();
|
||||
service.BuildArchiveBytes(enrollmentSucceeded: true);
|
||||
|
||||
var stats = service.LastPackaging;
|
||||
Assert.NotNull(stats);
|
||||
Assert.False(stats!.Truncated);
|
||||
Assert.Equal(0, stats.SkippedFiles);
|
||||
Assert.Empty(stats.SkippedByReason);
|
||||
Assert.Empty(stats.ProblemsByKind);
|
||||
Assert.True(stats.IncludedFiles >= 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildArchiveBytes_counts_a_rejected_source_folder_as_a_problem()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
using var outside = new TempDirectory();
|
||||
File.WriteAllText(Path.Combine(outside.Path, "snapshot.json"), "{}");
|
||||
var link = Path.Combine(rig.Tmp.Path, "StateLink");
|
||||
NtfsLinks.CreateJunction(link, outside.Path);
|
||||
|
||||
try
|
||||
{
|
||||
var service = rig.Build(sectionFolderOverrides: new Dictionary<string, string> { ["AgentState"] = link });
|
||||
service.BuildArchiveBytes(enrollmentSucceeded: true);
|
||||
|
||||
// The section is walked once per search pattern (11 patterns) but the folder
|
||||
// failed once — the counter says so.
|
||||
Assert.Equal(1, service.LastPackaging!.ProblemsByKind["folder-rejected"]);
|
||||
Assert.False(service.LastPackaging.Truncated);
|
||||
}
|
||||
finally
|
||||
{
|
||||
NtfsLinks.RemoveLink(link);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+16
-5
@@ -243,12 +243,23 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecodeHResult_KnownAndUnknown()
|
||||
public void ResolveHResultSymbol_ReadsTheSharedCatalog()
|
||||
{
|
||||
Assert.Equal("WU_E_ALL_UPDATES_FAILED", WindowsUpdateTracker.DecodeHResult(0x80240022));
|
||||
Assert.Equal("CBS_E_INSTALLERS_FAILED", WindowsUpdateTracker.DecodeHResult(0x800F0922));
|
||||
Assert.Equal("S_OK", WindowsUpdateTracker.DecodeHResult(0x00000000));
|
||||
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.DecodeHResult(0x8888DEAD));
|
||||
Assert.Equal("WU_E_ALL_UPDATES_FAILED", WindowsUpdateTracker.ResolveHResultSymbol(0x80240022));
|
||||
Assert.Equal("CBS_E_INSTALLERS_FAILED", WindowsUpdateTracker.ResolveHResultSymbol(0x800F0922));
|
||||
Assert.Equal("ERROR_TIMEOUT", WindowsUpdateTracker.ResolveHResultSymbol(0x800705B4));
|
||||
Assert.Equal("S_OK", WindowsUpdateTracker.ResolveHResultSymbol(0x00000000));
|
||||
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.ResolveHResultSymbol(0x8888DEAD));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveHResultSymbol_FallsBackWhenTheCatalogHasNoSymbolOrThrows()
|
||||
{
|
||||
// An entry without a symbol (IME/Intune paraphrases) still yields the sentinel.
|
||||
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.ResolveHResultSymbol(0x87D1041C));
|
||||
// A catalog load failure is decoration lost, never an event lost.
|
||||
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.ResolveHResultSymbol(0x80240022, _ => throw new InvalidOperationException("catalog")));
|
||||
Assert.Equal("S_OK", WindowsUpdateTracker.ResolveHResultSymbol(0, _ => throw new InvalidOperationException("catalog")));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
+1
@@ -11,6 +11,7 @@ using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
{
|
||||
|
||||
+3
-2
@@ -8,6 +8,7 @@ using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
#pragma warning disable xUnit1031
|
||||
|
||||
@@ -42,7 +43,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
// items must be a whiteglove_resumed event.
|
||||
Assert.DoesNotContain(
|
||||
rig.Uploader.Received.SelectMany(b => b),
|
||||
item => item.Kind == AutopilotMonitor.Agent.V2.Core.Transport.Telemetry.TelemetryItemKind.Event &&
|
||||
item => item.Kind == TelemetryItemKind.Event &&
|
||||
item.PayloadJson != null &&
|
||||
item.PayloadJson.Contains("\"whiteglove_resumed\""));
|
||||
}
|
||||
@@ -75,7 +76,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
var resumedEvents = rig.Uploader.Received
|
||||
.SelectMany(b => b)
|
||||
.Where(item =>
|
||||
item.Kind == AutopilotMonitor.Agent.V2.Core.Transport.Telemetry.TelemetryItemKind.Event &&
|
||||
item.Kind == TelemetryItemKind.Event &&
|
||||
item.PayloadJson != null &&
|
||||
item.PayloadJson.Contains("\"whiteglove_resumed\""))
|
||||
.ToList();
|
||||
|
||||
@@ -15,6 +15,7 @@ using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
#pragma warning disable xUnit1031
|
||||
|
||||
|
||||
+1
@@ -9,6 +9,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
#pragma warning disable xUnit1031
|
||||
|
||||
|
||||
+10
-1
@@ -282,8 +282,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
errorPatternId: null,
|
||||
errorDetail: null,
|
||||
errorCode: null,
|
||||
exitCode: null,
|
||||
exitCode: "0",
|
||||
hresultFromWin32: null,
|
||||
exitCodeClass: "Success",
|
||||
appVersion: "11.2.1787.0",
|
||||
appType: "WinGet",
|
||||
attemptNumber: 1,
|
||||
@@ -293,6 +294,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
|
||||
var info = Assert.Single(f.InfoEvents(SharedEventTypes.AppInstallComplete));
|
||||
Assert.Equal("app-xyz", info.Payload!["appId"]);
|
||||
// Installer outcome surfaces on the terminal event even when the app succeeded: the
|
||||
// return-code class is the only evidence of a SoftReboot/HardReboot mapping and the
|
||||
// number says which code was mapped (IME-EXITCODE-CLASS, ANALYZE-APP-018).
|
||||
Assert.Equal("Success", info.Payload["exitCodeClass"]);
|
||||
Assert.Equal("0", info.Payload["exitCode"]);
|
||||
Assert.Equal("Company Portal", info.Payload["appName"]);
|
||||
Assert.Equal("Installed", info.Payload["state"]);
|
||||
Assert.Equal("Install", info.Payload["intent"]);
|
||||
@@ -331,6 +337,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
errorCode: "60001",
|
||||
exitCode: "60001",
|
||||
hresultFromWin32: "-2146964895",
|
||||
exitCodeClass: "Failed",
|
||||
attemptNumber: 1,
|
||||
detectionResult: "NotDetected");
|
||||
|
||||
@@ -340,6 +347,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
Assert.Equal("true", info.Payload!["isError"]);
|
||||
Assert.Equal("IME-ERROR-UNMAPPED-EXIT", info.Payload["errorPatternId"]);
|
||||
Assert.Equal("60001", info.Payload["errorCode"]);
|
||||
Assert.Equal("60001", info.Payload["exitCode"]);
|
||||
Assert.Equal("Failed", info.Payload["exitCodeClass"]);
|
||||
Assert.Equal("-2146964895", info.Payload["hresultFromWin32"]);
|
||||
Assert.Equal(EventSeverity.Error.ToString(), info.Payload[SignalPayloadKeys.Severity]);
|
||||
// Codex review follow-up (P1): an unrelated ErrorPatternId (here a regular
|
||||
|
||||
+1
@@ -5,6 +5,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Telemetry.Signals
|
||||
{
|
||||
|
||||
+1
@@ -8,6 +8,7 @@ using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Telemetry.Transitions
|
||||
{
|
||||
|
||||
+81
@@ -1701,5 +1701,86 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Termination
|
||||
rig.PromotionCalls[0].failureType);
|
||||
Assert.Null(rig.PromotionCalls[0].errorCode);
|
||||
}
|
||||
|
||||
// ============================================================= packaging counters on the diag events
|
||||
|
||||
[Fact]
|
||||
public void Handle_diagnostics_uploaded_carries_packaging_counters_when_the_packager_reported_them()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Completed }.Build();
|
||||
rig.DiagnosticsResult = new DiagnosticsUploadResult
|
||||
{
|
||||
BlobName = "diag-blob.zip",
|
||||
Packaging = new DiagnosticsPackagingStats
|
||||
{
|
||||
IncludedFiles = 412,
|
||||
IncludedBytes = 123456,
|
||||
SkippedFiles = 3,
|
||||
SkippedByReason = new Dictionary<string, int> { ["size"] = 2, ["total"] = 1 },
|
||||
ProblemsByKind = new Dictionary<string, int> { ["copy"] = 1 },
|
||||
},
|
||||
};
|
||||
var cfg = rig.BuildConfig(diagEnabled: true, diagMode: "Always", selfDestruct: false);
|
||||
|
||||
rig.Build(cfg).Handle(sender: null!,
|
||||
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Succeeded, SessionStage.Completed));
|
||||
|
||||
var uploaded = rig.DataOf("diagnostics_uploaded");
|
||||
Assert.NotNull(uploaded);
|
||||
Assert.Equal(true, uploaded!["truncated"]);
|
||||
Assert.Equal(412, uploaded["includedFiles"]);
|
||||
Assert.Equal(123456L, uploaded["includedBytes"]);
|
||||
Assert.Equal(3, uploaded["skippedFiles"]);
|
||||
var byReason = Assert.IsType<Dictionary<string, int>>(uploaded["skippedByReason"]);
|
||||
Assert.Equal(2, byReason["size"]);
|
||||
Assert.Equal(1, byReason["total"]);
|
||||
var problems = Assert.IsType<Dictionary<string, int>>(uploaded["problemsByKind"]);
|
||||
Assert.Equal(1, problems["copy"]);
|
||||
// Counters only — no key or value carries a file path.
|
||||
foreach (var kv in uploaded)
|
||||
Assert.False(kv.Value is string s && (s.Contains("\\") || s.Contains("/")) && kv.Key != "sasUrlPrefix",
|
||||
$"payload key {kv.Key} looks like a path: {kv.Value}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handle_diagnostics_upload_failed_after_a_build_carries_the_counters_too()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Failed }.Build();
|
||||
rig.DiagnosticsResult = new DiagnosticsUploadResult
|
||||
{
|
||||
ErrorCode = "upload_5xx",
|
||||
Packaging = new DiagnosticsPackagingStats { IncludedFiles = 40, IncludedBytes = 1000 },
|
||||
};
|
||||
var cfg = rig.BuildConfig(diagEnabled: true, diagMode: "Always", selfDestruct: false);
|
||||
|
||||
rig.Build(cfg).Handle(sender: null!,
|
||||
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Failed, SessionStage.Failed));
|
||||
|
||||
var failed = rig.DataOf("diagnostics_upload_failed");
|
||||
Assert.NotNull(failed);
|
||||
Assert.Equal("upload_5xx", (string)failed!["errorCode"]);
|
||||
Assert.Equal(false, failed["truncated"]);
|
||||
Assert.Equal(40, failed["includedFiles"]);
|
||||
Assert.Empty(Assert.IsType<Dictionary<string, int>>(failed["skippedByReason"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handle_diagnostics_events_omit_the_counters_when_no_package_was_built()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Completed }.Build();
|
||||
rig.DiagnosticsResult = new DiagnosticsUploadResult { BlobName = "diag-blob.zip" };
|
||||
var cfg = rig.BuildConfig(diagEnabled: true, diagMode: "Always", selfDestruct: false);
|
||||
|
||||
rig.Build(cfg).Handle(sender: null!,
|
||||
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Succeeded, SessionStage.Completed));
|
||||
|
||||
var uploaded = rig.DataOf("diagnostics_uploaded");
|
||||
Assert.NotNull(uploaded);
|
||||
Assert.False(uploaded!.ContainsKey("truncated"));
|
||||
Assert.False(uploaded.ContainsKey("skippedByReason"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -6,6 +6,7 @@ using System.Net.Http;
|
||||
using System.Threading;
|
||||
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
|
||||
{
|
||||
|
||||
+1
@@ -8,6 +8,7 @@ using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
|
||||
{
|
||||
|
||||
+1
@@ -7,6 +7,7 @@ using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
|
||||
{
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.Text;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
|
||||
{
|
||||
|
||||
+1
@@ -4,6 +4,7 @@ using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
|
||||
{
|
||||
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Agent.V2.Core.Telemetry.Events;
|
||||
using AutopilotMonitor.Agent.V2.Core.Telemetry.Signals;
|
||||
using AutopilotMonitor.Agent.V2.Core.Telemetry.Transitions;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Telemetry.Events;
|
||||
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
|
||||
{
|
||||
/// <summary>
|
||||
/// The agent → backend wire contract of <c>POST /api/agent/telemetry</c>, proven from the
|
||||
/// WRITER side. <see cref="TelemetryItemDto"/> (Shared) is the one class both ends serialise;
|
||||
/// <see cref="TelemetryItem.ToWire"/> is the only mapping onto it.
|
||||
/// <list type="bullet">
|
||||
/// <item>Round trip + reflection: every DTO property is populated by <c>ToWire()</c> and
|
||||
/// survives Newtonsoft defaults — a DTO field added without a mapping fails here.</item>
|
||||
/// <item>Frozen body: the real batch serialiser's output for one item per
|
||||
/// <see cref="TelemetryItemKind"/> is pinned under <c>tests/fixtures/telemetry-wire/</c>.
|
||||
/// The backend's <c>TelemetryWireFixtureTests</c> reads the same files and demands zero
|
||||
/// rejections, so a rename on either side breaks a test until both sides and the fixture
|
||||
/// agree. Regenerate with <c>AM_WRITE_WIRE_FIXTURES=1</c>.</item>
|
||||
/// <item>Poison body: the exact 422 shape the backend writes (pinned there by
|
||||
/// <c>TelemetryWireFixtureTests</c>) is parsed as an item-level poison signal here.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public sealed class TelemetryWireContractTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "b2c3d4e5-f6a7-8901-bcde-f12345678901";
|
||||
private const string FixtureFile = "agent-v2.json";
|
||||
|
||||
private static readonly DateTime At = new DateTime(2026, 4, 20, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private static TelemetryItem FullyPopulatedItem() =>
|
||||
new TelemetryItem(
|
||||
kind: TelemetryItemKind.DecisionTransition,
|
||||
partitionKey: $"{TenantId}_{SessionId}",
|
||||
rowKey: "0000000007",
|
||||
telemetryItemId: 42,
|
||||
sessionTraceOrdinal: 7,
|
||||
payloadJson: "{\"StepIndex\":7}",
|
||||
requiresImmediateFlush: true,
|
||||
enqueuedAtUtc: At,
|
||||
retryCount: 3);
|
||||
|
||||
// ============================================================ ToWire mapping
|
||||
|
||||
[Fact]
|
||||
public void ToWire_round_trips_every_property_through_Newtonsoft_defaults()
|
||||
{
|
||||
var item = FullyPopulatedItem();
|
||||
|
||||
var json = JsonConvert.SerializeObject(item.ToWire());
|
||||
var dto = JsonConvert.DeserializeObject<TelemetryItemDto>(json)!;
|
||||
|
||||
Assert.Equal("DecisionTransition", dto.Kind);
|
||||
Assert.Equal(item.PartitionKey, dto.PartitionKey);
|
||||
Assert.Equal(item.RowKey, dto.RowKey);
|
||||
Assert.Equal(item.TelemetryItemId, dto.TelemetryItemId);
|
||||
Assert.Equal(item.SessionTraceOrdinal, dto.SessionTraceOrdinal);
|
||||
Assert.Equal(item.PayloadJson, dto.PayloadJson);
|
||||
Assert.Equal(item.RequiresImmediateFlush, dto.RequiresImmediateFlush);
|
||||
Assert.Equal(item.EnqueuedAtUtc, dto.EnqueuedAtUtc);
|
||||
Assert.Equal(DateTimeKind.Utc, dto.EnqueuedAtUtc.Kind);
|
||||
Assert.Equal(item.RetryCount, dto.RetryCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToWire_populates_every_TelemetryItemDto_property()
|
||||
{
|
||||
// A DTO property that ToWire() does not set keeps its default — this catches a field
|
||||
// added to the wire type without a mapping (the backend would read the default forever).
|
||||
var dto = FullyPopulatedItem().ToWire();
|
||||
|
||||
var unset = typeof(TelemetryItemDto)
|
||||
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Where(p => IsDefault(p.GetValue(dto), p.PropertyType))
|
||||
.Select(p => p.Name)
|
||||
.ToList();
|
||||
|
||||
Assert.True(unset.Count == 0,
|
||||
"TelemetryItem.ToWire() leaves these TelemetryItemDto properties at their default: " + string.Join(", ", unset));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TelemetryItemDto_properties_mirror_TelemetryItem()
|
||||
{
|
||||
var itemProps = typeof(TelemetryItem).GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.ToDictionary(p => p.Name, p => p.PropertyType);
|
||||
|
||||
foreach (var dtoProp in typeof(TelemetryItemDto).GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
Assert.True(itemProps.TryGetValue(dtoProp.Name, out var itemType),
|
||||
$"TelemetryItemDto.{dtoProp.Name} has no counterpart on TelemetryItem");
|
||||
var expected = dtoProp.Name == nameof(TelemetryItemDto.Kind) ? typeof(TelemetryItemKind) : dtoProp.PropertyType;
|
||||
Assert.True(itemType == expected,
|
||||
$"TelemetryItemDto.{dtoProp.Name} is {dtoProp.PropertyType.Name}, TelemetryItem.{dtoProp.Name} is {itemType.Name}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Every_kind_serialises_by_name_on_the_wire_and_on_the_spool_line()
|
||||
{
|
||||
foreach (var kind in TelemetryItemKinds.All)
|
||||
{
|
||||
var item = new TelemetryItem(kind, "T_S", "rk", 1, 1, "{}", false, At);
|
||||
|
||||
var wire = JObject.Parse(JsonConvert.SerializeObject(item.ToWire()));
|
||||
Assert.Equal(kind.ToString(), (string?)wire["Kind"]);
|
||||
|
||||
// The spool line (TelemetryItemSerializer) has always written the NAME too; the enum's
|
||||
// move to Shared must not turn it into an ordinal (a crash-restart rehydrates it).
|
||||
var spool = JObject.Parse(TelemetryItemSerializer.Serialize(item));
|
||||
Assert.Equal(kind.ToString(), (string?)spool["Kind"]);
|
||||
Assert.Equal(kind, TelemetryItemSerializer.Deserialize(spool.ToString(Formatting.None)).Kind);
|
||||
|
||||
Assert.True(TelemetryItemKinds.TryParse(kind.ToString(), out var parsed));
|
||||
Assert.Equal(kind, parsed);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================ Frozen wire body
|
||||
|
||||
[Fact]
|
||||
public void Frozen_wire_body_matches_the_current_serializer()
|
||||
{
|
||||
var items = OneItemPerKind();
|
||||
Assert.Equal(TelemetryItemKinds.All.OrderBy(k => k), items.Select(i => i.Kind).Distinct().OrderBy(k => k));
|
||||
|
||||
var body = BackendTelemetryUploader.SerializeBatch(items);
|
||||
var path = Path.Combine(RepoPaths.Fixtures("telemetry-wire"), FixtureFile);
|
||||
|
||||
if (Environment.GetEnvironmentVariable("AM_WRITE_WIRE_FIXTURES") == "1")
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.WriteAllText(path, body + "\n", new UTF8Encoding(false));
|
||||
}
|
||||
|
||||
Assert.True(File.Exists(path), "Missing wire fixture " + path + " — run this test with AM_WRITE_WIRE_FIXTURES=1 to create it.");
|
||||
var frozen = File.ReadAllText(path).TrimEnd('\r', '\n');
|
||||
Assert.True(string.Equals(frozen, body, StringComparison.Ordinal),
|
||||
"The agent's telemetry wire body changed. If the change is intended, update the backend ingest " +
|
||||
"(TelemetryWireFixtureTests must still dispatch every frozen body) and regenerate with " +
|
||||
"AM_WRITE_WIRE_FIXTURES=1.\nExpected: " + frozen + "\nActual: " + body);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One item per kind through the REAL emitters (payload shapes are theirs, not hand-typed),
|
||||
/// re-based onto fixed transport fields so the body is byte-stable.
|
||||
/// </summary>
|
||||
private static IReadOnlyList<TelemetryItem> OneItemPerKind()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
var transport = new FakeTelemetryTransport();
|
||||
var counter = new EventSequenceCounter(new EventSequencePersistence(tmp.File("seq.json")));
|
||||
|
||||
new TelemetryEventEmitter(transport, counter, SessionId, TenantId).Emit(new EnrollmentEvent
|
||||
{
|
||||
EventId = "00000000-0000-4000-8000-000000000001",
|
||||
EventType = Constants.EventTypes.AgentStarted,
|
||||
Severity = EventSeverity.Info,
|
||||
Source = "Agent",
|
||||
Timestamp = At,
|
||||
Phase = EnrollmentPhase.Unknown,
|
||||
Message = "Agent started",
|
||||
Data = new Dictionary<string, object> { ["agentVersion"] = "2.0.0" },
|
||||
});
|
||||
|
||||
new TelemetrySignalEmitter(transport, SessionId, TenantId).Emit(new DecisionSignal(
|
||||
sessionSignalOrdinal: 1,
|
||||
sessionTraceOrdinal: 1,
|
||||
kind: DecisionSignalKind.SessionStarted,
|
||||
kindSchemaVersion: 1,
|
||||
occurredAtUtc: At,
|
||||
sourceOrigin: "Fixture",
|
||||
evidence: new Evidence(EvidenceKind.Raw, "raw-1", "session start")));
|
||||
|
||||
new TelemetryTransitionEmitter(transport, SessionId, TenantId).Emit(new DecisionTransition(
|
||||
stepIndex: 1,
|
||||
sessionTraceOrdinal: 2,
|
||||
signalOrdinalRef: 1,
|
||||
occurredAtUtc: At,
|
||||
trigger: "SessionStarted",
|
||||
fromStage: SessionStage.Unknown,
|
||||
toStage: SessionStage.AwaitingEspPhaseChange,
|
||||
taken: true,
|
||||
deadEndReason: null,
|
||||
reducerVersion: "1.0.0"));
|
||||
|
||||
return transport.Enqueued
|
||||
.Select(e => new TelemetryItem(e.Kind, e.PartitionKey, e.RowKey, e.TelemetryItemId, e.SessionTraceOrdinal,
|
||||
e.PayloadJson, e.RequiresImmediateFlush, At))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
// ============================================================ Poison body
|
||||
|
||||
/// <summary>
|
||||
/// The exact 422 body the backend writes for rejected items (pinned byte-for-byte in the
|
||||
/// backend's TelemetryWireFixtureTests). camelCase because the backend serialises with
|
||||
/// its wire options; the agent's parser accepts both casings.
|
||||
/// </summary>
|
||||
internal const string BackendPoisonBody =
|
||||
"{\"error\":\"2 of 3 telemetry item(s) cannot be ingested (unknown Kind or unusable payload); they were not stored.\"," +
|
||||
"\"code\":\"TelemetryItemsRejected\",\"correlationId\":\"cid-1\",\"poison\":true,\"rejectedRowKeys\":[\"rk-1\",\"rk-3\"]," +
|
||||
"\"reason\":\"unknown_kind=1;unparseable=1\",\"received\":3,\"rejected\":2}";
|
||||
|
||||
[Fact]
|
||||
public async Task Backend_422_poison_body_is_parsed_as_item_level_poison()
|
||||
{
|
||||
using var handler = new RecordingHttpMessageHandler().QueueStatus((HttpStatusCode)422, BackendPoisonBody);
|
||||
using var http = new HttpClient(handler);
|
||||
var sut = new BackendTelemetryUploader(http, baseUrl: "https://backend.example.invalid", tenantId: TenantId, agentVersion: "2.0.0");
|
||||
|
||||
var result = await sut.UploadBatchAsync(new[] { FullyPopulatedItem() }, CancellationToken.None);
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.True(result.IsPoison);
|
||||
Assert.Equal(new[] { "rk-1", "rk-3" }, result.PoisonRowKeys);
|
||||
Assert.Equal("unknown_kind=1;unparseable=1", result.ErrorReason);
|
||||
}
|
||||
|
||||
private static bool IsDefault(object? value, Type type)
|
||||
{
|
||||
if (value == null) return true;
|
||||
if (type == typeof(string)) return ((string)value).Length == 0;
|
||||
var underlying = Nullable.GetUnderlyingType(type) ?? type;
|
||||
return underlying.IsValueType && value.Equals(Activator.CreateInstance(underlying));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// Installer result codes (captured from lpExitCode / hResultFromWin32 log lines)
|
||||
public string ExitCode { get; private set; }
|
||||
public string HResultFromWin32 { get; private set; }
|
||||
/// <summary>
|
||||
/// Admin-defined return-code class of the last installer exit code: Success, SoftReboot,
|
||||
/// HardReboot, Retry or Failed (IME's AppReturnCodeType, captured from the
|
||||
/// "lpExitCode is defined as X" line by IME-EXITCODE-CLASS). Last value wins, so a Retry
|
||||
/// loop that ends in Success reports Success.
|
||||
/// </summary>
|
||||
public string ExitCodeClass { get; private set; }
|
||||
|
||||
// App metadata (captured from IME log patterns — used by App Dashboard / reports)
|
||||
/// <summary>Product version detected after install (e.g. "11.2.1787.0"). From ReportingManager DetectedIdentityVersion.</summary>
|
||||
@@ -167,6 +174,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
int? progressPercent, long bytesDownloaded, long bytesTotal,
|
||||
string errorPatternId = null, string errorDetail = null, string errorCode = null,
|
||||
string exitCode = null, string hresultFromWin32 = null,
|
||||
string exitCodeClass = null,
|
||||
long doFileSize = 0, long doTotalBytesDownloaded = 0,
|
||||
long doBytesFromPeers = 0, int doPercentPeerCaching = 0,
|
||||
long doBytesFromLanPeers = 0, long doBytesFromGroupPeers = 0,
|
||||
@@ -195,6 +203,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
ErrorCode = errorCode,
|
||||
ExitCode = exitCode,
|
||||
HResultFromWin32 = hresultFromWin32,
|
||||
ExitCodeClass = exitCodeClass,
|
||||
InstallationStateLastChangedTicks = Stopwatch.GetTimestamp(),
|
||||
DoFileSize = doFileSize,
|
||||
DoTotalBytesDownloaded = doTotalBytesDownloaded,
|
||||
@@ -302,6 +311,19 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
HResultFromWin32 = code;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Captures the return-code class (Success/SoftReboot/HardReboot/Retry/Failed) IME assigned
|
||||
/// to the last exit code. Last value wins; empty values are ignored.
|
||||
/// </summary>
|
||||
public bool UpdateExitCodeClass(string exitCodeClass)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(exitCodeClass)) return false;
|
||||
var trimmed = exitCodeClass.Trim();
|
||||
if (ExitCodeClass == trimmed) return false;
|
||||
ExitCodeClass = trimmed;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the product version detected for this app (e.g. "11.2.1787.0").
|
||||
/// Only applies non-empty values so a later detection without version cannot wipe it.
|
||||
@@ -547,6 +569,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
data["exitCode"] = ExitCode;
|
||||
if (!string.IsNullOrEmpty(HResultFromWin32))
|
||||
data["hresultFromWin32"] = HResultFromWin32;
|
||||
if (!string.IsNullOrEmpty(ExitCodeClass))
|
||||
data["exitCodeClass"] = ExitCodeClass;
|
||||
|
||||
// App metadata fields (emitted whenever available so ingest can merge them).
|
||||
if (!string.IsNullOrEmpty(AppVersion))
|
||||
|
||||
+10
-1
@@ -491,7 +491,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
"imeshutdown", "espphasedetected", "setcurrentapp",
|
||||
"updatestateinstalled", "updatestatedownloading", "updatestateinstalling",
|
||||
"updatestateskipped", "updatestateerror", "updatestatepostponed",
|
||||
"captureexitcode", "capturehresult", "captureappversion",
|
||||
"captureexitcode", "capturehresult", "captureexitcodeclass", "captureappversion",
|
||||
"captureapptypewinget", "captureapptypemsi", "captureattemptnumber",
|
||||
"capturedetectionresult", "esptrackstatus", "policiesdiscovered",
|
||||
"ignorecompletedapp", "updatename", "updatewin32appstate",
|
||||
@@ -715,6 +715,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
_packageStates.GetPackage(_packageStates.CurrentPackageId)?.UpdateHResult(hresultVal);
|
||||
break;
|
||||
|
||||
case "captureexitcodeclass":
|
||||
// Return-code class of the exit code captured just before (IME logs the
|
||||
// number, then "lpExitCode is defined as <class>"). Same current-app
|
||||
// addressing as captureExitCode; last value wins across a Retry loop.
|
||||
var exitCodeClassVal = match.Groups["exitCodeClass"]?.Value;
|
||||
if (!string.IsNullOrEmpty(exitCodeClassVal) && !string.IsNullOrEmpty(_packageStates.CurrentPackageId))
|
||||
_packageStates.GetPackage(_packageStates.CurrentPackageId)?.UpdateExitCodeClass(exitCodeClassVal);
|
||||
break;
|
||||
|
||||
case "captureappversion":
|
||||
var appVersionVal = match.Groups["appVersion"]?.Value;
|
||||
if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(appVersionVal))
|
||||
|
||||
@@ -1241,6 +1241,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
ErrorCode = p.ErrorCode,
|
||||
ExitCode = p.ExitCode,
|
||||
HResultFromWin32 = p.HResultFromWin32,
|
||||
ExitCodeClass = p.ExitCodeClass,
|
||||
DoFileSize = p.DoFileSize,
|
||||
DoTotalBytesDownloaded = p.DoTotalBytesDownloaded,
|
||||
DoBytesFromPeers = p.DoBytesFromPeers,
|
||||
@@ -1270,6 +1271,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
p.ProgressPercent, p.BytesDownloaded, p.BytesTotal,
|
||||
errorPatternId: p.ErrorPatternId, errorDetail: p.ErrorDetail, errorCode: p.ErrorCode,
|
||||
exitCode: p.ExitCode, hresultFromWin32: p.HResultFromWin32,
|
||||
exitCodeClass: p.ExitCodeClass,
|
||||
doFileSize: p.DoFileSize, doTotalBytesDownloaded: p.DoTotalBytesDownloaded,
|
||||
doBytesFromPeers: p.DoBytesFromPeers, doPercentPeerCaching: p.DoPercentPeerCaching,
|
||||
doBytesFromLanPeers: p.DoBytesFromLanPeers, doBytesFromGroupPeers: p.DoBytesFromGroupPeers,
|
||||
|
||||
+3
@@ -190,6 +190,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// Installer result codes
|
||||
public string ExitCode { get; set; }
|
||||
public string HResultFromWin32 { get; set; }
|
||||
// Return-code class of the last exit code (null on state files written before the field
|
||||
// existed) - must survive the reboot a SoftReboot/HardReboot app asks for.
|
||||
public string ExitCodeClass { get; set; }
|
||||
|
||||
// Delivery Optimization telemetry
|
||||
public long DoFileSize { get; set; }
|
||||
|
||||
+18
-28
@@ -9,6 +9,7 @@ using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Orchestration;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Services;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
@@ -303,7 +304,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
if (TryNormalizeHResult(errorCode, out var hresultValue, out hresultHex))
|
||||
{
|
||||
data["hresult"] = hresultHex;
|
||||
data["hresultSymbol"] = DecodeHResult(hresultValue);
|
||||
data["hresultSymbol"] = ResolveHResultSymbol(hresultValue);
|
||||
}
|
||||
|
||||
var title = string.IsNullOrEmpty(updateTitle) ? "(unknown update)" : updateTitle;
|
||||
@@ -462,36 +463,25 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps common Windows Update HRESULTs to their symbolic name. Not exhaustive — the full
|
||||
/// catalog lives at
|
||||
/// https://learn.microsoft.com/windows/deployment/update/windows-update-error-reference.
|
||||
/// Unknown codes return "WU_E_UNKNOWN" so the raw <c>hresult</c> hex still carries the value.
|
||||
/// Symbolic name of a WU HRESULT from the shared error-code catalog (WU, CBS, Win32 and
|
||||
/// COM families). <c>S_OK</c> for zero, <c>WU_E_UNKNOWN</c> when the catalog has no symbol,
|
||||
/// so the raw <c>hresult</c> hex still carries the value. A catalog load failure is
|
||||
/// swallowed the same way: decoding is decoration and must never cost the event.
|
||||
/// </summary>
|
||||
internal static string DecodeHResult(uint hresult)
|
||||
internal static string ResolveHResultSymbol(uint hresult)
|
||||
=> ResolveHResultSymbol(hresult, code => ErrorCodeCatalog.TryLookup(code));
|
||||
|
||||
internal static string ResolveHResultSymbol(uint hresult, Func<string, ErrorCodeEntry> lookup)
|
||||
{
|
||||
switch (hresult)
|
||||
if (hresult == 0) return "S_OK";
|
||||
try
|
||||
{
|
||||
case 0x00000000: return "S_OK";
|
||||
// WU agent codes (0x8024xxxx)
|
||||
case 0x80240022: return "WU_E_ALL_UPDATES_FAILED";
|
||||
case 0x8024200B: return "WU_E_UH_INSTALLERFAILURE";
|
||||
case 0x80240020: return "WU_E_NO_INTERACTIVE_USER";
|
||||
case 0x80240016: return "WU_E_INSTALL_NOT_ALLOWED";
|
||||
case 0x8024000B: return "WU_E_CALL_CANCELLED";
|
||||
case 0x8024000C: return "WU_E_NOOP";
|
||||
case 0x80240FFF: return "WU_E_UNEXPECTED";
|
||||
case 0x80248007: return "WU_E_DS_NODATA";
|
||||
case 0x8024402C: return "WU_E_PT_WINHTTP_NAME_NOT_RESOLVED";
|
||||
// Generic Win32 / HRESULT
|
||||
case 0x80070005: return "E_ACCESSDENIED";
|
||||
case 0x80070002: return "ERROR_FILE_NOT_FOUND";
|
||||
case 0x80070003: return "ERROR_PATH_NOT_FOUND";
|
||||
case 0x800705B4: return "ERROR_TIMEOUT";
|
||||
// CBS / servicing (LCU install failures)
|
||||
case 0x800F0831: return "CBS_E_STORE_CORRUPTION";
|
||||
case 0x800F0922: return "CBS_E_INSTALLERS_FAILED";
|
||||
case 0x800F0991: return "PSFX_E_MISSING_PAYLOAD_FILE";
|
||||
default: return "WU_E_UNKNOWN";
|
||||
var symbol = lookup("0x" + hresult.ToString("x8", CultureInfo.InvariantCulture))?.Symbol;
|
||||
return string.IsNullOrEmpty(symbol) ? "WU_E_UNKNOWN" : symbol;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "WU_E_UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+88
-1
@@ -65,6 +65,44 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
|
||||
public static DiagnosticsUploadResult SkippedBy(string gate) =>
|
||||
new DiagnosticsUploadResult { Skipped = true, ErrorCode = gate };
|
||||
|
||||
/// <summary>
|
||||
/// Counters of the archive build that produced (or preceded) this result; null when no
|
||||
/// package was built (configuration gate, build exception). Surfaced into the
|
||||
/// <c>diagnostics_uploaded</c> / <c>diagnostics_upload_failed</c> events so a truncated or
|
||||
/// partially failed package is visible without opening the ZIP.
|
||||
/// </summary>
|
||||
public DiagnosticsPackagingStats Packaging { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the packager included, skipped and failed on — as bounded counters only. File paths
|
||||
/// stay inside the ZIP (<c>package-manifest.txt</c>, <c>_TRUNCATED.txt</c>): they can carry
|
||||
/// user names, and a skip list has no upper bound while this payload must stay small no
|
||||
/// matter how many files a cap rejected.
|
||||
/// </summary>
|
||||
public sealed class DiagnosticsPackagingStats
|
||||
{
|
||||
private static readonly IReadOnlyDictionary<string, int> Empty = new Dictionary<string, int>();
|
||||
|
||||
public int IncludedFiles { get; set; }
|
||||
public long IncludedBytes { get; set; }
|
||||
|
||||
/// <summary>Files rejected by a cap or a reparse-point check (the <c>_TRUNCATED.txt</c> list).</summary>
|
||||
public int SkippedFiles { get; set; }
|
||||
|
||||
/// <summary>True when at least one file was skipped — the same condition that writes <c>_TRUNCATED.txt</c>.</summary>
|
||||
public bool Truncated => SkippedFiles > 0;
|
||||
|
||||
/// <summary>Skip count per reason: <c>size</c>, <c>count</c>, <c>total</c>, <c>reparse</c>, <c>resolved-outside-folder</c>.</summary>
|
||||
public IReadOnlyDictionary<string, int> SkippedByReason { get; set; } = Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Packaging problems that are not cap skips, per kind: <c>path-guard</c> (configured path
|
||||
/// refused), <c>no-user-session</c> (user-profile token without a signed-in user),
|
||||
/// <c>folder-rejected</c>, <c>enumerate</c>, <c>open</c>, <c>copy</c>.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, int> ProblemsByKind { get; set; } = Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -134,6 +172,41 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
Skipped.Add(new SkipRecord(path, reason, size));
|
||||
|
||||
public bool HasSkips => Skipped.Count > 0;
|
||||
|
||||
// Non-cap problems (guard refusals, enumeration/open/copy failures) by kind — the
|
||||
// manifest names the files, the event carries only these counts.
|
||||
public Dictionary<string, int> Problems { get; } = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
private readonly HashSet<string> _problemKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Counts one problem of <paramref name="kind"/>. A section is walked once per search
|
||||
/// pattern, so a folder-level failure would otherwise be counted once per pattern —
|
||||
/// pass the folder as <paramref name="dedupeKey"/> to count it once.
|
||||
/// </summary>
|
||||
public void RecordProblem(string kind, string dedupeKey = null)
|
||||
{
|
||||
if (dedupeKey != null && !_problemKeys.Add(kind + "|" + dedupeKey)) return;
|
||||
Problems.TryGetValue(kind, out var n);
|
||||
Problems[kind] = n + 1;
|
||||
}
|
||||
|
||||
public DiagnosticsPackagingStats ToStats()
|
||||
{
|
||||
var byReason = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
foreach (var s in Skipped)
|
||||
{
|
||||
byReason.TryGetValue(s.Reason, out var n);
|
||||
byReason[s.Reason] = n + 1;
|
||||
}
|
||||
return new DiagnosticsPackagingStats
|
||||
{
|
||||
IncludedFiles = FileCount,
|
||||
IncludedBytes = TotalBytes,
|
||||
SkippedFiles = Skipped.Count,
|
||||
SkippedByReason = byReason,
|
||||
ProblemsByKind = new Dictionary<string, int>(Problems, StringComparer.Ordinal),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private readonly struct SkipRecord
|
||||
@@ -262,6 +335,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
var zipFileName = $"AgentDiagnostics-{_configuration.SessionId}-{timestamp}{suffix}.zip";
|
||||
|
||||
var zipBytes = BuildArchiveBytes(enrollmentSucceeded);
|
||||
var packaging = LastPackaging;
|
||||
|
||||
_logger.Info($"Diagnostics package created: {zipFileName} ({zipBytes.Length / 1024} KB)");
|
||||
|
||||
@@ -276,7 +350,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
var errorCode = uploadUrlResponse?.Message ?? "Failed to get diagnostics upload URL from backend";
|
||||
_logger.Warning($"Failed to get diagnostics upload URL from backend — skipping upload: {errorCode}");
|
||||
return new DiagnosticsUploadResult { ErrorCode = errorCode };
|
||||
return new DiagnosticsUploadResult { ErrorCode = errorCode, Packaging = packaging };
|
||||
}
|
||||
|
||||
var sasUrlPrefix = BuildSasUrlPrefix(uploadUrlResponse.UploadUrl);
|
||||
@@ -305,6 +379,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
BlobName = persistedBlobName,
|
||||
Destination = uploadUrlResponse.Destination,
|
||||
SasUrlPrefix = sasUrlPrefix,
|
||||
Packaging = packaging,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -313,6 +388,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
Destination = uploadUrlResponse.Destination,
|
||||
SasUrlPrefix = sasUrlPrefix,
|
||||
ErrorCode = uploadErrorCode,
|
||||
Packaging = packaging,
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -351,6 +427,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
// INSIDE the ZIP (field case: sessions a11102f4 / 3ae7528b, missing evtx undiagnosable).
|
||||
private StringBuilder _manifest;
|
||||
|
||||
/// <summary>Counters of the most recent <see cref="BuildArchiveBytes"/>; null before the first build.</summary>
|
||||
internal DiagnosticsPackagingStats LastPackaging { get; private set; }
|
||||
|
||||
private void ManifestLine(string text)
|
||||
{
|
||||
_manifest?.AppendLine($"[{DateTime.UtcNow:HH:mm:ss.fff}Z] {text}");
|
||||
@@ -391,6 +470,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Diagnostics path blocked by guard: {entry.Path}");
|
||||
ManifestLine($"BLOCKED (path guard): {entry.Path}");
|
||||
tracker.RecordProblem("path-guard");
|
||||
continue;
|
||||
}
|
||||
var expandedPath = UserProfileResolver.ExpandCustomTokens(entry.Path);
|
||||
@@ -398,6 +478,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Diagnostics path skipped (no user session for token): {entry.Path}");
|
||||
ManifestLine($"SKIPPED (no user session for token): {entry.Path}");
|
||||
tracker.RecordProblem("no-user-session");
|
||||
continue;
|
||||
}
|
||||
var folder = Path.GetDirectoryName(expandedPath);
|
||||
@@ -427,6 +508,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
WriteTruncatedMarker(archive, tracker);
|
||||
}
|
||||
|
||||
LastPackaging = tracker.ToStats();
|
||||
return ms.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -498,6 +580,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Built-in diagnostics section skipped (no user session for token): {section.Id}");
|
||||
ManifestLine($"BUILT-IN SKIPPED (no user session for token): {section.Id} '{section.SourceFolder}'");
|
||||
tracker.RecordProblem("no-user-session");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -584,6 +667,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Diagnostics source folder rejected ({folderRejection}): {sourceFolder}");
|
||||
ManifestLine($"FOLDER REJECTED ({folderRejection}): {sourceFolder} (pattern '{searchPattern}')");
|
||||
tracker.RecordProblem("folder-rejected", sourceFolder);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -597,6 +681,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Failed to enumerate log files in {sourceFolder}: {ex.Message}");
|
||||
ManifestLine($"ENUMERATION FAILED: {sourceFolder} (pattern '{searchPattern}'): {ex.Message}");
|
||||
tracker.RecordProblem("enumerate", sourceFolder);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -681,6 +766,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Failed to add log file to diagnostics package: {file} - {ex.Message}");
|
||||
ManifestLine($"FAILED (copy): {file}: {ex.Message}");
|
||||
tracker.RecordProblem("copy");
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -720,6 +806,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
default:
|
||||
_logger.Warning($"Failed to open {file}: {rejection}");
|
||||
ManifestLine($"FAILED (open): {file}: {rejection}");
|
||||
tracker.RecordProblem("open");
|
||||
break;
|
||||
}
|
||||
return null;
|
||||
|
||||
+2
@@ -278,6 +278,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
|
||||
data["logFile"] = Path.GetFileName(filePath);
|
||||
data["ruleId"] = rule.RuleId;
|
||||
data["ruleTitle"] = rule.Title;
|
||||
GatherRuleExecutor.StampRuleMarkers(rule, data);
|
||||
|
||||
var eventType = !string.IsNullOrEmpty(rule.OutputEventType)
|
||||
? rule.OutputEventType
|
||||
@@ -347,6 +348,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
|
||||
data["logFile"] = Path.GetFileName(filePath);
|
||||
data["ruleId"] = rule.RuleId;
|
||||
data["ruleTitle"] = rule.Title;
|
||||
GatherRuleExecutor.StampRuleMarkers(rule, data);
|
||||
|
||||
var eventType = !string.IsNullOrEmpty(rule.OutputEventType)
|
||||
? rule.OutputEventType
|
||||
|
||||
+13
-1
@@ -26,7 +26,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
/// emits (executor, context guard events, collectors). The timeline feed uses it to keep
|
||||
/// gather output from re-triggering on_event rules.
|
||||
/// </summary>
|
||||
public const string SourceName = "GatherRuleExecutor";
|
||||
public const string SourceName = Constants.EventSources.GatherRuleExecutor;
|
||||
|
||||
/// <summary>
|
||||
/// Upper bound on on_event executions per rule and session. on_event has no natural
|
||||
@@ -496,6 +496,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
|
||||
result["ruleId"] = rule.RuleId;
|
||||
result["ruleTitle"] = rule.Title;
|
||||
StampRuleMarkers(rule, result);
|
||||
|
||||
var eventType = !string.IsNullOrEmpty(rule.OutputEventType) ? rule.OutputEventType : Constants.EventTypes.GatherResult;
|
||||
|
||||
@@ -537,6 +538,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
|
||||
// ===== Phase scope (ActivePhases / ActiveFromPhase) =====
|
||||
|
||||
/// <summary>
|
||||
/// Injects the per-rule opt-in markers the backend reads at response time. Called after
|
||||
/// the on_change hash is taken (the markers are rule config, not collected data) by the
|
||||
/// executor and by collectors that emit directly (logparser).
|
||||
/// </summary>
|
||||
internal static void StampRuleMarkers(GatherRule rule, Dictionary<string, object> data)
|
||||
{
|
||||
if (rule.EnrichErrorCodes)
|
||||
data[Constants.GatherRuleDataKeys.EnrichErrorCodes] = true;
|
||||
}
|
||||
|
||||
private static bool HasPhaseScope(GatherRule rule)
|
||||
{
|
||||
return (rule.ActivePhases != null && rule.ActivePhases.Count > 0)
|
||||
|
||||
@@ -1628,6 +1628,15 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
if (app.AttemptNumber > 0) data["attemptNumber"] = app.AttemptNumber.ToString(culture);
|
||||
if (!string.IsNullOrEmpty(app.DetectionResult)) data["detectionResult"] = app.DetectionResult!;
|
||||
|
||||
// Installer outcome of the last attempt (IME-EXITCODE + IME-EXITCODE-CLASS). The class
|
||||
// is the admin's return-code mapping (Success/SoftReboot/HardReboot/Retry/Failed) and
|
||||
// the only evidence that an app asked for a reboot; the number says which code was
|
||||
// mapped (3010 vs 1641 vs custom). Both are known from the terminal lpExitCode lines
|
||||
// only, so they surface on the terminal events - completed, postponed, skipped and
|
||||
// failed alike - never on progress events.
|
||||
if (!string.IsNullOrEmpty(app.ExitCodeClass)) data["exitCodeClass"] = app.ExitCodeClass!;
|
||||
if (IsCompletedState(newState) && !string.IsNullOrEmpty(app.ExitCode)) data["exitCode"] = app.ExitCode!;
|
||||
|
||||
// Plan §5 Fix 4c — per-app install-lifecycle timing. StartedAt appears on the
|
||||
// first Downloading/Installing/InProgress event; CompletedAt + DurationSeconds
|
||||
// light up on the terminal event. Values are omitted when not yet known so the
|
||||
@@ -1644,7 +1653,6 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
if (!string.IsNullOrEmpty(app.ErrorPatternId)) data["errorPatternId"] = app.ErrorPatternId!;
|
||||
if (!string.IsNullOrEmpty(app.ErrorDetail)) data["errorDetail"] = app.ErrorDetail!;
|
||||
if (!string.IsNullOrEmpty(app.ErrorCode)) data["errorCode"] = app.ErrorCode!;
|
||||
if (!string.IsNullOrEmpty(app.ExitCode)) data["exitCode"] = app.ExitCode!;
|
||||
if (!string.IsNullOrEmpty(app.HResultFromWin32)) data["hresultFromWin32"] = app.HResultFromWin32!;
|
||||
|
||||
// Likely-stuck / detection-failure / install-failure classification: when the
|
||||
|
||||
@@ -4,6 +4,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Telemetry.Signals
|
||||
{
|
||||
|
||||
+1
@@ -4,6 +4,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Telemetry.Transitions
|
||||
{
|
||||
|
||||
+42
-17
@@ -1007,6 +1007,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
if (result != null && result.Success)
|
||||
{
|
||||
_logger.Info($"EnrollmentTerminationHandler: diagnostics uploaded (blob={result.BlobName}).");
|
||||
var data = new Dictionary<string, object>
|
||||
{
|
||||
{ "blobName", result.BlobName ?? string.Empty },
|
||||
// Tells the backend which storage the blob landed in so it can
|
||||
// stamp Session.DiagnosticsBlobDestination and route downloads
|
||||
// even after a future tenant destination switch. Empty when the
|
||||
// backend predates the field (agent falls through harmlessly).
|
||||
{ "destination", result.Destination ?? string.Empty },
|
||||
{ "sasUrlPrefix", result.SasUrlPrefix ?? string.Empty },
|
||||
};
|
||||
AppendPackagingStats(data, result.Packaging);
|
||||
EmitEventSafe(new EnrollmentEvent
|
||||
{
|
||||
SessionId = _configuration.SessionId,
|
||||
@@ -1015,17 +1026,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
Severity = EventSeverity.Info,
|
||||
Source = "EnrollmentTerminationHandler",
|
||||
Phase = EnrollmentPhase.Unknown,
|
||||
Message = $"Diagnostics package uploaded ({result.BlobName}).",
|
||||
Data = new Dictionary<string, object>
|
||||
{
|
||||
{ "blobName", result.BlobName ?? string.Empty },
|
||||
// Tells the backend which storage the blob landed in so it can
|
||||
// stamp Session.DiagnosticsBlobDestination and route downloads
|
||||
// even after a future tenant destination switch. Empty when the
|
||||
// backend predates the field (agent falls through harmlessly).
|
||||
{ "destination", result.Destination ?? string.Empty },
|
||||
{ "sasUrlPrefix", result.SasUrlPrefix ?? string.Empty },
|
||||
},
|
||||
Message = $"Diagnostics package uploaded ({result.BlobName})."
|
||||
+ (result.Packaging != null && result.Packaging.Truncated
|
||||
? $" Truncated: {result.Packaging.SkippedFiles} file(s) skipped by the packaging caps."
|
||||
: string.Empty),
|
||||
Data = data,
|
||||
ImmediateUpload = true,
|
||||
});
|
||||
}
|
||||
@@ -1033,6 +1038,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
{
|
||||
var errorCode = result?.ErrorCode ?? "null-result";
|
||||
_logger.Warning($"EnrollmentTerminationHandler: diagnostics upload failed: {errorCode}.");
|
||||
var data = new Dictionary<string, object>
|
||||
{
|
||||
{ "errorCode", errorCode },
|
||||
{ "blobName", result?.BlobName ?? string.Empty },
|
||||
{ "destination", result?.Destination ?? string.Empty },
|
||||
};
|
||||
AppendPackagingStats(data, result?.Packaging);
|
||||
EmitEventSafe(new EnrollmentEvent
|
||||
{
|
||||
SessionId = _configuration.SessionId,
|
||||
@@ -1042,17 +1054,30 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
Source = "EnrollmentTerminationHandler",
|
||||
Phase = EnrollmentPhase.Unknown,
|
||||
Message = $"Diagnostics upload failed: {errorCode}.",
|
||||
Data = new Dictionary<string, object>
|
||||
{
|
||||
{ "errorCode", errorCode },
|
||||
{ "blobName", result?.BlobName ?? string.Empty },
|
||||
{ "destination", result?.Destination ?? string.Empty },
|
||||
},
|
||||
Data = data,
|
||||
ImmediateUpload = true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the packager's counters to a diagnostics event payload — counts only, never a
|
||||
/// file path (paths live in the ZIP's manifest and may carry user names). Absent when no
|
||||
/// package was built, so consumers treat the keys as optional.
|
||||
/// </summary>
|
||||
private static void AppendPackagingStats(Dictionary<string, object> data, DiagnosticsPackagingStats packaging)
|
||||
{
|
||||
if (packaging == null) return;
|
||||
data["truncated"] = packaging.Truncated;
|
||||
data["includedFiles"] = packaging.IncludedFiles;
|
||||
data["includedBytes"] = packaging.IncludedBytes;
|
||||
data["skippedFiles"] = packaging.SkippedFiles;
|
||||
data["skippedByReason"] = new Dictionary<string, int>(
|
||||
(IDictionary<string, int>)packaging.SkippedByReason ?? new Dictionary<string, int>(), StringComparer.Ordinal);
|
||||
data["problemsByKind"] = new Dictionary<string, int>(
|
||||
(IDictionary<string, int>)packaging.ProblemsByKind ?? new Dictionary<string, int>(), StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
private void WriteEnrollmentCompleteMarker(EnrollmentTerminatedEventArgs args)
|
||||
{
|
||||
// On WhiteGlove Part 1 exit we keep the session alive for Part 2 — DO NOT write the
|
||||
|
||||
+9
-5
@@ -395,12 +395,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
}
|
||||
}
|
||||
|
||||
private static string SerializeBatch(IReadOnlyList<TelemetryItem> items)
|
||||
/// <summary>
|
||||
/// The batch body: a JSON array of <see cref="TelemetryItemDto"/> — the Shared class the
|
||||
/// ingest deserialises — with Newtonsoft defaults (PascalCase, ISO-8601 UTC, Kind by name).
|
||||
/// Internal so <c>TelemetryWireContractTests</c> can freeze the real output as a fixture.
|
||||
/// </summary>
|
||||
internal static string SerializeBatch(IReadOnlyList<TelemetryItem> items)
|
||||
{
|
||||
// Newtonsoft PascalCase default + TelemetryItemKind carries [StringEnumConverter] →
|
||||
// Backend routes by string "Event"/"Signal"/"DecisionTransition". Wire-format
|
||||
// matches Plan §4.x M5 contract (PascalCase, StringEnum, ISO-8601 UTC).
|
||||
return JsonConvert.SerializeObject(items, Formatting.None);
|
||||
var wire = new TelemetryItemDto[items.Count];
|
||||
for (var i = 0; i < items.Count; i++) wire[i] = items[i].ToWire();
|
||||
return JsonConvert.SerializeObject(wire, Formatting.None);
|
||||
}
|
||||
|
||||
private static byte[] CompressWithGzip(string text)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
{
|
||||
@@ -106,6 +107,26 @@ namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
/// <summary>Anzahl der bisher fehlgeschlagenen Upload-Versuche. Wird vom Orchestrator incrementiert.</summary>
|
||||
public int RetryCount { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The wire shape of this item. <see cref="TelemetryItemDto"/> (Shared) is the ONE class both
|
||||
/// ends serialise; this mapping is the only place the agent's validated model meets it.
|
||||
/// <c>TelemetryWireContractTests</c> proves every DTO property is populated here and
|
||||
/// freezes the resulting body under <c>tests/fixtures/telemetry-wire/</c> for the backend.
|
||||
/// </summary>
|
||||
public TelemetryItemDto ToWire() =>
|
||||
new TelemetryItemDto
|
||||
{
|
||||
Kind = Kind.ToString(),
|
||||
PartitionKey = PartitionKey,
|
||||
RowKey = RowKey,
|
||||
TelemetryItemId = TelemetryItemId,
|
||||
SessionTraceOrdinal = SessionTraceOrdinal,
|
||||
PayloadJson = PayloadJson,
|
||||
RequiresImmediateFlush = RequiresImmediateFlush,
|
||||
EnqueuedAtUtc = EnqueuedAtUtc,
|
||||
RetryCount = RetryCount,
|
||||
};
|
||||
|
||||
/// <summary>Copy-with-incremented <see cref="RetryCount"/>. Immutable-Erhalt (§2.3 L.3).</summary>
|
||||
public TelemetryItem WithRetryIncremented() =>
|
||||
new TelemetryItem(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
{
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
#nullable enable
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
{
|
||||
/// <summary>
|
||||
/// Typ eines <see cref="TelemetryItem"/>. Plan §2.7a / L.10.
|
||||
/// <para>
|
||||
/// Drei getrennte Backend-Tabellen:
|
||||
/// <see cref="Event"/> → <c>Events</c>,
|
||||
/// <see cref="Signal"/> → <c>Signals</c>,
|
||||
/// <see cref="DecisionTransition"/> → <c>DecisionTransitions</c>.
|
||||
/// Der generische Transport routet auf Backend-Seite nach <c>Kind</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// String-serialisiert via <see cref="StringEnumConverter"/> — Backend-Routing darf
|
||||
/// nicht von Integer-Ordering abhängen, das bei zukünftigen Erweiterungen bricht
|
||||
/// (L.14 forward-compat).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
[JsonConverter(typeof(StringEnumConverter))]
|
||||
public enum TelemetryItemKind
|
||||
{
|
||||
Event = 0,
|
||||
Signal,
|
||||
DecisionTransition,
|
||||
}
|
||||
}
|
||||
+18
-2
@@ -2,6 +2,7 @@
|
||||
using System;
|
||||
using AutopilotMonitor.DecisionCore.Serialization;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
{
|
||||
@@ -16,10 +17,25 @@ namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
/// </summary>
|
||||
public static class TelemetryItemSerializer
|
||||
{
|
||||
/// <summary>
|
||||
/// DecisionCore settings plus a <see cref="StringEnumConverter"/>: <see cref="TelemetryItem.Kind"/>
|
||||
/// is the only enum on a spool line and has always been written by NAME (<c>"Event"</c>),
|
||||
/// which is also what the wire carries. The enum lives in Shared (no Newtonsoft there), so
|
||||
/// the converter is registered here instead of as an attribute on the type.
|
||||
/// </summary>
|
||||
private static readonly JsonSerializerSettings SpoolSettings = CreateSpoolSettings();
|
||||
|
||||
private static JsonSerializerSettings CreateSpoolSettings()
|
||||
{
|
||||
var settings = DecisionCoreJsonSettings.Create();
|
||||
settings.Converters.Add(new StringEnumConverter());
|
||||
return settings;
|
||||
}
|
||||
|
||||
public static string Serialize(TelemetryItem item)
|
||||
{
|
||||
if (item == null) throw new ArgumentNullException(nameof(item));
|
||||
return JsonConvert.SerializeObject(item, DecisionCoreJsonSettings.Shared);
|
||||
return JsonConvert.SerializeObject(item, SpoolSettings);
|
||||
}
|
||||
|
||||
public static TelemetryItem Deserialize(string line)
|
||||
@@ -28,7 +44,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
|
||||
|
||||
try
|
||||
{
|
||||
var result = JsonConvert.DeserializeObject<TelemetryItem>(line, DecisionCoreJsonSettings.Shared);
|
||||
var result = JsonConvert.DeserializeObject<TelemetryItem>(line, SpoolSettings);
|
||||
if (result == null)
|
||||
{
|
||||
throw new JsonSerializationException($"TelemetryItem deserialization produced null: {line}");
|
||||
|
||||
@@ -11,9 +11,8 @@ namespace AutopilotMonitor.DecisionCore.Tests.State
|
||||
{
|
||||
/// <summary>
|
||||
/// Every payload-derived string that lands in <see cref="DecisionState"/> is bounded by
|
||||
/// <see cref="FactStringBounds"/> at the reducer boundary. The server-side semantic replay
|
||||
/// (<c>ReducerVerifier</c>) folds device-uploaded payloads through the same engine, so an
|
||||
/// unbounded string there is a per-request memory/CPU amplifier. These tests pin that the
|
||||
/// <see cref="FactStringBounds"/> at the reducer boundary — an unbounded string there is a
|
||||
/// per-signal memory/CPU amplifier in every snapshot persist. These tests pin that the
|
||||
/// bound is applied BEFORE any dedupe comparison (so a forged multi-hundred-KB key neither
|
||||
/// costs a full-length compare nor lands in state) and that real-sized values pass through
|
||||
/// unchanged.
|
||||
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Default-value + round-trip tests for <see cref="AdminConfiguration.EnableIndexDualWrite"/>
|
||||
/// (Plan §M5.d). The flag gates the index-table dual-write rollout — defaulting to false
|
||||
/// keeps pre-M5.d behaviour bit-exact and lets operators flip it on deliberately.
|
||||
/// </summary>
|
||||
public class AdminConfigurationEnableIndexDualWriteTests
|
||||
{
|
||||
[Fact]
|
||||
public void EnableIndexDualWrite_defaults_to_false_on_new_config()
|
||||
{
|
||||
var cfg = new AdminConfiguration();
|
||||
Assert.False(cfg.EnableIndexDualWrite);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnableIndexDualWrite_defaults_to_false_on_CreateDefault()
|
||||
{
|
||||
// CreateDefault() is called when no admin-config row exists yet — if it somehow
|
||||
// enabled dual-write it would break the "default-off" contract immediately.
|
||||
var cfg = AdminConfiguration.CreateDefault();
|
||||
Assert.False(cfg.EnableIndexDualWrite);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnableIndexDualWrite_true_persists_on_the_config()
|
||||
{
|
||||
var cfg = new AdminConfiguration { EnableIndexDualWrite = true };
|
||||
Assert.True(cfg.EnableIndexDualWrite);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the derivation shared by the agent channel (GET agent/config) and the Global-Admin
|
||||
/// report route (GET config/{tenantId}/effective-agent-config): every rule the Tenant Config
|
||||
/// Report used to re-implement in the web now has exactly one implementation, and these
|
||||
/// facts are its contract.
|
||||
/// </summary>
|
||||
public class AgentConfigResolverTests
|
||||
{
|
||||
private const string TenantId = "11111111-2222-3333-4444-555555555555";
|
||||
private static readonly DateTime Now = new(2026, 9, 6, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private static TenantConfiguration Tenant(Action<TenantConfiguration>? mutate = null)
|
||||
{
|
||||
var c = new TenantConfiguration { TenantId = TenantId, DomainName = "contoso.example", UpdatedBy = "ga@operator.example" };
|
||||
mutate?.Invoke(c);
|
||||
return c;
|
||||
}
|
||||
|
||||
private static AdminConfiguration Admin(Action<AdminConfiguration>? mutate = null)
|
||||
{
|
||||
var a = new AdminConfiguration();
|
||||
mutate?.Invoke(a);
|
||||
return a;
|
||||
}
|
||||
|
||||
private static AgentConfigResponse Build(TenantConfiguration tenant, AdminConfiguration? admin = null, int agentMajor = AgentConfigResolver.CurrentAgentMajor)
|
||||
=> AgentConfigResolver.Build(tenant, admin ?? Admin(), new List<GatherRule>(), new List<ImeLogPattern>(), agentMajor, Now).Response;
|
||||
|
||||
[Fact]
|
||||
public void Fresh_tenant_gets_the_agent_defaults()
|
||||
{
|
||||
var r = Build(Tenant());
|
||||
|
||||
Assert.Equal(AgentConfigResolver.ConfigVersion, r.ConfigVersion);
|
||||
Assert.Equal(AutopilotMonitor.Shared.Constants.DefaultUploadIntervalSeconds, r.UploadIntervalSeconds);
|
||||
Assert.Equal(10, r.UploadIntervalSeconds); // the report showed 30 for a month — pinned
|
||||
Assert.True(r.SelfDestructOnComplete);
|
||||
Assert.False(r.KeepLogFile);
|
||||
Assert.True(r.EnableGeoLocation);
|
||||
Assert.Equal(5, r.MaxAuthFailures);
|
||||
Assert.Equal(0, r.AuthFailureTimeoutMinutes);
|
||||
Assert.Equal("Info", r.LogLevel);
|
||||
Assert.Equal(10, r.RebootDelaySeconds);
|
||||
Assert.Equal(60, r.EnrollmentSummaryTimeoutSeconds);
|
||||
Assert.Equal(120, r.EnrollmentSummaryLaunchRetrySeconds);
|
||||
Assert.Equal(100, r.MaxBatchSize);
|
||||
Assert.Equal("time.windows.com", r.NtpServer);
|
||||
Assert.Equal("Off", r.DiagnosticsUploadMode);
|
||||
Assert.False(r.DiagnosticsUploadEnabled);
|
||||
Assert.False(r.UnrestrictedMode);
|
||||
Assert.False(r.DeviceBlocked);
|
||||
Assert.False(r.DeviceKillSignal);
|
||||
Assert.Null(r.UnblockAt);
|
||||
Assert.Null(r.MigrateToApiBaseUrl);
|
||||
|
||||
Assert.Equal(360, r.Collectors.AgentMaxLifetimeMinutes);
|
||||
Assert.Equal(15, r.Collectors.CollectorIdleTimeoutMinutes);
|
||||
Assert.Equal(10, r.Collectors.DesktopDetectorNoCandidateTimeoutMinutes);
|
||||
Assert.Equal(new[] { 100, 1005, 1010 }, r.Collectors.ModernDeploymentHarmlessEventIds);
|
||||
|
||||
Assert.True(r.Analyzers.EnableLocalAdminAnalyzer);
|
||||
Assert.Empty(r.Analyzers.LocalAdminAllowedAccounts);
|
||||
Assert.False(r.Analyzers.EnableSoftwareInventoryAnalyzer);
|
||||
Assert.True(r.Analyzers.EnableIntegrityBypassAnalyzer);
|
||||
Assert.False(r.Analyzers.EnableRealmJoinWatcher);
|
||||
Assert.False(r.Analyzers.KeepAwakeDuringUserEsp);
|
||||
Assert.True(r.Analyzers.EnableConsoleBypassDetection);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, "CustomerSas", "Off", false)]
|
||||
[InlineData(null, "Hosted", "Off", true)] // hosted destination needs no SAS
|
||||
[InlineData("https://acct.blob.core.windows.net/c?sv=1", "CustomerSas", "Off", true)] // SAS enables regardless of mode
|
||||
public void Diagnostics_upload_enabled_follows_sas_or_hosted_not_the_mode(string? sas, string destination, string mode, bool expected)
|
||||
{
|
||||
var r = Build(Tenant(t =>
|
||||
{
|
||||
t.DiagnosticsBlobSasUrl = sas!;
|
||||
t.DiagnosticsUploadDestination = destination;
|
||||
t.DiagnosticsUploadMode = mode;
|
||||
}));
|
||||
Assert.Equal(expected, r.DiagnosticsUploadEnabled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("free", true, true, false)] // Community: entitlement missing
|
||||
[InlineData("pro", false, true, false)] // GA gate off
|
||||
[InlineData("pro", true, false, false)] // tenant toggle off
|
||||
[InlineData("pro", true, true, true)]
|
||||
public void Unrestricted_mode_needs_entitlement_and_gate_and_toggle(string planTier, bool gaGate, bool toggle, bool expected)
|
||||
{
|
||||
var r = Build(Tenant(t =>
|
||||
{
|
||||
t.PlanTier = planTier;
|
||||
t.UnrestrictedModeEnabled = gaGate;
|
||||
t.UnrestrictedMode = toggle;
|
||||
}));
|
||||
Assert.Equal(expected, r.UnrestrictedMode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Operator_knobs_come_from_the_admin_configuration()
|
||||
{
|
||||
var admin = Admin(a =>
|
||||
{
|
||||
a.CollectorIdleTimeoutMinutes = 25;
|
||||
a.DesktopDetectorNoCandidateTimeoutMinutes = 7;
|
||||
a.AllowAgentDowngrade = true;
|
||||
a.ModernDeploymentHarmlessEventIdsJson = "[100, 42]";
|
||||
a.LatestAgentV2Sha256 = "zip-v2";
|
||||
a.LatestAgentV2ExeSha256 = "exe-v2";
|
||||
});
|
||||
|
||||
var r = Build(Tenant(), admin);
|
||||
|
||||
Assert.Equal(25, r.Collectors.CollectorIdleTimeoutMinutes);
|
||||
Assert.Equal(7, r.Collectors.DesktopDetectorNoCandidateTimeoutMinutes);
|
||||
Assert.True(r.AllowAgentDowngrade);
|
||||
Assert.Equal(new[] { 100, 42 }, r.Collectors.ModernDeploymentHarmlessEventIds);
|
||||
Assert.Equal("zip-v2", r.LatestAgentSha256);
|
||||
Assert.Equal("exe-v2", r.LatestAgentExeSha256);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Legacy_major_gets_empty_hashes_the_current_major_gets_v2()
|
||||
{
|
||||
var admin = Admin(a => { a.LatestAgentV2Sha256 = "zip-v2"; a.LatestAgentV2ExeSha256 = "exe-v2"; });
|
||||
|
||||
var legacy = Build(Tenant(), admin, agentMajor: 1);
|
||||
Assert.Equal(string.Empty, legacy.LatestAgentSha256);
|
||||
|
||||
var current = Build(Tenant(), admin, agentMajor: AgentConfigResolver.CurrentAgentMajor);
|
||||
Assert.Equal("zip-v2", current.LatestAgentSha256);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Tenant_overrides_win_over_defaults()
|
||||
{
|
||||
var r = Build(Tenant(t =>
|
||||
{
|
||||
t.MaxBatchSize = 25;
|
||||
t.LogLevel = "Debug";
|
||||
t.NtpServer = "";
|
||||
t.LocalAdminAllowedAccountsJson = "[\"Admin\",\"Helpdesk\"]";
|
||||
t.AgentMaxLifetimeMinutes = 120;
|
||||
t.EnableConsoleBypassDetection = false;
|
||||
}));
|
||||
|
||||
Assert.Equal(25, r.MaxBatchSize);
|
||||
Assert.Equal("Debug", r.LogLevel);
|
||||
Assert.Equal("time.windows.com", r.NtpServer); // empty string falls back like null
|
||||
Assert.Equal(new[] { "Admin", "Helpdesk" }, r.Analyzers.LocalAdminAllowedAccounts);
|
||||
Assert.Equal(120, r.Collectors.AgentMaxLifetimeMinutes);
|
||||
Assert.False(r.Analyzers.EnableConsoleBypassDetection);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Migration_target_is_served_when_valid_and_reported_when_rejected()
|
||||
{
|
||||
const string Us = "https://autopilotmonitor-api-us.azurewebsites.net";
|
||||
var served = AgentConfigResolver.Build(Tenant(), Admin(a => a.AgentMigrateApiBaseUrl = Us),
|
||||
new List<GatherRule>(), new List<ImeLogPattern>(), AgentConfigResolver.CurrentAgentMajor, Now);
|
||||
Assert.Equal(Us, served.Response.MigrateToApiBaseUrl);
|
||||
Assert.Null(served.RejectedMigrateCandidate);
|
||||
|
||||
var rejected = AgentConfigResolver.Build(Tenant(), Admin(a => a.AgentMigrateApiBaseUrl = "https://evil.example"),
|
||||
new List<GatherRule>(), new List<ImeLogPattern>(), AgentConfigResolver.CurrentAgentMajor, Now);
|
||||
Assert.Null(rejected.Response.MigrateToApiBaseUrl);
|
||||
Assert.Equal("https://evil.example", rejected.RejectedMigrateCandidate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Catalogs_pass_through_unchanged()
|
||||
{
|
||||
var rules = new List<GatherRule> { new() { RuleId = "GATHER-TEST-001" } };
|
||||
var patterns = new List<ImeLogPattern> { new() { PatternId = "IME-TEST-001" } };
|
||||
var r = AgentConfigResolver.Build(Tenant(), Admin(), rules, patterns, AgentConfigResolver.CurrentAgentMajor, Now).Response;
|
||||
Assert.Same(rules, r.GatherRules);
|
||||
Assert.Same(patterns, r.ImeLogPatterns);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using System.Threading;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
@@ -21,7 +22,7 @@ public class AgentEfficiencyMetricsServiceTests
|
||||
{
|
||||
var repo = new Mock<ISessionRepository>();
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(new List<SessionSummary>(), null));
|
||||
repo
|
||||
.Setup(r => r.GetSessionEventsByTypesAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IReadOnlyCollection<string>>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<int>()))
|
||||
@@ -67,7 +68,7 @@ public class AgentEfficiencyMetricsServiceTests
|
||||
private static void SetupSessions(Mock<ISessionRepository> repo, List<SessionSummary> sessions)
|
||||
{
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(sessions, null));
|
||||
}
|
||||
|
||||
@@ -201,8 +202,8 @@ public class AgentEfficiencyMetricsServiceTests
|
||||
string? capturedTenant = null;
|
||||
IEnumerable<string>? capturedSelect = null;
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?>((t, _, _, _, _, sel) => { capturedTenant = t; capturedSelect = sel; })
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?, CancellationToken>((t, _, _, _, _, sel, _) => { capturedTenant = t; capturedSelect = sel; })
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(new List<SessionSummary>(), null));
|
||||
|
||||
var result = await service.ComputeAsync(days: 45, limit: 100, tenantId: Tenant);
|
||||
@@ -220,7 +221,7 @@ public class AgentEfficiencyMetricsServiceTests
|
||||
var (service, repo) = CreateService();
|
||||
int callCount = 0;
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.Callback(() => callCount++)
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(new List<SessionSummary>(), null));
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using AutopilotMonitor.Functions.Functions.Config;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Services;
|
||||
using Xunit;
|
||||
@@ -8,7 +8,7 @@ namespace AutopilotMonitor.Functions.Tests;
|
||||
/// <summary>
|
||||
/// Pins the endpoint-migration serving contract: the shared allowlist rules
|
||||
/// (<see cref="AgentEndpointMigrationRules"/>, used verbatim by the agent too) and the
|
||||
/// backend-side per-tenant resolution (<see cref="GetAgentConfigFunction.ResolveMigrateTarget"/> —
|
||||
/// backend-side per-tenant resolution (<see cref="AgentConfigResolver.ResolveMigrateTarget"/> —
|
||||
/// tenant override wins, empty override pins, invalid values are never served).
|
||||
/// </summary>
|
||||
public class AgentEndpointMigrationTests
|
||||
@@ -75,7 +75,7 @@ public class AgentEndpointMigrationTests
|
||||
{
|
||||
var config = new AdminConfiguration();
|
||||
|
||||
Assert.Null(GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out var rejected));
|
||||
Assert.Null(AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out var rejected));
|
||||
Assert.Null(rejected);
|
||||
}
|
||||
|
||||
@@ -84,8 +84,8 @@ public class AgentEndpointMigrationTests
|
||||
{
|
||||
var config = new AdminConfiguration { AgentMigrateApiBaseUrl = UsUrl };
|
||||
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantB, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantB, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -97,8 +97,8 @@ public class AgentEndpointMigrationTests
|
||||
AgentMigrateTenantOverridesJson = $"{{\"{TenantA}\": \"{EuUrl}\"}}"
|
||||
};
|
||||
|
||||
Assert.Equal(EuUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantB, out _));
|
||||
Assert.Equal(EuUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantB, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -110,9 +110,9 @@ public class AgentEndpointMigrationTests
|
||||
AgentMigrateTenantOverridesJson = $"{{\"{TenantA}\": \"\"}}"
|
||||
};
|
||||
|
||||
Assert.Null(GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out var rejected));
|
||||
Assert.Null(AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out var rejected));
|
||||
Assert.Null(rejected); // pinned, not rejected
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantB, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantB, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -123,7 +123,7 @@ public class AgentEndpointMigrationTests
|
||||
AgentMigrateTenantOverridesJson = $"{{\"{TenantA.ToUpperInvariant()}\": \"{UsUrl}\"}}"
|
||||
};
|
||||
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -131,7 +131,7 @@ public class AgentEndpointMigrationTests
|
||||
{
|
||||
var config = new AdminConfiguration { AgentMigrateApiBaseUrl = "https://attacker.example.com" };
|
||||
|
||||
Assert.Null(GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out var rejected));
|
||||
Assert.Null(AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out var rejected));
|
||||
Assert.Equal("https://attacker.example.com", rejected);
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ public class AgentEndpointMigrationTests
|
||||
AgentMigrateTenantOverridesJson = "{not json"
|
||||
};
|
||||
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -155,6 +155,6 @@ public class AgentEndpointMigrationTests
|
||||
AgentMigrateApiBaseUrl = "https://AutopilotMonitor-API-US.azurewebsites.net/"
|
||||
};
|
||||
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ namespace AutopilotMonitor.Functions.Tests;
|
||||
/// <summary>
|
||||
/// JSON round-trip tests for <see cref="AnalyzeOnEnrollmentEndEnvelope"/>. The producer
|
||||
/// (<c>AzureQueueAnalyzeOnEnrollmentEndProducer</c>) serializes with Newtonsoft and the
|
||||
/// queue worker (<c>AnalyzeOnEnrollmentEndQueueWorker</c>) deserializes the same shape —
|
||||
/// queue worker (<c>AnalyzeOnEnrollmentEndQueueFunction</c>) deserializes the same shape —
|
||||
/// pinning the contract here keeps the queue from silently breaking when fields are added.
|
||||
/// </summary>
|
||||
public class AnalyzeOnEnrollmentEndEnvelopeSerializationTests
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The middleware-side error-envelope writer: status, content type, Retry-After and the exact body
|
||||
/// (production wire options — camelCase, absent-when-null) for the generic envelope and for a
|
||||
/// specialised <see cref="IApiErrorResponse"/>. Whatever the authentication, policy, rate-limit and
|
||||
/// quota middlewares write flows through here, so this is the one place their body shape is pinned.
|
||||
/// </summary>
|
||||
public class ApiErrorWriterTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Generic_envelope_writes_status_content_type_and_the_three_prefix_keys()
|
||||
{
|
||||
var ctx = NewContext();
|
||||
|
||||
await ApiErrorWriter.WriteAsync(ctx, "cid-42", HttpStatusCode.Unauthorized,
|
||||
Constants.ApiErrorCodes.AuthenticationRequired, "Authentication required.");
|
||||
|
||||
Assert.Equal(401, ctx.Response.StatusCode);
|
||||
Assert.StartsWith("application/json", ctx.Response.ContentType);
|
||||
Assert.False(ctx.Response.Headers.ContainsKey("Retry-After"));
|
||||
Assert.Equal(
|
||||
"{\"error\":\"Authentication required.\",\"code\":\"AuthenticationRequired\",\"correlationId\":\"cid-42\"}",
|
||||
Body(ctx));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Generic_envelope_with_retry_window_sets_the_header_and_mirrors_it_in_the_body()
|
||||
{
|
||||
var ctx = NewContext();
|
||||
|
||||
await ApiErrorWriter.WriteAsync(ctx, "cid-7", HttpStatusCode.TooManyRequests,
|
||||
Constants.ApiErrorCodes.RateLimited, "Rate limit exceeded: 60 requests per minute",
|
||||
retryAfterSeconds: 23);
|
||||
|
||||
Assert.Equal(429, ctx.Response.StatusCode);
|
||||
Assert.Equal("23", ctx.Response.Headers["Retry-After"]);
|
||||
Assert.Equal(
|
||||
"{\"error\":\"Rate limit exceeded: 60 requests per minute\",\"code\":\"RateLimited\",\"correlationId\":\"cid-7\",\"retryAfterSeconds\":23}",
|
||||
Body(ctx));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Generic_envelope_carries_hint_and_operation_only_when_given()
|
||||
{
|
||||
var ctx = NewContext();
|
||||
|
||||
await ApiErrorWriter.WriteAsync(ctx, "cid-9", HttpStatusCode.InternalServerError,
|
||||
Constants.ApiErrorCodes.InternalError, "QueryTable failed.",
|
||||
hint: "Retry with a narrower filter.", operation: "QueryTable");
|
||||
|
||||
Assert.Equal(
|
||||
"{\"error\":\"QueryTable failed.\",\"code\":\"InternalError\",\"correlationId\":\"cid-9\"," +
|
||||
"\"hint\":\"Retry with a narrower filter.\",\"operation\":\"QueryTable\"}",
|
||||
Body(ctx));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Specialised_body_is_stamped_with_the_correlation_id_and_serialized_as_its_runtime_type()
|
||||
{
|
||||
var ctx = NewContext();
|
||||
var body = new DelegatedSlotLimitReachedResponse
|
||||
{
|
||||
Error = "Slot limit reached.",
|
||||
HomeTenantId = "7aa20c11-0002-4b7c-a1d2-52f3aaaa0001",
|
||||
Used = 2,
|
||||
Limit = 2,
|
||||
Required = 1,
|
||||
};
|
||||
|
||||
await ApiErrorWriter.WriteAsync(ctx, "cid-slot", HttpStatusCode.Conflict, body);
|
||||
|
||||
Assert.Equal(409, ctx.Response.StatusCode);
|
||||
Assert.Equal("cid-slot", body.CorrelationId);
|
||||
var json = JsonDocument.Parse(Body(ctx)).RootElement;
|
||||
// Envelope prefix first, then the specialised fields — and nothing of the marker interface.
|
||||
var keys = json.EnumerateObject().Select(p => p.Name).ToArray();
|
||||
Assert.Equal(new[] { "error", "code", "correlationId", "homeTenantId", "used", "limit", "required" }, keys);
|
||||
Assert.Equal("DelegatedSlotLimitReached", json.GetProperty("code").GetString());
|
||||
}
|
||||
|
||||
private static DefaultHttpContext NewContext()
|
||||
{
|
||||
var ctx = new DefaultHttpContext();
|
||||
ctx.Response.Body = new MemoryStream();
|
||||
return ctx;
|
||||
}
|
||||
|
||||
private static string Body(HttpContext ctx)
|
||||
{
|
||||
ctx.Response.Body.Position = 0;
|
||||
using var reader = new StreamReader(ctx.Response.Body);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Text.Json;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
@@ -29,6 +30,33 @@ public class ApiResponseWireParityTests
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
|
||||
// ---- Error envelope (2026-09, deliberate wire change) ----------------------------------
|
||||
// Non-2xx bodies used to be ~10 anonymous shapes ({ success = false, message }, { error },
|
||||
// { error, message }, { error, code }, …). They are ONE typed envelope now, so these pins fix
|
||||
// the NEW shape exactly rather than proving parity with any single legacy literal.
|
||||
|
||||
[Fact]
|
||||
public void ApiErrorResponse_pins_the_minimal_envelope_shape()
|
||||
{
|
||||
var body = ApiErrorWriter.Build("cid-1", Constants.ApiErrorCodes.NotFound, "Session not found.");
|
||||
|
||||
Assert.Equal(
|
||||
"{\"error\":\"Session not found.\",\"code\":\"NotFound\",\"correlationId\":\"cid-1\"}",
|
||||
JsonSerializer.Serialize(body, WireOptions));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApiErrorResponse_pins_the_full_envelope_shape_and_key_order()
|
||||
{
|
||||
var body = ApiErrorWriter.Build("cid-2", Constants.ApiErrorCodes.ServiceUnavailable,
|
||||
"Authorization service temporarily unavailable.", hint: "Retry.", retryAfterSeconds: 5, operation: "PolicyEnforcement");
|
||||
|
||||
Assert.Equal(
|
||||
"{\"error\":\"Authorization service temporarily unavailable.\",\"code\":\"ServiceUnavailable\"," +
|
||||
"\"correlationId\":\"cid-2\",\"hint\":\"Retry.\",\"retryAfterSeconds\":5,\"operation\":\"PolicyEnforcement\"}",
|
||||
JsonSerializer.Serialize(body, WireOptions));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SuccessMessageResponse_matches_the_canonical_anonymous_shape()
|
||||
{
|
||||
|
||||
@@ -356,7 +356,8 @@ public class ApplicationPrincipalTests
|
||||
var members = new StubTenantMemberRoleResolver();
|
||||
var sut = new McpUserService(
|
||||
adminRepo.Object, bindings, cache, NullLogger<McpUserService>.Instance,
|
||||
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, members);
|
||||
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, members,
|
||||
new TenantConfigurationService(Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache));
|
||||
return (sut, members);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ public class AuthFunctionSideEffectTests
|
||||
var mcpUserMock = new Mock<McpUserService>(
|
||||
adminRepo, new StubAdminIdentityBindingService(bound: true), cache, Mock.Of<ILogger<McpUserService>>(),
|
||||
globalAdminMock.Object, delegatedAdminMock.Object, adminConfigService.Object,
|
||||
new TenantMemberRoleResolver(_tenantAdminsMock.Object, _tenantConfigMock.Object))
|
||||
new TenantMemberRoleResolver(_tenantAdminsMock.Object, _tenantConfigMock.Object), _tenantConfigMock.Object)
|
||||
{ CallBase = false };
|
||||
|
||||
_metricsRepoMock = new Mock<IMetricsRepository>();
|
||||
|
||||
@@ -55,6 +55,76 @@ public class AuthFunctionTests
|
||||
Assert.True((bool)body.hasMcpAccess);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HappyPath_SurfacesWhatsNewSeenMarks()
|
||||
{
|
||||
var platformSeen = new DateTime(2026, 9, 8, 10, 0, 0, DateTimeKind.Utc);
|
||||
var agentSeen = new DateTime(2026, 9, 8, 10, 5, 0, DateTimeKind.Utc);
|
||||
|
||||
var result = AuthFunction.BuildAuthResult(
|
||||
DefaultConfig(), isGlobalAdmin: false, isGlobalReader: false, isPreviewApproved: true,
|
||||
memberRole: AdminRole(), mcpCheck: McpAllowed(),
|
||||
hasTenantAdmins: true,
|
||||
TenantId, Upn, DisplayName, ObjectId,
|
||||
whatsNewSeenPlatformUtc: platformSeen,
|
||||
whatsNewSeenAgentUtc: agentSeen);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
var body = ToDynamic(result.Body);
|
||||
Assert.Equal(platformSeen, (DateTime)body.whatsNewSeenPlatformUtc);
|
||||
Assert.Equal(agentSeen, (DateTime)body.whatsNewSeenAgentUtc);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("platform", "platform")]
|
||||
[InlineData("Platform", "platform")]
|
||||
[InlineData("agent", "agent")]
|
||||
public void TryNormalizeWhatsNewSeen_AcceptsKnownChannels(string input, string expected)
|
||||
{
|
||||
var seen = new DateTime(2026, 9, 8, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
var ok = AuthFunction.TryNormalizeWhatsNewSeen(
|
||||
new WhatsNewSeenRequest { Channel = input, SeenUtc = seen },
|
||||
seen.AddMinutes(1),
|
||||
out var channel,
|
||||
out var seenUtc,
|
||||
out var error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(expected, channel);
|
||||
Assert.Equal(seen, seenUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryNormalizeWhatsNewSeen_RejectsUnknownChannel()
|
||||
{
|
||||
var ok = AuthFunction.TryNormalizeWhatsNewSeen(
|
||||
new WhatsNewSeenRequest { Channel = "other", SeenUtc = DateTime.UtcNow },
|
||||
DateTime.UtcNow,
|
||||
out _,
|
||||
out _,
|
||||
out var error);
|
||||
|
||||
Assert.False(ok);
|
||||
Assert.Equal("channel must be 'platform' or 'agent'", error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryNormalizeWhatsNewSeen_ClampsFarFutureTimestamp()
|
||||
{
|
||||
var now = new DateTime(2026, 9, 8, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
var ok = AuthFunction.TryNormalizeWhatsNewSeen(
|
||||
new WhatsNewSeenRequest { Channel = "agent", SeenUtc = now.AddMinutes(6) },
|
||||
now,
|
||||
out _,
|
||||
out var seenUtc,
|
||||
out var error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(now, seenUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HappyPath_OperatorUser_ReturnsCorrectRole()
|
||||
{
|
||||
|
||||
@@ -47,6 +47,12 @@ public class AutopilotDeviceValidatorTests
|
||||
new(status) { Content = new StringContent(body) };
|
||||
|
||||
private static (AutopilotDeviceValidator Sut, DelayingHandler Handler, MemoryCache Cache) BuildSut(params HttpResponseMessage?[] responses)
|
||||
{
|
||||
var built = BuildSutWithTokens(responses);
|
||||
return (built.Sut, built.Handler, built.Cache);
|
||||
}
|
||||
|
||||
private static (AutopilotDeviceValidator Sut, DelayingHandler Handler, MemoryCache Cache, Mock<GraphTokenService> Tokens) BuildSutWithTokens(params HttpResponseMessage?[] responses)
|
||||
{
|
||||
var handler = new DelayingHandler(responses);
|
||||
var factory = new Mock<IHttpClientFactory>();
|
||||
@@ -71,10 +77,52 @@ public class AutopilotDeviceValidatorTests
|
||||
|
||||
var sut = new AutopilotDeviceValidator(
|
||||
NullLogger<AutopilotDeviceValidator>.Instance, factory.Object, cache, tokenService.Object);
|
||||
return (sut, handler, cache);
|
||||
return (sut, handler, cache, tokenService);
|
||||
}
|
||||
|
||||
private const string FoundBody = "{\"value\":[{\"id\":\"ap-1\",\"serialNumber\":\"PF3XKQ7\"}]}";
|
||||
private const string ForbiddenBody = "{\"error\":{\"code\":\"Authorization_RequestDenied\",\"message\":\"Application is not authorized to perform this operation.\"}}";
|
||||
|
||||
[Fact]
|
||||
public async Task StaleTokenForbidden_ThenSuccess_InvalidatesOnce_AndValidatesWithTheFreshToken()
|
||||
{
|
||||
// Field case 2026-09-02: a second instance held a roleless app-only token minted before the
|
||||
// tenant's consent; Graph answered 403 for 45 minutes. Attempt 1 must drop that token and
|
||||
// attempt 2 must succeed with the re-minted one — no 503 loop, no cached negative.
|
||||
var (sut, handler, cache, tokens) = BuildSutWithTokens(
|
||||
Json(ForbiddenBody, HttpStatusCode.Forbidden),
|
||||
Json(FoundBody));
|
||||
|
||||
var result = await sut.ValidateAutopilotDeviceAsync(TenantId, Serial, null, CancellationToken.None);
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
Assert.Equal("ap-1", result.AutopilotDeviceId);
|
||||
Assert.Equal(2, handler.Requests.Count);
|
||||
tokens.Verify(t => t.InvalidateTenant(TenantId), Times.Once);
|
||||
tokens.Verify(t => t.GetAccessTokenAsync(TenantId, It.IsAny<CancellationToken>()), Times.Exactly(2));
|
||||
Assert.True(cache.TryGetValue($"autopilot-device-validation:{TenantId}:{Serial}", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ForbiddenWithFreshToken_StaysTransient_WithLongerRetryAfter_NotCached()
|
||||
{
|
||||
// Consent genuinely missing (or not yet propagated): the agent must keep getting 503 (a 403
|
||||
// would make it shut down as "device not registered"), but with the permission-gap
|
||||
// Retry-After and nothing cached so a granted consent takes effect on the next call.
|
||||
var (sut, handler, cache, tokens) = BuildSutWithTokens(
|
||||
Json(ForbiddenBody, HttpStatusCode.Forbidden),
|
||||
Json(ForbiddenBody, HttpStatusCode.Forbidden));
|
||||
|
||||
var result = await sut.ValidateAutopilotDeviceAsync(TenantId, Serial, null, CancellationToken.None);
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
Assert.True(result.IsTransient);
|
||||
Assert.Equal(GraphAuthFailure.PermissionMissingRetryAfterSeconds, result.RetryAfterSeconds);
|
||||
Assert.Contains("permission missing", result.ErrorMessage);
|
||||
Assert.Equal(2, handler.Requests.Count);
|
||||
tokens.Verify(t => t.InvalidateTenant(TenantId), Times.Once);
|
||||
Assert.False(cache.TryGetValue($"autopilot-device-validation:{TenantId}:{Serial}", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Budget_defaults_sit_inside_the_agents_30s_client_timeout()
|
||||
|
||||
+5
-3
@@ -61,7 +61,8 @@ public class AzureQueueImeMsiArchiveProducerTests
|
||||
public async Task EnqueueAsync_send_failure_is_swallowed()
|
||||
{
|
||||
var (producer, queue, _) = BuildSut();
|
||||
queue.Setup(q => q.SendMessageAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
queue.Setup(q => q.SendMessageAsync(
|
||||
It.IsAny<string>(), It.IsAny<TimeSpan?>(), It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new RequestFailedException(503, "queue busy"));
|
||||
|
||||
// Fire-and-forget continuation on the ingest path — must never throw.
|
||||
@@ -107,8 +108,9 @@ public class AzureQueueImeMsiArchiveProducerTests
|
||||
queue.Setup(q => q.CreateIfNotExistsAsync(
|
||||
It.IsAny<IDictionary<string, string>>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync((Response?)null);
|
||||
queue.Setup(q => q.SendMessageAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.Returns<string, CancellationToken>((body, _) =>
|
||||
queue.Setup(q => q.SendMessageAsync(
|
||||
It.IsAny<string>(), It.IsAny<TimeSpan?>(), It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>()))
|
||||
.Returns<string, TimeSpan?, TimeSpan?, CancellationToken>((body, _, _, _) =>
|
||||
{
|
||||
sentBodies.Add(body);
|
||||
var receipt = QueuesModelFactory.SendReceipt(
|
||||
|
||||
@@ -53,4 +53,94 @@ public class BuiltInRuleCatalogPolicyTests
|
||||
Assert.True(duplicates.Count == 0,
|
||||
$"Duplicate built-in gather rule IDs: {string.Join(", ", duplicates)}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Built-in rules that assert an ABSENCE (required not_exists) of an event the agent derives
|
||||
/// from the IME logs, and deliberately do NOT carry the ime_tracker_degraded coverage gate.
|
||||
/// Every entry is a decision with a reason; adding one here is the way to ship such a rule.
|
||||
/// </summary>
|
||||
private static readonly IReadOnlyDictionary<string, string> AbsenceWithoutCoverageGate =
|
||||
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["ANALYZE-ID-004"] =
|
||||
"A hybrid session whose user never obtained an Entra token must not lose its finding because " +
|
||||
"the tracker skipped the remaining patterns on one line; the tracker state is shown next to " +
|
||||
"the finding in get_session_summary (coverage) instead (plan session-coverage-and-absence-audit).",
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Required_not_exists_on_ime_derived_events_is_coverage_gated_or_documented()
|
||||
{
|
||||
// "Absence proves nothing": a required not_exists on an IME-log-derived event evaluates
|
||||
// to true both when the event never happened and when the IME log tracker skipped the
|
||||
// line that carried it (ime_tracker_degraded). A built-in rule that asserts such an
|
||||
// absence either suppresses itself on degraded sessions (precondition
|
||||
// ime_tracker_degraded not_exists) or is listed above with the reason it does not.
|
||||
// The IME-derived list is the guardrails.json mirror the MCP validate_rule lint reads,
|
||||
// so catalog and pre-flight judge by one list.
|
||||
var guardrailsPath = Path.Combine(FindRepoRoot(), "rules", "guardrails.json");
|
||||
var json = Newtonsoft.Json.Linq.JObject.Parse(File.ReadAllText(guardrailsPath));
|
||||
var imeDerived = new HashSet<string>(
|
||||
json["imeLogDerivedEventTypes"]!.ToObject<string[]>()!, StringComparer.OrdinalIgnoreCase);
|
||||
Assert.Contains("ime_user_token_acquired", imeDerived);
|
||||
|
||||
var offenders = new List<string>();
|
||||
foreach (var rule in BuiltInAnalyzeRules.GetAll())
|
||||
{
|
||||
var assertsImeAbsence = rule.Conditions.Any(c =>
|
||||
c.Required
|
||||
&& string.Equals(c.Operator, "not_exists", StringComparison.OrdinalIgnoreCase)
|
||||
&& string.IsNullOrEmpty(c.DataField)
|
||||
&& !string.IsNullOrEmpty(c.EventType)
|
||||
&& imeDerived.Contains(c.EventType));
|
||||
if (!assertsImeAbsence) continue;
|
||||
|
||||
var gated = rule.Preconditions.Any(p =>
|
||||
string.Equals(p.EventType, "ime_tracker_degraded", StringComparison.OrdinalIgnoreCase)
|
||||
&& string.Equals(p.Operator, "not_exists", StringComparison.OrdinalIgnoreCase)
|
||||
&& string.IsNullOrEmpty(p.DataField));
|
||||
if (gated || AbsenceWithoutCoverageGate.ContainsKey(rule.RuleId)) continue;
|
||||
offenders.Add(rule.RuleId);
|
||||
}
|
||||
|
||||
Assert.True(offenders.Count == 0,
|
||||
"Built-in rules assert the absence of an IME-log-derived event without the " +
|
||||
"ime_tracker_degraded coverage precondition and without a documented exception: " +
|
||||
string.Join(", ", offenders));
|
||||
|
||||
// The exception list must not outlive the rules it excuses.
|
||||
var catalogIds = new HashSet<string>(BuiltInAnalyzeRules.GetAll().Select(r => r.RuleId), StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var excused in AbsenceWithoutCoverageGate.Keys)
|
||||
Assert.True(catalogIds.Contains(excused), $"Exception list names a rule that is not in the catalog: {excused}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ime_derived_list_names_only_real_event_types_and_the_tracker_event_exists()
|
||||
{
|
||||
var guardrailsPath = Path.Combine(FindRepoRoot(), "rules", "guardrails.json");
|
||||
var json = Newtonsoft.Json.Linq.JObject.Parse(File.ReadAllText(guardrailsPath));
|
||||
var imeDerived = json["imeLogDerivedEventTypes"]!.ToObject<string[]>()!;
|
||||
|
||||
var known = new HashSet<string>(
|
||||
typeof(AutopilotMonitor.Shared.Constants.EventTypes)
|
||||
.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
|
||||
.Where(f => f.IsLiteral && f.FieldType == typeof(string))
|
||||
.Select(f => (string)f.GetRawConstantValue()!),
|
||||
StringComparer.Ordinal);
|
||||
|
||||
var phantom = imeDerived.Where(t => !known.Contains(t)).ToList();
|
||||
Assert.True(phantom.Count == 0, $"imeLogDerivedEventTypes lists unknown event types: {string.Join(", ", phantom)}");
|
||||
Assert.Contains(AutopilotMonitor.Shared.Constants.EventTypes.ImeTrackerDegraded, known);
|
||||
}
|
||||
|
||||
private static string FindRepoRoot()
|
||||
{
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (dir != null && !File.Exists(Path.Combine(dir.FullName, "AutopilotMonitor.sln")))
|
||||
{
|
||||
dir = dir.Parent;
|
||||
}
|
||||
Assert.NotNull(dir);
|
||||
return dir!.FullName;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ public class BuiltInRulesTests
|
||||
"healthScriptResult", "healthScriptDetectionResult",
|
||||
"captureExitCode", "captureHResult",
|
||||
"captureAppVersion", "captureAppTypeWinGet", "captureAppTypeMsi",
|
||||
"captureAttemptNumber", "captureDetectionResult"
|
||||
"captureAttemptNumber", "captureDetectionResult", "captureExitCodeClass"
|
||||
};
|
||||
|
||||
var patterns = BuiltInImeLogPatterns.GetAll();
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Models.Config;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Concurrent cache misses on the two configuration services share one repository read
|
||||
/// (audit 2026-09-05 F12). The MemoryCache stays: the hit path and the in-place projection
|
||||
/// semantics are untouched, only the miss path is single-flighted.
|
||||
/// </summary>
|
||||
public class ConfigurationServiceSingleFlightTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Admin_config_concurrent_misses_issue_one_repository_read()
|
||||
{
|
||||
var gate = new TaskCompletionSource<AdminConfiguration?>();
|
||||
var repo = new Mock<IConfigRepository>();
|
||||
repo.Setup(r => r.GetAdminConfigurationAsync()).Returns(gate.Task);
|
||||
var sut = new AdminConfigurationService(repo.Object, NullLogger<AdminConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
|
||||
|
||||
var calls = Enumerable.Range(0, 10).Select(_ => sut.GetConfigurationAsync()).ToArray();
|
||||
gate.SetResult(AdminConfiguration.CreateDefault());
|
||||
var results = await Task.WhenAll(calls);
|
||||
|
||||
repo.Verify(r => r.GetAdminConfigurationAsync(), Times.Once);
|
||||
Assert.All(results, r => Assert.Same(results[0], r));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admin_config_after_completion_the_next_miss_reads_again()
|
||||
{
|
||||
var repo = new Mock<IConfigRepository>();
|
||||
repo.Setup(r => r.GetAdminConfigurationAsync()).ReturnsAsync(AdminConfiguration.CreateDefault());
|
||||
var sut = new AdminConfigurationService(repo.Object, NullLogger<AdminConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
|
||||
|
||||
await sut.GetConfigurationAsync();
|
||||
sut.InvalidateCache();
|
||||
await sut.GetConfigurationAsync();
|
||||
|
||||
repo.Verify(r => r.GetAdminConfigurationAsync(), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Tenant_config_concurrent_misses_for_one_tenant_issue_one_repository_read()
|
||||
{
|
||||
const string tenantId = "11111111-1111-1111-1111-111111111111";
|
||||
var gate = new TaskCompletionSource<TenantConfiguration?>();
|
||||
var repo = new Mock<IConfigRepository>();
|
||||
repo.Setup(r => r.GetTenantConfigurationAsync(tenantId)).Returns(gate.Task);
|
||||
var sut = new TenantConfigurationService(repo.Object, NullLogger<TenantConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
|
||||
|
||||
var calls = Enumerable.Range(0, 10).Select(_ => sut.GetConfigurationAsync(tenantId)).ToArray();
|
||||
gate.SetResult(TenantConfiguration.CreateDefault(tenantId));
|
||||
var results = await Task.WhenAll(calls);
|
||||
|
||||
repo.Verify(r => r.GetTenantConfigurationAsync(tenantId), Times.Once);
|
||||
Assert.All(results, r => Assert.Same(results[0], r));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Tenant_config_different_tenants_do_not_share_a_flight()
|
||||
{
|
||||
const string a = "11111111-1111-1111-1111-111111111111";
|
||||
const string b = "22222222-2222-2222-2222-222222222222";
|
||||
var repo = new Mock<IConfigRepository>();
|
||||
repo.Setup(r => r.GetTenantConfigurationAsync(It.IsAny<string>()))
|
||||
.Returns<string>(id => Task.FromResult<TenantConfiguration?>(TenantConfiguration.CreateDefault(id)));
|
||||
var sut = new TenantConfigurationService(repo.Object, NullLogger<TenantConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
|
||||
|
||||
await Task.WhenAll(sut.GetConfigurationAsync(a), sut.GetConfigurationAsync(b));
|
||||
|
||||
repo.Verify(r => r.GetTenantConfigurationAsync(a), Times.Once);
|
||||
repo.Verify(r => r.GetTenantConfigurationAsync(b), Times.Once);
|
||||
}
|
||||
}
|
||||
@@ -224,17 +224,36 @@ public class CorporateIdentifierValidatorTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAsync_graphPermissionDenied_isCached_notRetried()
|
||||
public async Task ValidateAsync_graphPermissionDenied_isCached_afterOneFreshTokenRetry()
|
||||
{
|
||||
// Definitive permission failures are negative-cached so an agent retry storm does not
|
||||
// hammer Graph while consent is being fixed; the in-call retry loop must not fire either.
|
||||
// hammer Graph while consent is being fixed. Attempt 1 may have used a token minted before
|
||||
// the consent (GraphAuthFailure), so exactly ONE retry with a fresh token precedes the
|
||||
// verdict; the cached verdict then answers the next call without Graph.
|
||||
var (sut, handler) = BuildSut(Json("""{"error":{"code":"Forbidden"}}""", HttpStatusCode.Forbidden));
|
||||
|
||||
await sut.ValidateAsync(TenantId, "Microsoft Corporation", "Virtual Machine", Serial);
|
||||
var first = await sut.ValidateAsync(TenantId, "Microsoft Corporation", "Virtual Machine", Serial);
|
||||
var second = await sut.ValidateAsync(TenantId, "Microsoft Corporation", "Virtual Machine", Serial);
|
||||
|
||||
Assert.False(first.IsTransient);
|
||||
Assert.False(second.IsValid);
|
||||
Assert.Single(handler.Requests);
|
||||
Assert.Equal(2, handler.Requests.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAsync_staleTokenForbidden_thenFound_validatesWithTheFreshToken()
|
||||
{
|
||||
// Field case 2026-09-02 in this validator's shape: a stale roleless token gets 403, the
|
||||
// fresh one finds the identifier. Without the retry the stale token would have been cached
|
||||
// as "not permitted" for 5 minutes, every 5 minutes, until its 55-minute TTL.
|
||||
var (sut, handler) = BuildSut(
|
||||
Json("""{"error":{"code":"Forbidden"}}""", HttpStatusCode.Forbidden),
|
||||
Json($$"""{"value":[{"importedDeviceIdentityType":"manufacturerModelSerial","importedDeviceIdentifier":"{{StoredIdentifier}}"}]}"""));
|
||||
|
||||
var result = await sut.ValidateAsync(TenantId, "Microsoft Corporation", "Virtual Machine", Serial);
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
Assert.Equal(2, handler.Requests.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -182,6 +182,7 @@ public class CrossTenantAccessTests
|
||||
|
||||
[Theory]
|
||||
[InlineData("PATCH", "/api/config/{0}/plan")]
|
||||
[InlineData("GET", "/api/config/{0}/effective-agent-config")]
|
||||
[InlineData("POST", "/api/preview/whitelist/{0}")]
|
||||
[InlineData("DELETE", "/api/preview/whitelist/{0}")]
|
||||
[InlineData("POST", "/api/preview/send-welcome-email/{0}")]
|
||||
|
||||
@@ -1,179 +0,0 @@
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for <see cref="DecisionGraphBuilder"/> — pure projection, zero IO. Covers node
|
||||
/// de-duplication, terminal classification, dead-end preservation, visit-count semantics, and
|
||||
/// empty / out-of-order inputs.
|
||||
/// </summary>
|
||||
public class DecisionGraphBuilderTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "b2c3d4e5-f6a7-8901-bcde-f12345678901";
|
||||
|
||||
private static DecisionTransitionRecord Transition(
|
||||
int step, string from, string to, bool taken = true, string? deadEnd = null, string trigger = "t",
|
||||
string reducer = "1.0.0")
|
||||
=> new DecisionTransitionRecord
|
||||
{
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
StepIndex = step,
|
||||
FromStage = from,
|
||||
ToStage = to,
|
||||
Taken = taken,
|
||||
DeadEndReason = deadEnd,
|
||||
Trigger = trigger,
|
||||
ReducerVersion = reducer,
|
||||
IsTerminal = DecisionGraphBuilder.IsTerminalStage(to),
|
||||
OccurredAtUtc = new DateTime(2026, 4, 21, 10, step, 0, DateTimeKind.Utc),
|
||||
};
|
||||
|
||||
// ============================================================ Empty input
|
||||
|
||||
[Fact]
|
||||
public void Build_returns_empty_projection_when_no_transitions()
|
||||
{
|
||||
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, Array.Empty<DecisionTransitionRecord>());
|
||||
|
||||
Assert.Equal(TenantId, graph.TenantId);
|
||||
Assert.Equal(SessionId, graph.SessionId);
|
||||
Assert.Empty(graph.Nodes);
|
||||
Assert.Empty(graph.Edges);
|
||||
Assert.Equal(string.Empty, graph.ReducerVersion);
|
||||
}
|
||||
|
||||
// ============================================================ Node de-duplication
|
||||
|
||||
[Fact]
|
||||
public void Build_deduplicates_stages_into_unique_nodes()
|
||||
{
|
||||
// Same stage visited twice through different paths — appears once in Nodes.
|
||||
var transitions = new[]
|
||||
{
|
||||
Transition(0, "SessionStarted", "EspInProgress"),
|
||||
Transition(1, "EspInProgress", "AccountSetup"),
|
||||
Transition(2, "AccountSetup", "EspInProgress"), // back-edge (hypothetical)
|
||||
Transition(3, "EspInProgress", "Completed"),
|
||||
};
|
||||
|
||||
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
|
||||
|
||||
// Unique stages: SessionStarted, EspInProgress, AccountSetup, Completed = 4 nodes.
|
||||
Assert.Equal(4, graph.Nodes.Count);
|
||||
Assert.Contains(graph.Nodes, n => n.Id == "SessionStarted");
|
||||
Assert.Contains(graph.Nodes, n => n.Id == "EspInProgress");
|
||||
Assert.Contains(graph.Nodes, n => n.Id == "AccountSetup");
|
||||
Assert.Contains(graph.Nodes, n => n.Id == "Completed");
|
||||
}
|
||||
|
||||
// ============================================================ Terminal classification
|
||||
|
||||
[Theory]
|
||||
[InlineData("Completed", "Succeeded")]
|
||||
[InlineData("Failed", "Failed")]
|
||||
[InlineData("WhiteGloveSealed", "PausedForPart2")]
|
||||
public void Build_marks_terminal_stages_and_derives_outcome(string terminalStage, string expectedOutcome)
|
||||
{
|
||||
var transitions = new[]
|
||||
{
|
||||
Transition(0, "Start", terminalStage),
|
||||
};
|
||||
|
||||
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
|
||||
var node = graph.Nodes.Single(n => n.Id == terminalStage);
|
||||
|
||||
Assert.True(node.IsTerminal);
|
||||
Assert.Equal(expectedOutcome, node.TerminalOutcome);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_leaves_non_terminal_nodes_unmarked()
|
||||
{
|
||||
var transitions = new[] { Transition(0, "SessionStarted", "EspInProgress") };
|
||||
|
||||
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
|
||||
|
||||
Assert.All(graph.Nodes, n =>
|
||||
{
|
||||
Assert.False(n.IsTerminal);
|
||||
Assert.Null(n.TerminalOutcome);
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================================ Edges
|
||||
|
||||
[Fact]
|
||||
public void Build_preserves_all_edges_including_dead_ends()
|
||||
{
|
||||
var transitions = new[]
|
||||
{
|
||||
Transition(0, "EspInProgress", "Completed", taken: true),
|
||||
Transition(1, "EspInProgress", "EspInProgress", taken: false,
|
||||
deadEnd: "hybrid_reboot_gate_blocking", trigger: "EspExiting"),
|
||||
};
|
||||
|
||||
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
|
||||
|
||||
Assert.Equal(2, graph.Edges.Count);
|
||||
Assert.Contains(graph.Edges, e => e.Taken && e.ToStage == "Completed");
|
||||
var deadEnd = graph.Edges.Single(e => !e.Taken);
|
||||
Assert.Equal("hybrid_reboot_gate_blocking", deadEnd.DeadEndReason);
|
||||
Assert.Equal("EspExiting", deadEnd.Trigger);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_orders_edges_by_StepIndex_even_if_input_is_shuffled()
|
||||
{
|
||||
// Repository sorts, but defend anyway — the builder is used directly in tests and
|
||||
// could be fed arbitrary lists.
|
||||
var transitions = new[]
|
||||
{
|
||||
Transition(2, "AccountSetup", "Completed"),
|
||||
Transition(0, "SessionStarted", "EspInProgress"),
|
||||
Transition(1, "EspInProgress", "AccountSetup"),
|
||||
};
|
||||
|
||||
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
|
||||
|
||||
Assert.Equal(new[] { 0, 1, 2 }, graph.Edges.Select(e => e.StepIndex));
|
||||
}
|
||||
|
||||
// ============================================================ VisitCount
|
||||
|
||||
[Fact]
|
||||
public void Build_counts_only_taken_transitions_toward_VisitCount()
|
||||
{
|
||||
var transitions = new[]
|
||||
{
|
||||
Transition(0, "Start", "EspInProgress", taken: true),
|
||||
Transition(1, "EspInProgress", "EspInProgress", taken: false, deadEnd: "blocked"),
|
||||
Transition(2, "EspInProgress", "Completed", taken: true),
|
||||
Transition(3, "Start", "EspInProgress", taken: true), // hypothetical retry
|
||||
};
|
||||
|
||||
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
|
||||
|
||||
var esp = graph.Nodes.Single(n => n.Id == "EspInProgress");
|
||||
Assert.Equal(2, esp.VisitCount); // two taken → EspInProgress; the dead-end does not count
|
||||
|
||||
var completed = graph.Nodes.Single(n => n.Id == "Completed");
|
||||
Assert.Equal(1, completed.VisitCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_exposes_ReducerVersion_from_first_row()
|
||||
{
|
||||
var transitions = new[]
|
||||
{
|
||||
Transition(0, "Start", "EspInProgress", reducer: "1.4.2"),
|
||||
Transition(1, "EspInProgress", "Completed", reducer: "1.4.2"),
|
||||
};
|
||||
|
||||
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
|
||||
|
||||
Assert.Equal("1.4.2", graph.ReducerVersion);
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ public class DelegationWireParityTests
|
||||
{
|
||||
error = "Delegated tenant slot limit reached for partner.example: 2 of 2 slot(s) in use, 1 more needed. Raise the tenant's limit (plan package or Global Admin override) and retry.",
|
||||
code = "DelegatedSlotLimitReached",
|
||||
correlationId = "",
|
||||
homeTenantId = Home,
|
||||
homeTenantDomain = "partner.example",
|
||||
used = 2,
|
||||
@@ -47,6 +48,7 @@ public class DelegationWireParityTests
|
||||
{
|
||||
error = $"Delegated tenant slot limit reached for {Home}: 3 of 3 slot(s) in use, 2 more needed. Raise the tenant's limit (plan package or Global Admin override) and retry.",
|
||||
code = "DelegatedSlotLimitReached",
|
||||
correlationId = "",
|
||||
homeTenantId = Home,
|
||||
homeTenantDomain,
|
||||
used = 3,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
using System.Net;
|
||||
using System.Reflection;
|
||||
using AutopilotMonitor.Functions.Functions.Sessions;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Functions.Services.Deletion;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
@@ -59,6 +60,9 @@ public class DeleteSessionFunctionTests
|
||||
}
|
||||
|
||||
// ── BuildV2ResponseBody ───────────────────────────────────────────────────────────────
|
||||
// The success arm is SessionDeletionQueuedResponse; every rejected arm is the typed error body
|
||||
// SessionDeletionRejectedResponse (envelope prefix error/code/correlationId + lock diagnostics).
|
||||
// The correlation id is stamped by the writer, so the builder leaves it empty here.
|
||||
|
||||
[Fact]
|
||||
public void BuildV2ResponseBody_Enqueued_carries_manifestId_and_queued_status()
|
||||
@@ -69,15 +73,15 @@ public class DeleteSessionFunctionTests
|
||||
ManifestId = ManifestId,
|
||||
};
|
||||
|
||||
var body = DeleteSessionFunction.BuildV2ResponseBody(result, SessionId);
|
||||
var body = Assert.IsType<SessionDeletionQueuedResponse>(DeleteSessionFunction.BuildV2ResponseBody(result, SessionId));
|
||||
|
||||
AssertProperty(body, "success", true);
|
||||
AssertProperty(body, "status", "queued");
|
||||
AssertProperty(body, "manifestId", ManifestId);
|
||||
Assert.True(body.Success);
|
||||
Assert.Equal("queued", body.Status);
|
||||
Assert.Equal(ManifestId, body.ManifestId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildV2ResponseBody_AlreadyInFlight_carries_state_and_manifestId_with_hint()
|
||||
public void BuildV2ResponseBody_AlreadyInFlight_carries_state_and_manifestId_with_code()
|
||||
{
|
||||
var result = new SessionDeletionEnqueueResult
|
||||
{
|
||||
@@ -86,12 +90,11 @@ public class DeleteSessionFunctionTests
|
||||
ExistingState = "Running",
|
||||
};
|
||||
|
||||
var body = DeleteSessionFunction.BuildV2ResponseBody(result, SessionId);
|
||||
var body = Rejected(DeleteSessionFunction.BuildV2ResponseBody(result, SessionId));
|
||||
|
||||
AssertProperty(body, "success", false);
|
||||
AssertProperty(body, "manifestId", ManifestId);
|
||||
AssertProperty(body, "deletionState", "Running");
|
||||
AssertProperty(body, "hint", "cascade_already_in_flight");
|
||||
Assert.Equal(Constants.ApiErrorCodes.CascadeAlreadyInFlight, body.Code);
|
||||
Assert.Equal(ManifestId, body.ManifestId);
|
||||
Assert.Equal("Running", body.DeletionState);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -106,13 +109,12 @@ public class DeleteSessionFunctionTests
|
||||
ExistingState = "Poisoned",
|
||||
};
|
||||
|
||||
var body = DeleteSessionFunction.BuildV2ResponseBody(result, SessionId);
|
||||
var body = Rejected(DeleteSessionFunction.BuildV2ResponseBody(result, SessionId));
|
||||
|
||||
AssertProperty(body, "hint", "cascade_poisoned_use_restore");
|
||||
AssertProperty(body, "manifestId", ManifestId);
|
||||
Assert.Equal(Constants.ApiErrorCodes.CascadePoisonedUseRestore, body.Code);
|
||||
Assert.Equal(ManifestId, body.ManifestId);
|
||||
// The message string must mention the restore endpoint so the UI surfaces it verbatim.
|
||||
var message = GetProperty<string>(body, "message");
|
||||
Assert.Contains("/restore", message);
|
||||
Assert.Contains("/restore", body.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -126,10 +128,27 @@ public class DeleteSessionFunctionTests
|
||||
Outcome = SessionDeletionEnqueueOutcome.KillSwitchActive,
|
||||
};
|
||||
|
||||
var body = DeleteSessionFunction.BuildV2ResponseBody(result, SessionId);
|
||||
var body = Rejected(DeleteSessionFunction.BuildV2ResponseBody(result, SessionId));
|
||||
|
||||
AssertProperty(body, "hint", "kill_switch_active");
|
||||
Assert.False(HasProperty(body, "manifestId"));
|
||||
Assert.Equal(Constants.ApiErrorCodes.KillSwitchActive, body.Code);
|
||||
Assert.Null(body.ManifestId);
|
||||
Assert.DoesNotContain("manifestId", TestWire.Serialize(body));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildV2ResponseBody_rejected_arms_serialize_with_the_envelope_prefix()
|
||||
{
|
||||
var result = new SessionDeletionEnqueueResult
|
||||
{
|
||||
Outcome = SessionDeletionEnqueueOutcome.SessionNotFound,
|
||||
};
|
||||
|
||||
var body = Rejected(DeleteSessionFunction.BuildV2ResponseBody(result, SessionId));
|
||||
body.CorrelationId = "cid-1";
|
||||
|
||||
Assert.Equal(
|
||||
$"{{\"error\":\"Session {SessionId} not found\",\"code\":\"NotFound\",\"correlationId\":\"cid-1\"}}",
|
||||
TestWire.Serialize(body));
|
||||
}
|
||||
|
||||
// ── EvaluateAdminDeleteGates (kill-switch short-circuit) ──────────────────────────────
|
||||
@@ -141,10 +160,10 @@ public class DeleteSessionFunctionTests
|
||||
|
||||
Assert.NotNull(gate);
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, gate!.Value.Status);
|
||||
AssertProperty(gate.Value.Body, "hint", "kill_switch_active");
|
||||
Assert.Equal(Constants.ApiErrorCodes.KillSwitchActive, gate.Value.Body.Code);
|
||||
// The kill-switch body must NOT carry a manifestId so the UI doesn't render a
|
||||
// "track this cascade" link for a request that was refused.
|
||||
Assert.False(HasProperty(gate.Value.Body, "manifestId"));
|
||||
Assert.Null(gate.Value.Body.ManifestId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -157,25 +176,6 @@ public class DeleteSessionFunctionTests
|
||||
Assert.Null(gate);
|
||||
}
|
||||
|
||||
// ── Anonymous-object reflection helpers ───────────────────────────────────────────────
|
||||
|
||||
// IgnoreCase: the Enqueued arm is a typed DTO (PascalCase properties, camelCased on the
|
||||
// wire by ApiJsonOptions); the error arms stay anonymous (camelCase). Both resolve here.
|
||||
private static void AssertProperty(object body, string propertyName, object? expected)
|
||||
{
|
||||
var prop = body.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
|
||||
Assert.NotNull(prop);
|
||||
Assert.Equal(expected, prop!.GetValue(body));
|
||||
}
|
||||
|
||||
private static T GetProperty<T>(object body, string propertyName)
|
||||
{
|
||||
var prop = body.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
|
||||
Assert.NotNull(prop);
|
||||
var value = prop!.GetValue(body);
|
||||
return (T)value!;
|
||||
}
|
||||
|
||||
private static bool HasProperty(object body, string propertyName) =>
|
||||
body.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance) != null;
|
||||
private static SessionDeletionRejectedResponse Rejected(IApiResponse body)
|
||||
=> Assert.IsType<SessionDeletionRejectedResponse>(body);
|
||||
}
|
||||
|
||||
@@ -46,12 +46,7 @@ public class DeletionManifestBuilderTests
|
||||
.WithSignals(15)
|
||||
.WithDecisionTransitions(4)
|
||||
.WithEventTypeIndex(5)
|
||||
.WithCveIndex(2)
|
||||
.WithSessionsByTerminal(1)
|
||||
.WithSessionsByStage(3)
|
||||
.WithDeadEndsByReason(0)
|
||||
.WithClassifierVerdictsByIdLevel(2)
|
||||
.WithSignalsByKind(11));
|
||||
.WithCveIndex(2));
|
||||
|
||||
var manifest = await NewBuilder(reader).BuildAsync(
|
||||
TenantId, SessionId, "admin_delete",
|
||||
@@ -69,15 +64,10 @@ public class DeletionManifestBuilderTests
|
||||
Assert.Equal(4, c["decisionTransitions"]);
|
||||
Assert.Equal(5, c["eventTypeIndex"]);
|
||||
Assert.Equal(2, c["cveIndex"]);
|
||||
Assert.Equal(1, c["sessionsByTerminal"]);
|
||||
Assert.Equal(3, c["sessionsByStage"]);
|
||||
Assert.Equal(0, c["deadEndsByReason"]);
|
||||
Assert.Equal(2, c["classifierVerdictsByIdLevel"]);
|
||||
Assert.Equal(11, c["signalsByKind"]);
|
||||
|
||||
// 20 cascade tables (incl. SessionTimeBreakdowns F1 PR2, 3 SessionAnnotations lanes +
|
||||
// SessionTenantLookup P6.1) + tombstone = 21 steps; no inventory steps when no contributions row.
|
||||
Assert.Equal(21, manifest.Steps.Count);
|
||||
// 15 cascade tables (incl. SessionTimeBreakdowns F1 PR2, 3 SessionAnnotations lanes +
|
||||
// SessionTenantLookup P6.1) + tombstone = 16 steps; no inventory steps when no contributions row.
|
||||
Assert.Equal(16, manifest.Steps.Count);
|
||||
Assert.Equal(DeletionStepClass.Final, manifest.Steps.Last().Class);
|
||||
}
|
||||
|
||||
@@ -99,11 +89,6 @@ public class DeletionManifestBuilderTests
|
||||
.WithDecisionTransitions(1, propValue: "transitions_marker")
|
||||
.WithEventTypeIndex(1, propValue: "eti_marker")
|
||||
.WithCveIndex(1, propValue: "cve_marker")
|
||||
.WithSessionsByTerminal(1, propValue: "terminal_marker")
|
||||
.WithSessionsByStage(1, propValue: "stage_marker")
|
||||
.WithDeadEndsByReason(1, propValue: "deadend_marker")
|
||||
.WithClassifierVerdictsByIdLevel(1, propValue: "classifier_marker")
|
||||
.WithSignalsByKind(1, propValue: "signalkind_marker")
|
||||
.WithSessionTimeBreakdown(propValue: "breakdown_marker")
|
||||
.WithSessionAnnotations(propValue: "annotation_marker")
|
||||
.WithSessionTenantLookup(propValue: "lookup_marker"));
|
||||
@@ -149,9 +134,9 @@ public class DeletionManifestBuilderTests
|
||||
new DeletionRetentionContext { TenantRetentionDays = 90 });
|
||||
|
||||
var nonTombstoneSteps = manifest.Steps.Where(s => s.Class != DeletionStepClass.Final).ToList();
|
||||
// Without a contributions row, neither inventory step is emitted → exactly 20 cascade-table steps
|
||||
// (16 + the 3 SessionAnnotations lane steps + SessionTenantLookup).
|
||||
Assert.Equal(20, nonTombstoneSteps.Count);
|
||||
// Without a contributions row, neither inventory step is emitted → exactly 15 cascade-table steps
|
||||
// (11 + the 3 SessionAnnotations lane steps + SessionTenantLookup).
|
||||
Assert.Equal(15, nonTombstoneSteps.Count);
|
||||
foreach (var step in nonTombstoneSteps)
|
||||
{
|
||||
Assert.Equal(0, step.RowCount);
|
||||
@@ -180,8 +165,8 @@ public class DeletionManifestBuilderTests
|
||||
new DeletionActor { Type = "admin", Actor = "alice@example.com" },
|
||||
new DeletionRetentionContext { TenantRetentionDays = 90 });
|
||||
|
||||
// Expect: 20 cascade + 2 inventory + 1 tombstone = 23 steps.
|
||||
Assert.Equal(23, manifest.Steps.Count);
|
||||
// Expect: 15 cascade + 2 inventory + 1 tombstone = 18 steps.
|
||||
Assert.Equal(18, manifest.Steps.Count);
|
||||
|
||||
var aggregate = manifest.Steps.Single(s => s.Class == DeletionStepClass.Aggregate);
|
||||
Assert.Equal(DeletionStepNames.SoftwareInventoryDecrement, aggregate.Step);
|
||||
@@ -310,8 +295,7 @@ public class DeletionManifestBuilderTests
|
||||
.WithSessionsRow()
|
||||
.WithSessionsIndexRow()
|
||||
.WithEvents(3)
|
||||
.WithSignals(5)
|
||||
.WithSessionsByTerminal(1));
|
||||
.WithSignals(5));
|
||||
|
||||
var first = await NewBuilder(reader).BuildAsync(TenantId, SessionId, "admin_delete",
|
||||
new DeletionActor { Type = "admin", Actor = "alice@example.com" },
|
||||
@@ -345,7 +329,6 @@ public class DeletionManifestBuilderTests
|
||||
.WithSessionsIndexRow()
|
||||
.WithEvents(2, propValue: "events_check")
|
||||
.WithRuleResults(1, propValue: "rules_check")
|
||||
.WithSessionsByTerminal(1, propValue: "terminal_check")
|
||||
.WithSessionInventoryContributions(MakeContributionsRow(new List<DeletionDecrementKey>
|
||||
{
|
||||
new DeletionDecrementKey { Vendor = "Contoso", Name = "App", Version = "1.0" },
|
||||
@@ -778,12 +761,6 @@ public class DeletionManifestBuilderTests
|
||||
return this;
|
||||
}
|
||||
|
||||
public ReaderSeed WithSessionsByTerminal(int n, string propValue = "term") => SeedDiscriminatorPkProp(Constants.TableNames.SessionsByTerminal, n, propValue, "Failed");
|
||||
public ReaderSeed WithSessionsByStage(int n, string propValue = "stg") => SeedDiscriminatorPkProp(Constants.TableNames.SessionsByStage, n, propValue, "AccountSetup");
|
||||
public ReaderSeed WithDeadEndsByReason(int n, string propValue = "de") => SeedDiscriminatorPkProp(Constants.TableNames.DeadEndsByReason, n, propValue, "Timeout");
|
||||
public ReaderSeed WithClassifierVerdictsByIdLevel(int n, string propValue = "cls") => SeedDiscriminatorPkProp(Constants.TableNames.ClassifierVerdictsByIdLevel, n, propValue, "EspApps_High");
|
||||
public ReaderSeed WithSignalsByKind(int n, string propValue = "sk") => SeedDiscriminatorPkProp(Constants.TableNames.SignalsByKind, n, propValue, "EspPhaseChanged");
|
||||
|
||||
public ReaderSeed WithSessionAnnotations(string propValue = "anno")
|
||||
{
|
||||
// One row per lane — the builder emits one exact-RK step per lane.
|
||||
@@ -887,22 +864,5 @@ public class DeletionManifestBuilderTests
|
||||
return this;
|
||||
}
|
||||
|
||||
private ReaderSeed SeedDiscriminatorPkProp(string tableName, int n, string propValue, string discriminator)
|
||||
{
|
||||
// PK = {tenantId}_{discriminator}, server-side filter on PK prefix + SessionId == sessionId.
|
||||
var rows = new List<TableEntity>(n);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var e = new TableEntity($"{TenantId}_{discriminator}", $"{tableName}_{i:D5}")
|
||||
{
|
||||
["Marker"] = propValue,
|
||||
["SessionId"] = SessionId,
|
||||
};
|
||||
e.ETag = new ETag("0x" + tableName + i);
|
||||
rows.Add(e);
|
||||
}
|
||||
_query[tableName] = rows;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -726,17 +726,6 @@ public class DeviceJourneyAndFtrTests
|
||||
Assert.Equal(3, totals.ExcludedSessions);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, 30)] // default window
|
||||
[InlineData("garbage", 30)]
|
||||
[InlineData("7", 7)]
|
||||
[InlineData("0", 1)] // clamped low
|
||||
[InlineData("999", 180)] // clamped to aggregate retention
|
||||
public void ClampDays_DefaultsAndClamps(string? raw, int expected)
|
||||
{
|
||||
Assert.Equal(expected, DeviceJourneyMetricsResponseBuilder.ClampDays(raw));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InclusiveWindowStart_YieldsExactlyNCalendarDays()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
public class EndpointNormalizerTests
|
||||
{
|
||||
[Fact]
|
||||
public void Normalize_StripsApiPrefixReplacesGuidsAndKeyChars()
|
||||
{
|
||||
var normalized = EndpointNormalizer.Normalize("/api/Sessions/0f8fad5b-d9cb-469f-a165-70867728950e/events?x=1");
|
||||
Assert.Equal("sessions_{id}_events_x=1", normalized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolNameKey_RealToolName_PassesThroughUnchanged()
|
||||
{
|
||||
// Existing UserUsageLog rows are keyed by "<tool>:<endpoint>"; a real tool name must keep its key.
|
||||
Assert.Equal("get_session_events", EndpointNormalizer.ToolNameKey("get_session_events"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolNameKey_NullOrEmpty_ReturnsEmpty()
|
||||
{
|
||||
Assert.Equal(string.Empty, EndpointNormalizer.ToolNameKey(null));
|
||||
Assert.Equal(string.Empty, EndpointNormalizer.ToolNameKey(string.Empty));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolNameKey_WithCrlfAndControlChars_StripsThem()
|
||||
{
|
||||
// The log-forging vector: a header that tries to inject a fake log line through the row key.
|
||||
var forged = $"get_metrics\r\n[McpQuota] FAKE{(char)0}{(char)27}{(char)0x2028}x";
|
||||
var key = EndpointNormalizer.ToolNameKey(forged);
|
||||
Assert.Equal("get_metrics[McpQuota] FAKEx", key);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolNameKey_WithTableKeyIllegalChars_ReplacesThem()
|
||||
{
|
||||
// '/', '\', '#', '?' are rejected by Table Storage in keys — a header carrying them would make
|
||||
// every usage increment fail with 400, so they are replaced the same way the path is.
|
||||
Assert.Equal("a_b_c_d_e", EndpointNormalizer.ToolNameKey("a/b\\c#d?e"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolNameKey_LongerThanCap_IsTruncated()
|
||||
{
|
||||
var key = EndpointNormalizer.ToolNameKey(new string('t', EndpointNormalizer.MaxToolNameLength + 10));
|
||||
Assert.Equal(EndpointNormalizer.MaxToolNameLength, key.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolNameKey_OnlyControlChars_ReturnsEmpty()
|
||||
{
|
||||
Assert.Equal(string.Empty, EndpointNormalizer.ToolNameKey("\r\n "));
|
||||
}
|
||||
}
|
||||
-25
@@ -277,31 +277,6 @@ public class EndpointPolicyCatalogCompletenessTests
|
||||
Assert.Equal(TenantScoping.QueryParam, entry.TenantScoping);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inspector v1 endpoints (signals, decision-graph, reducer-verification) MUST stay locked to a
|
||||
/// platform-scope tier while the UI matures (Plan §M6 — primary use case is modelling 2-stage
|
||||
/// WhiteGlove deployments). They are now GlobalReadOrAdmin (GA + read-only GlobalReader): still
|
||||
/// invisible to tenant admins/members, but visible to the read-only platform tier. Defense-in-depth
|
||||
/// against an accidental downgrade to a tenant tier (MemberRead/TenantAdminOrGA) that would expose
|
||||
/// decision internals before the lift.
|
||||
///
|
||||
/// When the v2 adminMode lift happens, signals+decision-graph move to MemberRead with
|
||||
/// TenantScoping.QueryParam. reducer-verification stays platform-scope (never tenant-visible).
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("GET", "/api/sessions/abc-123/signals", "sessions/{sessionId}/signals")]
|
||||
[InlineData("GET", "/api/sessions/abc-123/decision-graph", "sessions/{sessionId}/decision-graph")]
|
||||
[InlineData("GET", "/api/sessions/abc-123/reducer-verification", "sessions/{sessionId}/reducer-verification")]
|
||||
public void InspectorRoutes_AreGlobalReadOrAdmin(string method, string path, string expectedTemplate)
|
||||
{
|
||||
var entry = EndpointAccessPolicyCatalog.FindPolicy(method, path);
|
||||
|
||||
Assert.NotNull(entry);
|
||||
Assert.Equal(expectedTemplate, entry!.RouteTemplate);
|
||||
Assert.Equal(EndpointPolicy.GlobalReadOrAdmin, entry.Policy);
|
||||
Assert.Equal(TenantScoping.None, entry.TenantScoping);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SignalR group join/leave MUST be AuthenticatedUserWithRole — NOT MemberRead and NOT plain
|
||||
/// AuthenticatedUser. The Progress Portal admits non-member end users, so MemberRead 403s them
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// ANALYZE-APP-018 — pins the firing behaviour of the reboot-return-code rule on the agent's
|
||||
/// <c>exitCodeClass</c> payload (IME-EXITCODE-CLASS: the admin-defined return-code class of the
|
||||
/// installer exit code, one of Success/SoftReboot/HardReboot/Retry/Failed):
|
||||
/// - SoftReboot or HardReboot on an app_install_completed event fires at base confidence,
|
||||
/// - HardReboot and an observed system_reboot_detected add confidence (ESP-005's twin),
|
||||
/// - Success, Retry and Failed never fire, and neither does a class on app_install_failed alone.
|
||||
/// The required condition uses the comma-separated <c>in</c> operator; the matched event's
|
||||
/// data fields feed the {{appName}} / {{exitCode}} / {{exitCodeClass}} interpolation.
|
||||
/// </summary>
|
||||
public class ExitCodeClassRuleTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "11111111-2222-3333-4444-555555555555";
|
||||
private const string RuleId = "ANALYZE-APP-018";
|
||||
|
||||
private static AnalyzeRule Rule() => BuiltInAnalyzeRules.GetAll().First(r => r.RuleId == RuleId);
|
||||
|
||||
[Fact]
|
||||
public void Rule_is_a_warning_that_never_fails_the_session()
|
||||
{
|
||||
var rule = Rule();
|
||||
Assert.True(rule.Enabled);
|
||||
Assert.Equal("warning", rule.Severity);
|
||||
Assert.Equal("apps", rule.Category);
|
||||
Assert.False(rule.MarkSessionAsFailedDefault);
|
||||
Assert.Contains("whiteglove_sealed", rule.EvaluateOn ?? new List<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SoftReboot_on_a_completed_app_fires_at_base_confidence_without_an_observed_reboot()
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
AppCompleted("Contoso VPN Client", exitCode: "3010", exitCodeClass: "SoftReboot"),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
Assert.Equal(RuleId, result.RuleId);
|
||||
Assert.Equal("warning", result.Severity);
|
||||
Assert.Equal(60, result.ConfidenceScore);
|
||||
|
||||
// The evidence is persisted and interpolated at render time (portal, MCP
|
||||
// interpolate-rule-template.ts): {{exitCodeClass}} resolves through the condition's
|
||||
// field/value pair, {{appName}} and {{exitCode}} through the whitelisted payload keys
|
||||
// (AddDataFieldsToEvidence) — every token the rule text uses must be reachable here.
|
||||
var matched = AsDict(result.MatchedConditions["reboot_return_code"]);
|
||||
Assert.Equal("exitCodeClass", AsString(matched["field"]));
|
||||
Assert.Equal("SoftReboot", AsString(matched["value"]));
|
||||
Assert.Equal("Contoso VPN Client", AsString(matched["appName"]));
|
||||
Assert.Equal("3010", AsString(matched["exitCode"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HardReboot_with_an_observed_reboot_reaches_full_confidence()
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
AppCompleted("Contoso Security Agent", exitCode: "1641", exitCodeClass: "HardReboot", state: "Postponed"),
|
||||
RebootDetected(),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
Assert.Equal(100, result.ConfidenceScore);
|
||||
Assert.True(result.MatchedConditions.ContainsKey("hard_reboot_return_code"));
|
||||
Assert.True(result.MatchedConditions.ContainsKey("reboot_observed"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Success")]
|
||||
[InlineData("Retry")]
|
||||
[InlineData("Failed")]
|
||||
public async Task Other_return_code_classes_do_not_fire(string exitCodeClass)
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
AppCompleted("Contoso Reader", exitCode: "0", exitCodeClass: exitCodeClass),
|
||||
RebootDetected(),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(events);
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_completed_app_without_the_class_does_not_fire_even_with_a_reboot_exit_code()
|
||||
{
|
||||
// Older agents emit exitCode only on failures and never the class; 3010 alone is not
|
||||
// evidence of the mapping the admin chose.
|
||||
var evt = AppCompleted("Legacy App", exitCode: "3010", exitCodeClass: null);
|
||||
var outcome = await RunAsync(new List<EnrollmentEvent> { evt, RebootDetected() });
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_reboot_class_on_a_failed_app_alone_does_not_fire()
|
||||
{
|
||||
// The rule reads the terminal completed/postponed event; a failure carrying the class is
|
||||
// covered by the app-failure rules and must not double-report here.
|
||||
var failed = AppCompleted("Contoso Agent", exitCode: "1641", exitCodeClass: "HardReboot");
|
||||
failed.EventType = "app_install_failed";
|
||||
failed.Data!["state"] = "Error";
|
||||
failed.Data["isError"] = "true";
|
||||
|
||||
var outcome = await RunAsync(new List<EnrollmentEvent> { failed, RebootDetected() });
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
// ===== Event builders — mirror ImeLogTrackerAdapter.BuildAppStatePayload =====
|
||||
|
||||
private static int s_sequence = 10;
|
||||
|
||||
private static EnrollmentEvent AppCompleted(string appName, string exitCode, string? exitCodeClass, string state = "Installed")
|
||||
{
|
||||
var data = new Dictionary<string, object>
|
||||
{
|
||||
["appId"] = Guid.NewGuid().ToString(),
|
||||
["appName"] = appName,
|
||||
["state"] = state,
|
||||
["intent"] = "Install",
|
||||
["targeted"] = "Device",
|
||||
["runAs"] = "System",
|
||||
["progressPercent"] = "100",
|
||||
["bytesDownloaded"] = "0",
|
||||
["bytesTotal"] = "0",
|
||||
["isError"] = "false",
|
||||
["isCompleted"] = "true",
|
||||
["exitCode"] = exitCode,
|
||||
};
|
||||
if (exitCodeClass != null) data["exitCodeClass"] = exitCodeClass;
|
||||
|
||||
return new EnrollmentEvent
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
EventType = "app_install_completed",
|
||||
Timestamp = DateTime.UtcNow,
|
||||
Sequence = s_sequence++,
|
||||
Data = data,
|
||||
};
|
||||
}
|
||||
|
||||
private static EnrollmentEvent RebootDetected() => new()
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
EventType = "system_reboot_detected",
|
||||
Timestamp = DateTime.UtcNow.AddMinutes(2),
|
||||
Sequence = s_sequence++,
|
||||
Data = new Dictionary<string, object>
|
||||
{
|
||||
["bootTime"] = DateTime.UtcNow.AddMinutes(1).ToString("o"),
|
||||
},
|
||||
};
|
||||
|
||||
private static Dictionary<string, object> AsDict(object o)
|
||||
{
|
||||
if (o is Dictionary<string, object> d) return d;
|
||||
throw new InvalidOperationException($"Expected Dictionary<string,object>, got {o?.GetType().Name ?? "null"}");
|
||||
}
|
||||
|
||||
private static string AsString(object o) => o?.ToString() ?? string.Empty;
|
||||
|
||||
private static async Task<AnalysisOutcome> RunAsync(List<EnrollmentEvent> events)
|
||||
{
|
||||
var rule = Rule();
|
||||
var ruleRepo = new Mock<IRuleRepository>();
|
||||
ruleRepo.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(new List<AnalyzeRule> { rule });
|
||||
ruleRepo.Setup(r => r.GetAnalyzeRulesAsync(TenantId)).ReturnsAsync(new List<AnalyzeRule>());
|
||||
ruleRepo.Setup(r => r.GetRuleStatesAsync(It.IsAny<string>())).ReturnsAsync(new Dictionary<string, RuleState>());
|
||||
ruleRepo.Setup(r => r.GetRuleResultsAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(new List<RuleResult>());
|
||||
|
||||
var sessionRepo = new Mock<ISessionRepository>();
|
||||
sessionRepo.Setup(s => s.GetSessionEventsStrictAsync(TenantId, SessionId, It.IsAny<int>())).ReturnsAsync(events);
|
||||
|
||||
var ruleService = new AnalyzeRuleService(ruleRepo.Object, NullLogger<AnalyzeRuleService>.Instance);
|
||||
var engine = new RuleEngine(ruleService, ruleRepo.Object, sessionRepo.Object, NullLogger<ExitCodeClassRuleTests>.Instance);
|
||||
|
||||
return await engine.AnalyzeSessionAsync(TenantId, SessionId);
|
||||
}
|
||||
}
|
||||
@@ -147,11 +147,11 @@ public class FleetHealthPayloadTests
|
||||
var payload = MetricsMath.BuildFleetHealthPayload(sessions, days: 30);
|
||||
|
||||
Assert.Equal(6, payload.ModelHealth.Count);
|
||||
Assert.Equal("Contoso Model7", payload.ModelHealth[0].Model);
|
||||
Assert.Equal("Contoso Model7", payload.ModelHealth[0].Label);
|
||||
Assert.Equal(7, payload.ModelHealth[0].Total);
|
||||
Assert.Equal(7, payload.ModelHealth[0].Succeeded);
|
||||
// The smallest (volume 1) is dropped by the top-6 cut.
|
||||
Assert.DoesNotContain(payload.ModelHealth, m => m.Model == "Contoso Model1");
|
||||
Assert.DoesNotContain(payload.ModelHealth, m => m.Label == "Contoso Model1");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -182,7 +182,47 @@ public class FleetHealthPayloadTests
|
||||
new List<SessionSummary> { S(SessionStatus.Succeeded, manufacturer: "", model: "") },
|
||||
days: 7);
|
||||
|
||||
Assert.Equal("Unknown", Assert.Single(payload.ModelHealth).Model);
|
||||
var m = Assert.Single(payload.ModelHealth);
|
||||
Assert.Equal("Unknown", m.Label);
|
||||
Assert.Equal("", m.Manufacturer);
|
||||
Assert.Equal("", m.Model);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ModelBuckets_CarryManufacturerAndModelSeparately_OnAllThreeLists()
|
||||
{
|
||||
// The dashboard deep link addresses the two session fields as two qualified search
|
||||
// terms; a client must never have to split the label again.
|
||||
var sessions = new List<SessionSummary>
|
||||
{
|
||||
S(SessionStatus.Succeeded, durationSeconds: 600, manufacturer: " Contoso ", model: "EliteBook 840"),
|
||||
S(SessionStatus.Failed, manufacturer: "Contoso", model: "EliteBook 840"),
|
||||
};
|
||||
|
||||
var payload = MetricsMath.BuildFleetHealthPayload(sessions, days: 7);
|
||||
|
||||
var health = Assert.Single(payload.ModelHealth);
|
||||
Assert.Equal(("Contoso", "EliteBook 840", "Contoso EliteBook 840"), (health.Manufacturer, health.Model, health.Label));
|
||||
Assert.Equal(2, health.Total);
|
||||
var slow = Assert.Single(payload.SlowestModels);
|
||||
Assert.Equal(("Contoso", "EliteBook 840", "Contoso EliteBook 840"), (slow.Manufacturer, slow.Model, slow.Label));
|
||||
var failing = Assert.Single(payload.TopFailingModels);
|
||||
Assert.Equal(("Contoso", "EliteBook 840", "Contoso EliteBook 840"), (failing.Manufacturer, failing.Model, failing.Label));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ModelBuckets_GroupOnThePair_NotOnTheLabel()
|
||||
{
|
||||
var sessions = new List<SessionSummary>
|
||||
{
|
||||
S(SessionStatus.Succeeded, manufacturer: "Contoso", model: "A B"),
|
||||
S(SessionStatus.Succeeded, manufacturer: "Contoso A", model: "B"),
|
||||
};
|
||||
|
||||
var payload = MetricsMath.BuildFleetHealthPayload(sessions, days: 7);
|
||||
|
||||
Assert.Equal(2, payload.ModelHealth.Count);
|
||||
Assert.All(payload.ModelHealth, m => Assert.Equal("Contoso A B", m.Label));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -199,10 +239,10 @@ public class FleetHealthPayloadTests
|
||||
var payload = MetricsMath.BuildFleetHealthPayload(sessions, days: 30);
|
||||
|
||||
Assert.Equal(2, payload.SlowestModels.Count);
|
||||
Assert.Equal("Contoso Slow", payload.SlowestModels[0].Model);
|
||||
Assert.Equal("Contoso Slow", payload.SlowestModels[0].Label);
|
||||
Assert.Equal(30, payload.SlowestModels[0].AvgMinutes);
|
||||
Assert.Equal(1, payload.SlowestModels[0].Count);
|
||||
Assert.Equal("Contoso Fast", payload.SlowestModels[1].Model);
|
||||
Assert.Equal("Contoso Fast", payload.SlowestModels[1].Label);
|
||||
Assert.Equal(10, payload.SlowestModels[1].AvgMinutes);
|
||||
}
|
||||
|
||||
@@ -227,13 +267,13 @@ public class FleetHealthPayloadTests
|
||||
var payload = MetricsMath.BuildFleetHealthPayload(sessions, days: 30);
|
||||
|
||||
Assert.Equal(2, payload.TopFailingModels.Count);
|
||||
Assert.Equal("Contoso B", payload.TopFailingModels[0].Model);
|
||||
Assert.Equal("Contoso B", payload.TopFailingModels[0].Label);
|
||||
Assert.Equal(2, payload.TopFailingModels[0].Failed);
|
||||
Assert.Equal(100, payload.TopFailingModels[0].FailureRate);
|
||||
Assert.Equal("Contoso A", payload.TopFailingModels[1].Model);
|
||||
Assert.Equal("Contoso A", payload.TopFailingModels[1].Label);
|
||||
Assert.Equal(4, payload.TopFailingModels[1].Total);
|
||||
Assert.Equal(50, payload.TopFailingModels[1].FailureRate);
|
||||
Assert.DoesNotContain(payload.TopFailingModels, m => m.Model == "Contoso C");
|
||||
Assert.DoesNotContain(payload.TopFailingModels, m => m.Label == "Contoso C");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -129,6 +129,29 @@ public class GatherRuleScopeFieldsTests
|
||||
Assert.Null(mapped.ActivePhases);
|
||||
Assert.Null(mapped.ActiveFromPhase);
|
||||
Assert.Null(mapped.EmitMode);
|
||||
Assert.False(mapped.EnrichErrorCodes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Roundtrip_EnrichErrorCodes_SurvivesStoreAndMap()
|
||||
{
|
||||
var (service, lastUpserted) = BuildStorageHarness();
|
||||
var rule = new GatherRule
|
||||
{
|
||||
RuleId = "GATHER-ENRICH-001",
|
||||
Title = "MSI log parser",
|
||||
CollectorType = "logparser",
|
||||
Target = "C:\\Windows\\Temp\\msi.log",
|
||||
Trigger = "interval",
|
||||
IntervalSeconds = 60,
|
||||
OutputEventType = "gather_msi",
|
||||
EnrichErrorCodes = true,
|
||||
};
|
||||
|
||||
Assert.True(await service.StoreGatherRuleAsync(rule, "global"));
|
||||
var mapped = service.MapToGatherRule(lastUpserted()!);
|
||||
|
||||
Assert.True(mapped.EnrichErrorCodes);
|
||||
}
|
||||
|
||||
// ── ContentEquivalent ──────────────────────────────────────────────────
|
||||
@@ -175,6 +198,10 @@ public class GatherRuleScopeFieldsTests
|
||||
var emit = BaseRule();
|
||||
emit.EmitMode = "on_change";
|
||||
Assert.False(GatherRuleService.ContentEquivalent(baseline, emit));
|
||||
|
||||
var enrich = BaseRule();
|
||||
enrich.EnrichErrorCodes = true;
|
||||
Assert.False(GatherRuleService.ContentEquivalent(baseline, enrich));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -37,6 +37,7 @@ public class GatherRuleUpdatePartialMergeTests
|
||||
CreatedAt = new DateTime(2026, 1, 15, 12, 0, 0, DateTimeKind.Utc),
|
||||
ActiveFromPhase = "AccountSetup",
|
||||
EmitMode = "on_change",
|
||||
EnrichErrorCodes = true,
|
||||
};
|
||||
|
||||
private static (GatherRuleService service, Mock<IRuleRepository> repo, List<GatherRule> stored) BuildService(
|
||||
@@ -77,6 +78,7 @@ public class GatherRuleUpdatePartialMergeTests
|
||||
Assert.Equal("Version", written.Parameters["valueName"]);
|
||||
Assert.Equal("AccountSetup", written.ActiveFromPhase);
|
||||
Assert.Equal("on_change", written.EmitMode);
|
||||
Assert.True(written.EnrichErrorCodes);
|
||||
Assert.Equal(existing.CreatedAt, written.CreatedAt);
|
||||
Assert.Equal("Alice Admin", written.Author);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
using AutopilotMonitor.Functions.Functions.Config;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for <see cref="GetAgentConfigFunction.ParseAgentMajor"/> — the pure decision logic that picks
|
||||
/// Tests for <see cref="AgentConfigResolver.ParseAgentMajor"/> — the pure decision logic that picks
|
||||
/// the per-line hash-oracle field set based on the X-Agent-Version header value.
|
||||
/// </summary>
|
||||
public class GetAgentConfigFunctionTests
|
||||
@@ -29,7 +29,7 @@ public class GetAgentConfigFunctionTests
|
||||
[InlineData("vNEXT", 1)]
|
||||
public void ParseAgentMajor_ExtractsMajor(string? agentVersion, int expectedMajor)
|
||||
{
|
||||
var actual = GetAgentConfigFunction.ParseAgentMajor(agentVersion);
|
||||
var actual = AgentConfigResolver.ParseAgentMajor(agentVersion);
|
||||
Assert.Equal(expectedMajor, actual);
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ public class GetAgentConfigFunctionTests
|
||||
P(@"C:\Windows\SetupDiag\*.log", "tenant"),
|
||||
};
|
||||
|
||||
var merged = GetAgentConfigFunction.MergeDiagnosticsLogPaths(global, tenant);
|
||||
var merged = AgentConfigResolver.MergeDiagnosticsLogPaths(global, tenant);
|
||||
|
||||
Assert.Equal(new[]
|
||||
{
|
||||
@@ -63,7 +63,7 @@ public class GetAgentConfigFunctionTests
|
||||
[Fact]
|
||||
public void MergeDiagnosticsLogPaths_DropsBlankEntries()
|
||||
{
|
||||
var merged = GetAgentConfigFunction.MergeDiagnosticsLogPaths(
|
||||
var merged = AgentConfigResolver.MergeDiagnosticsLogPaths(
|
||||
new[] { P(""), P(" "), P(@"C:\Install\Log\*.log") },
|
||||
new DiagnosticsLogPath[] { null!, P(@"C:\Install\Log\*.log") });
|
||||
|
||||
@@ -90,7 +90,7 @@ public class GetAgentConfigFunctionTests
|
||||
public void ResolveDiagnosticsUploadEnabled_GatesOnSasOrHosted(
|
||||
string? diagnosticsBlobSasUrl, string? destination, bool expected)
|
||||
{
|
||||
var actual = GetAgentConfigFunction.ResolveDiagnosticsUploadEnabled(diagnosticsBlobSasUrl, destination);
|
||||
var actual = AgentConfigResolver.ResolveDiagnosticsUploadEnabled(diagnosticsBlobSasUrl, destination);
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
using AutopilotMonitor.Functions.Functions.Sessions;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the pure helpers on <see cref="GetSessionSignalsFunction"/>. The HTTP-trigger
|
||||
/// end needs a live runtime harness; this file covers the deterministic query-string
|
||||
/// normalisation that decides how many rows we load.
|
||||
/// </summary>
|
||||
public class GetSessionSignalsFunctionTests
|
||||
{
|
||||
[Fact]
|
||||
public void ParseMaxResults_defaults_when_query_param_missing()
|
||||
{
|
||||
var result = GetSessionSignalsFunction.ParseMaxResults("");
|
||||
|
||||
Assert.Equal(GetSessionSignalsFunction.DefaultMaxResults, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseMaxResults_defaults_when_query_param_is_garbage()
|
||||
{
|
||||
var result = GetSessionSignalsFunction.ParseMaxResults("?maxResults=banana");
|
||||
|
||||
Assert.Equal(GetSessionSignalsFunction.DefaultMaxResults, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseMaxResults_honours_valid_value_inside_range()
|
||||
{
|
||||
var result = GetSessionSignalsFunction.ParseMaxResults("?maxResults=250");
|
||||
|
||||
Assert.Equal(250, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseMaxResults_caps_at_MaxResultsCap()
|
||||
{
|
||||
var result = GetSessionSignalsFunction.ParseMaxResults("?maxResults=999999");
|
||||
|
||||
Assert.Equal(GetSessionSignalsFunction.MaxResultsCap, result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("?maxResults=0")]
|
||||
[InlineData("?maxResults=-5")]
|
||||
public void ParseMaxResults_floors_at_one_for_non_positive_values(string query)
|
||||
{
|
||||
var result = GetSessionSignalsFunction.ParseMaxResults(query);
|
||||
|
||||
Assert.Equal(1, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ParseMaxResults_handles_null_query_string()
|
||||
{
|
||||
var result = GetSessionSignalsFunction.ParseMaxResults(null!);
|
||||
|
||||
Assert.Equal(GetSessionSignalsFunction.DefaultMaxResults, result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using System.Net;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the shared 401/403 contract of the Graph-backed device validators: attempt 1 drops the
|
||||
/// tenant's cached token (it may predate the consent grant on this instance) and reports
|
||||
/// transient so the loop re-mints; attempt 2 and every other status leave the token alone.
|
||||
/// </summary>
|
||||
public class GraphAuthFailureTests
|
||||
{
|
||||
private const string TenantId = "11111111-1111-1111-1111-111111111111";
|
||||
|
||||
private static Mock<GraphTokenService> TokenService()
|
||||
{
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["EntraId:ClientId"] = "aaaaaaaa-0000-0000-0000-000000000001",
|
||||
["EntraId:ClientSecret"] = "secret",
|
||||
}).Build();
|
||||
var registry = new EntraAppRegistry(configuration, NullLogger<EntraAppRegistry>.Instance);
|
||||
var tenantConfig = new Mock<TenantConfigurationService>(
|
||||
Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache)
|
||||
{ CallBase = false };
|
||||
return new Mock<GraphTokenService>(
|
||||
NullLogger<GraphTokenService>.Instance, Mock.Of<IHttpClientFactory>(), cache,
|
||||
configuration, registry, tenantConfig.Object)
|
||||
{ CallBase = false };
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.Unauthorized)]
|
||||
[InlineData(HttpStatusCode.Forbidden)]
|
||||
public void AuthFailure_OnFirstAttempt_InvalidatesOnce_AndAsksForRetry(HttpStatusCode status)
|
||||
{
|
||||
var tokens = TokenService();
|
||||
|
||||
var retry = GraphAuthFailure.TryRecoverStaleToken(tokens.Object, NullLogger.Instance, "Test", TenantId, status, attempt: 1);
|
||||
|
||||
Assert.True(retry);
|
||||
tokens.Verify(t => t.InvalidateTenant(TenantId), Times.Once);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.Unauthorized)]
|
||||
[InlineData(HttpStatusCode.Forbidden)]
|
||||
public void AuthFailure_OnSecondAttempt_LeavesTheFreshToken_AndDefersToTheValidator(HttpStatusCode status)
|
||||
{
|
||||
var tokens = TokenService();
|
||||
|
||||
var retry = GraphAuthFailure.TryRecoverStaleToken(tokens.Object, NullLogger.Instance, "Test", TenantId, status, attempt: 2);
|
||||
|
||||
Assert.False(retry);
|
||||
tokens.Verify(t => t.InvalidateTenant(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.NotFound)]
|
||||
[InlineData(HttpStatusCode.BadRequest)]
|
||||
[InlineData(HttpStatusCode.TooManyRequests)]
|
||||
[InlineData(HttpStatusCode.InternalServerError)]
|
||||
[InlineData(HttpStatusCode.GatewayTimeout)]
|
||||
public void OtherStatuses_NeverTouchTheToken(HttpStatusCode status)
|
||||
{
|
||||
var tokens = TokenService();
|
||||
|
||||
var retry = GraphAuthFailure.TryRecoverStaleToken(tokens.Object, NullLogger.Instance, "Test", TenantId, status, attempt: 1);
|
||||
|
||||
Assert.False(retry);
|
||||
Assert.False(GraphAuthFailure.IsAuthFailure(status));
|
||||
tokens.Verify(t => t.InvalidateTenant(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PermissionMissingRetryAfter_IsLongerThanTheDefault_ButInsideTheAgentsPatience()
|
||||
{
|
||||
// 30 s is the SecurityValidator default for a transient failure; a consent gap needs more
|
||||
// than that to close, and the agent's replay logic honours any Retry-After.
|
||||
Assert.True(GraphAuthFailure.PermissionMissingRetryAfterSeconds > 30);
|
||||
Assert.True(GraphAuthFailure.PermissionMissingRetryAfterSeconds <= 300);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, null, null)]
|
||||
[InlineData(null, 120, 120)]
|
||||
[InlineData(30, null, 30)]
|
||||
[InlineData(30, 120, 120)]
|
||||
[InlineData(120, 30, 120)]
|
||||
public void SecurityValidator_KeepsTheLargestRetryAfter(int? accumulated, int? next, int? expected)
|
||||
=> Assert.Equal(expected, SecurityValidator.MaxRetryAfter(accumulated, next));
|
||||
}
|
||||
@@ -77,17 +77,62 @@ public class HealthCheckServiceMcpServerTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_TimeoutOrConnectionFailure_ReportsWarningForColdStart()
|
||||
public async Task Check_Timeout_ReportsWarmingSoTheCallerCanRePoll()
|
||||
{
|
||||
var svc = BuildServiceWithFactory(
|
||||
new ThrowingHttpClientFactory(new TaskCanceledException("timeout")));
|
||||
|
||||
var check = await svc.CheckMcpServerAsync();
|
||||
|
||||
// Failure to wake the scaled-to-zero container within the budget is a warning,
|
||||
// not a hard outage (a re-check may still succeed once it finishes warming).
|
||||
// A scaled-to-zero container that did not answer inside the budget is "warming",
|
||||
// NOT a fault: the caller re-checks and the activation we triggered keeps running.
|
||||
Assert.Equal("warming", check.Status);
|
||||
// The default budget is pinned here because it is set nowhere else in the repo —
|
||||
// the code default IS the live production value.
|
||||
Assert.Contains("3s", check.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_Timeout_HonoursConfiguredBudget()
|
||||
{
|
||||
var svc = BuildServiceWithFactory(
|
||||
new ThrowingHttpClientFactory(new TaskCanceledException("timeout")),
|
||||
extraConfig: new Dictionary<string, string?> { ["McpServerHealthTimeoutSeconds"] = "7" });
|
||||
|
||||
var check = await svc.CheckMcpServerAsync();
|
||||
|
||||
Assert.Equal("warming", check.Status);
|
||||
Assert.Contains("7s", check.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_ConnectionFailure_ReportsWarningNotWarmingAndKeepsTheHostOut()
|
||||
{
|
||||
var svc = BuildServiceWithFactory(
|
||||
new ThrowingHttpClientFactory(new System.Net.Http.HttpRequestException("no such host mcp.example.test")));
|
||||
|
||||
var check = await svc.CheckMcpServerAsync();
|
||||
|
||||
// Reaching the network and failing to connect is a real warning — distinct from
|
||||
// the expected cold-start path, so it must not be softened to "warming".
|
||||
Assert.Equal("warning", check.Status);
|
||||
Assert.Contains("could not be reached", check.Message);
|
||||
Assert.DoesNotContain("http", check.Message, System.StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("mcp.example.test", check.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(12, false)]
|
||||
[InlineData(750, false)]
|
||||
[InlineData(751, true)]
|
||||
[InlineData(2400, true)]
|
||||
public void McpReachableMessage_marksOnlyAnswersAboveTheWarmThresholdAsColdStart(long elapsedMs, bool expectColdStart)
|
||||
{
|
||||
var message = HealthCheckService.McpReachableMessage(elapsedMs);
|
||||
|
||||
// Both arms keep the word "reachable" — the healthy-path assertions rely on it.
|
||||
Assert.Contains("reachable", message);
|
||||
Assert.Contains($"{elapsedMs}ms", message);
|
||||
Assert.Equal(expectColdStart, message.Contains("cold start"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -101,13 +146,21 @@ public class HealthCheckServiceMcpServerTests
|
||||
return BuildServiceWithFactory(new StubHttpClientFactory(handler));
|
||||
}
|
||||
|
||||
private static HealthCheckService BuildServiceWithFactory(System.Net.Http.IHttpClientFactory factory)
|
||||
private static HealthCheckService BuildServiceWithFactory(
|
||||
System.Net.Http.IHttpClientFactory factory,
|
||||
Dictionary<string, string?>? extraConfig = null)
|
||||
{
|
||||
var settings = new Dictionary<string, string?>
|
||||
{
|
||||
["McpServerUrl"] = "https://mcp.example.test",
|
||||
};
|
||||
if (extraConfig != null)
|
||||
{
|
||||
foreach (var kv in extraConfig) settings[kv.Key] = kv.Value;
|
||||
}
|
||||
|
||||
var config = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["McpServerUrl"] = "https://mcp.example.test",
|
||||
})
|
||||
.AddInMemoryCollection(settings)
|
||||
.Build();
|
||||
|
||||
return new HealthCheckService(
|
||||
|
||||
@@ -75,7 +75,7 @@ public class HealthCheckServicePoisonQueueTests
|
||||
var probe = new FakePoisonQueueProbe();
|
||||
probe.Counts[Constants.QueueNames.AnalyzeOnEnrollmentEnd + "-poison"] = 3;
|
||||
probe.Counts[Constants.QueueNames.VulnerabilityCorrelate + "-poison"] = 0;
|
||||
probe.Counts[Constants.QueueNames.TelemetryIndexReconcile + "-poison"] = 0;
|
||||
probe.Counts[Constants.QueueNames.TenantAutoApprove + "-poison"] = 0;
|
||||
|
||||
var svc = BuildService(probe);
|
||||
var check = await svc.CheckPoisonQueuesAsync();
|
||||
@@ -94,7 +94,7 @@ public class HealthCheckServicePoisonQueueTests
|
||||
var probe = new FakePoisonQueueProbe();
|
||||
probe.Counts[Constants.QueueNames.AnalyzeOnEnrollmentEnd + "-poison"] = 15;
|
||||
probe.Counts[Constants.QueueNames.VulnerabilityCorrelate + "-poison"] = 0;
|
||||
probe.Counts[Constants.QueueNames.TelemetryIndexReconcile + "-poison"] = 2;
|
||||
probe.Counts[Constants.QueueNames.TenantAutoApprove + "-poison"] = 2;
|
||||
|
||||
var svc = BuildService(probe);
|
||||
var check = await svc.CheckPoisonQueuesAsync();
|
||||
@@ -117,7 +117,7 @@ public class HealthCheckServicePoisonQueueTests
|
||||
}
|
||||
};
|
||||
probe.Counts[Constants.QueueNames.AnalyzeOnEnrollmentEnd + "-poison"] = 0;
|
||||
probe.Counts[Constants.QueueNames.TelemetryIndexReconcile + "-poison"] = 0;
|
||||
probe.Counts[Constants.QueueNames.TenantAutoApprove + "-poison"] = 0;
|
||||
|
||||
var svc = BuildService(probe);
|
||||
var check = await svc.CheckPoisonQueuesAsync();
|
||||
@@ -134,7 +134,7 @@ public class HealthCheckServicePoisonQueueTests
|
||||
var probe = new FakePoisonQueueProbe();
|
||||
probe.Counts[Constants.QueueNames.AnalyzeOnEnrollmentEnd + "-poison"] = 4;
|
||||
probe.Counts[Constants.QueueNames.VulnerabilityCorrelate + "-poison"] = 0;
|
||||
probe.Counts[Constants.QueueNames.TelemetryIndexReconcile + "-poison"] = 0;
|
||||
probe.Counts[Constants.QueueNames.TenantAutoApprove + "-poison"] = 0;
|
||||
|
||||
// warn=5 → 4 messages now classifies as healthy (would be warning under defaults)
|
||||
var svc = BuildService(probe, new Dictionary<string, string?>
|
||||
@@ -153,7 +153,7 @@ public class HealthCheckServicePoisonQueueTests
|
||||
var probe = new FakePoisonQueueProbe();
|
||||
probe.Counts[Constants.QueueNames.AnalyzeOnEnrollmentEnd + "-poison"] = 1;
|
||||
probe.Counts[Constants.QueueNames.VulnerabilityCorrelate + "-poison"] = 0;
|
||||
probe.Counts[Constants.QueueNames.TelemetryIndexReconcile + "-poison"] = 0;
|
||||
probe.Counts[Constants.QueueNames.TenantAutoApprove + "-poison"] = 0;
|
||||
|
||||
var svc = BuildService(probe);
|
||||
var check = await svc.CheckPoisonQueuesAsync();
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Functions.Queue;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Functions.Services.Ime;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Azure.Storage.Queues.Models;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Newtonsoft.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Contract of the ime-msi-archive queue function (successor of the self-polling worker):
|
||||
/// merge the archiver's outcome onto the ImeVersionHistory row on EVERY attempt (also
|
||||
/// failures, so operators see a stuck download), return for terminal outcomes so the host
|
||||
/// deletes the message, throw for retryable ones so the host's retry → poison ladder applies,
|
||||
/// re-enqueue with a delay — not drop — while ImeMsiArchivingEnabled is off, and drop
|
||||
/// version-less envelopes before the archiver runs.
|
||||
/// </summary>
|
||||
public class ImeMsiArchiveQueueFunctionTests
|
||||
{
|
||||
private const string Version = "1.104.102.0";
|
||||
|
||||
[Fact]
|
||||
public async Task Success_merges_row_and_completes()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.Archiver.Result = new ImeMsiArchiveResult(
|
||||
true, ImeMsiArchiver.Statuses.Archived, Retryable: false,
|
||||
$"{Version}/IntuneWindowsAgent.msi", "abc123", 42L, ImeMsiArchiver.FallbackMsiUrls[1]);
|
||||
|
||||
await h.Sut.ProcessAsync(Message(Envelope()), CancellationToken.None);
|
||||
|
||||
h.Repo.Verify(r => r.UpdateImeVersionArchiveInfoAsync(
|
||||
Version, ImeMsiArchiver.Statuses.Archived,
|
||||
$"{Version}/IntuneWindowsAgent.msi", "abc123", 42L, ImeMsiArchiver.FallbackMsiUrls[1]),
|
||||
Times.Once);
|
||||
h.Producer.Verify(p => p.EnqueueAsync(
|
||||
It.IsAny<ImeMsiArchiveEnvelope>(), It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Retryable_failure_merges_row_and_throws_for_host_retry()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.Archiver.Result = new ImeMsiArchiveResult(
|
||||
false, ImeMsiArchiver.Statuses.FailedDownload, Retryable: true,
|
||||
null, null, null, ImeMsiArchiver.FallbackMsiUrls[1]);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(
|
||||
() => h.Sut.ProcessAsync(Message(Envelope()), CancellationToken.None));
|
||||
|
||||
// Row always tells the truth — the failure status IS merged before the throw.
|
||||
h.Repo.Verify(r => r.UpdateImeVersionArchiveInfoAsync(
|
||||
Version, ImeMsiArchiver.Statuses.FailedDownload,
|
||||
null, null, null, ImeMsiArchiver.FallbackMsiUrls[1]),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Permanent_failure_merges_row_and_completes()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.Archiver.Result = new ImeMsiArchiveResult(
|
||||
false, ImeMsiArchiver.Statuses.FailedTooLarge, Retryable: false,
|
||||
null, null, 999L, ImeMsiArchiver.FallbackMsiUrls[1]);
|
||||
|
||||
await h.Sut.ProcessAsync(Message(Envelope()), CancellationToken.None);
|
||||
|
||||
h.Repo.Verify(r => r.UpdateImeVersionArchiveInfoAsync(
|
||||
Version, ImeMsiArchiver.Statuses.FailedTooLarge,
|
||||
null, null, 999L, ImeMsiArchiver.FallbackMsiUrls[1]),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Paused_requeues_with_delay_and_skips_archiver()
|
||||
{
|
||||
var h = new Harness(archivingEnabled: false);
|
||||
|
||||
await h.Sut.ProcessAsync(Message(Envelope()), CancellationToken.None);
|
||||
|
||||
Assert.Equal(0, h.Archiver.Calls);
|
||||
h.Producer.Verify(p => p.EnqueueAsync(
|
||||
It.Is<ImeMsiArchiveEnvelope>(e => e.Version == Version),
|
||||
ImeMsiArchiveQueueFunction.PauseRequeueDelay,
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
h.Repo.Verify(r => r.UpdateImeVersionArchiveInfoAsync(
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string?>(),
|
||||
It.IsAny<string?>(), It.IsAny<long?>(), It.IsAny<string?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Envelope_without_version_is_dropped_before_archiver()
|
||||
{
|
||||
var h = new Harness();
|
||||
|
||||
await h.Sut.ProcessAsync(Message(new ImeMsiArchiveEnvelope
|
||||
{
|
||||
Version = string.Empty,
|
||||
EnqueuedAt = DateTime.UtcNow,
|
||||
}), CancellationToken.None);
|
||||
|
||||
Assert.Equal(0, h.Archiver.Calls);
|
||||
h.Repo.Verify(r => r.UpdateImeVersionArchiveInfoAsync(
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string?>(),
|
||||
It.IsAny<string?>(), It.IsAny<long?>(), It.IsAny<string?>()),
|
||||
Times.Never);
|
||||
h.Producer.Verify(p => p.EnqueueAsync(
|
||||
It.IsAny<ImeMsiArchiveEnvelope>(), It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
// ============================================================ Helpers ====
|
||||
|
||||
private static ImeMsiArchiveEnvelope Envelope() => new()
|
||||
{
|
||||
Version = Version,
|
||||
MsiDownloadUrl = ImeMsiArchiver.FallbackMsiUrls[1],
|
||||
MsiMatchedBy = "productVersion",
|
||||
TenantId = "11111111-1111-1111-1111-111111111111",
|
||||
SessionId = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
|
||||
EnqueuedAt = DateTime.UtcNow,
|
||||
};
|
||||
|
||||
private static QueueMessage Message(ImeMsiArchiveEnvelope envelope) => QueuesModelFactory.QueueMessage(
|
||||
messageId: "msg-" + Guid.NewGuid().ToString("N"),
|
||||
popReceipt: "pop-" + Guid.NewGuid().ToString("N"),
|
||||
body: new BinaryData(JsonConvert.SerializeObject(envelope)),
|
||||
dequeueCount: 1);
|
||||
|
||||
/// <summary>Scripted archiver — the function only consumes the classified result.</summary>
|
||||
private sealed class StubArchiver : ImeMsiArchiver
|
||||
{
|
||||
private int _calls;
|
||||
|
||||
public ImeMsiArchiveResult Result { get; set; } = new(
|
||||
true, Statuses.Archived, Retryable: false, null, null, null, null);
|
||||
|
||||
public int Calls => Volatile.Read(ref _calls);
|
||||
|
||||
public override Task<ImeMsiArchiveResult> ArchiveAsync(
|
||||
ImeMsiArchiveEnvelope envelope, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Interlocked.Increment(ref _calls);
|
||||
return Task.FromResult(Result);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
public StubArchiver Archiver { get; } = new();
|
||||
public Mock<ISessionRepository> Repo { get; } = new();
|
||||
public Mock<IImeMsiArchiveProducer> Producer { get; } = new();
|
||||
public ImeMsiArchiveQueueFunction Sut { get; }
|
||||
|
||||
public Harness(bool archivingEnabled = true)
|
||||
{
|
||||
var adminConfig = new Mock<AdminConfigurationService>(
|
||||
Mock.Of<IConfigRepository>(),
|
||||
NullLogger<AdminConfigurationService>.Instance,
|
||||
new MemoryCache(new MemoryCacheOptions()));
|
||||
adminConfig.Setup(a => a.GetConfigurationAsync())
|
||||
.ReturnsAsync(new AdminConfiguration { ImeMsiArchivingEnabled = archivingEnabled });
|
||||
|
||||
Sut = new ImeMsiArchiveQueueFunction(
|
||||
Archiver, Repo.Object, adminConfig.Object, Producer.Object,
|
||||
NullLogger<ImeMsiArchiveQueueFunction>.Instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Azure;
|
||||
using Azure.Storage.Queues;
|
||||
using Azure.Storage.Queues.Models;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Functions.Services.Ime;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Newtonsoft.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Worker-level tests for the ime-msi-archive queue consumer (daily review 2026-08-18:
|
||||
/// previously untested). The worker's contract: merge the archiver's outcome onto the
|
||||
/// ImeVersionHistory row on EVERY attempt (also failures, so operators see a stuck
|
||||
/// download), delete the message for terminal outcomes, rethrow for retryable ones
|
||||
/// (visibility-timeout ladder), pause — not drop — while ImeMsiArchivingEnabled is off,
|
||||
/// and drop version-less envelopes without invoking the archiver.
|
||||
/// </summary>
|
||||
public class ImeMsiArchiveQueueWorkerTests
|
||||
{
|
||||
private const string Version = "1.104.102.0";
|
||||
|
||||
[Fact]
|
||||
public async Task Worker_success_merges_row_and_deletes_message()
|
||||
{
|
||||
var harness = new Harness();
|
||||
harness.Archiver.Result = new ImeMsiArchiveResult(
|
||||
true, ImeMsiArchiver.Statuses.Archived, Retryable: false,
|
||||
$"{Version}/IntuneWindowsAgent.msi", "abc123", 42L, ImeMsiArchiver.FallbackMsiUrls[1]);
|
||||
harness.EnqueueMessage(JsonConvert.SerializeObject(Envelope()));
|
||||
|
||||
await harness.RunUntilAsync(() => harness.MainQueueDeleted());
|
||||
|
||||
harness.Repo.Verify(r => r.UpdateImeVersionArchiveInfoAsync(
|
||||
Version, ImeMsiArchiver.Statuses.Archived,
|
||||
$"{Version}/IntuneWindowsAgent.msi", "abc123", 42L, ImeMsiArchiver.FallbackMsiUrls[1]),
|
||||
Times.Once);
|
||||
harness.MainQueue.Verify(q => q.DeleteMessageAsync(
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Worker_retryable_failure_merges_row_but_leaves_message()
|
||||
{
|
||||
var harness = new Harness();
|
||||
harness.Archiver.Result = new ImeMsiArchiveResult(
|
||||
false, ImeMsiArchiver.Statuses.FailedDownload, Retryable: true,
|
||||
null, null, null, ImeMsiArchiver.FallbackMsiUrls[1]);
|
||||
harness.EnqueueMessage(JsonConvert.SerializeObject(Envelope()));
|
||||
|
||||
await harness.RunUntilAsync(() => harness.Archiver.Calls > 0);
|
||||
|
||||
// Row always tells the truth — the failure status IS merged...
|
||||
harness.Repo.Verify(r => r.UpdateImeVersionArchiveInfoAsync(
|
||||
Version, ImeMsiArchiver.Statuses.FailedDownload,
|
||||
null, null, null, ImeMsiArchiver.FallbackMsiUrls[1]),
|
||||
Times.AtLeastOnce);
|
||||
// ...but the message stays for the visibility-timeout retry → poison ladder.
|
||||
harness.MainQueue.Verify(q => q.DeleteMessageAsync(
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Worker_permanent_failure_merges_row_and_completes_message()
|
||||
{
|
||||
var harness = new Harness();
|
||||
harness.Archiver.Result = new ImeMsiArchiveResult(
|
||||
false, ImeMsiArchiver.Statuses.FailedTooLarge, Retryable: false,
|
||||
null, null, 999L, ImeMsiArchiver.FallbackMsiUrls[1]);
|
||||
harness.EnqueueMessage(JsonConvert.SerializeObject(Envelope()));
|
||||
|
||||
await harness.RunUntilAsync(() => harness.MainQueueDeleted());
|
||||
|
||||
harness.Repo.Verify(r => r.UpdateImeVersionArchiveInfoAsync(
|
||||
Version, ImeMsiArchiver.Statuses.FailedTooLarge,
|
||||
null, null, 999L, ImeMsiArchiver.FallbackMsiUrls[1]),
|
||||
Times.Once);
|
||||
harness.MainQueue.Verify(q => q.DeleteMessageAsync(
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Worker_pauses_while_archiving_disabled()
|
||||
{
|
||||
var harness = new Harness(archivingEnabled: false);
|
||||
harness.EnqueueMessage(JsonConvert.SerializeObject(Envelope()));
|
||||
|
||||
await harness.RunForAsync(TimeSpan.FromMilliseconds(500));
|
||||
|
||||
// Pause, not drop: no receive, no archive attempt — the message parks in the queue.
|
||||
harness.MainQueue.Verify(q => q.ReceiveMessagesAsync(
|
||||
It.IsAny<int>(), It.IsAny<TimeSpan>(), It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
Assert.Equal(0, harness.Archiver.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Worker_drops_envelope_without_version_before_archiver()
|
||||
{
|
||||
var harness = new Harness();
|
||||
harness.EnqueueMessage(JsonConvert.SerializeObject(new ImeMsiArchiveEnvelope
|
||||
{
|
||||
Version = string.Empty,
|
||||
EnqueuedAt = DateTime.UtcNow,
|
||||
}));
|
||||
|
||||
await harness.RunUntilAsync(() => harness.MainQueueDeleted());
|
||||
|
||||
Assert.Equal(0, harness.Archiver.Calls);
|
||||
harness.Repo.Verify(r => r.UpdateImeVersionArchiveInfoAsync(
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string?>(),
|
||||
It.IsAny<string?>(), It.IsAny<long?>(), It.IsAny<string?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
// ============================================================ Helpers ====
|
||||
|
||||
private static ImeMsiArchiveEnvelope Envelope() => new()
|
||||
{
|
||||
Version = Version,
|
||||
MsiDownloadUrl = ImeMsiArchiver.FallbackMsiUrls[1],
|
||||
MsiMatchedBy = "productVersion",
|
||||
TenantId = "11111111-1111-1111-1111-111111111111",
|
||||
SessionId = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
|
||||
EnqueuedAt = DateTime.UtcNow,
|
||||
};
|
||||
|
||||
/// <summary>Scripted archiver — the worker only consumes the classified result.</summary>
|
||||
private sealed class StubArchiver : ImeMsiArchiver
|
||||
{
|
||||
private int _calls;
|
||||
|
||||
public ImeMsiArchiveResult Result { get; set; } = new(
|
||||
true, Statuses.Archived, Retryable: false, null, null, null, null);
|
||||
|
||||
public int Calls => Volatile.Read(ref _calls);
|
||||
|
||||
public override Task<ImeMsiArchiveResult> ArchiveAsync(
|
||||
ImeMsiArchiveEnvelope envelope, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Interlocked.Increment(ref _calls);
|
||||
return Task.FromResult(Result);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Mock-queue poll-loop harness, same shape as SessionDeletionWorkerTests.</summary>
|
||||
private sealed class Harness
|
||||
{
|
||||
public Mock<QueueClient> MainQueue { get; }
|
||||
public Mock<QueueClient> PoisonQueue { get; }
|
||||
public StubArchiver Archiver { get; } = new();
|
||||
public Mock<ISessionRepository> Repo { get; } = new();
|
||||
public ImeMsiArchiveQueueWorker Sut { get; }
|
||||
|
||||
private readonly Queue<QueueMessage> _pendingMessages = new();
|
||||
|
||||
public Harness(bool archivingEnabled = true)
|
||||
{
|
||||
MainQueue = new Mock<QueueClient>();
|
||||
PoisonQueue = new Mock<QueueClient>();
|
||||
|
||||
MainQueue.Setup(q => q.CreateIfNotExistsAsync(
|
||||
It.IsAny<IDictionary<string, string>>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync((Response?)null);
|
||||
PoisonQueue.Setup(q => q.CreateIfNotExistsAsync(
|
||||
It.IsAny<IDictionary<string, string>>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync((Response?)null);
|
||||
|
||||
MainQueue.Setup(q => q.ReceiveMessagesAsync(
|
||||
It.IsAny<int>(), It.IsAny<TimeSpan>(), It.IsAny<CancellationToken>()))
|
||||
.Returns<int, TimeSpan?, CancellationToken>((maxMessages, _, _) =>
|
||||
{
|
||||
var batch = new List<QueueMessage>();
|
||||
lock (_pendingMessages)
|
||||
{
|
||||
while (batch.Count < maxMessages && _pendingMessages.Count > 0)
|
||||
batch.Add(_pendingMessages.Dequeue());
|
||||
}
|
||||
return Task.FromResult(Response.FromValue(batch.ToArray(), new Mock<Response>().Object));
|
||||
});
|
||||
|
||||
MainQueue.Setup(q => q.DeleteMessageAsync(
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new Mock<Response>().Object);
|
||||
|
||||
MainQueue.Setup(q => q.UpdateMessageAsync(
|
||||
It.IsAny<string>(), It.IsAny<string>(),
|
||||
It.IsAny<string>(), It.IsAny<TimeSpan>(), It.IsAny<CancellationToken>()))
|
||||
.Returns<string, string, string, TimeSpan, CancellationToken>((_, _, _, vis, _) =>
|
||||
{
|
||||
var updated = QueuesModelFactory.UpdateReceipt(
|
||||
"pop-extended-" + Guid.NewGuid().ToString("N"),
|
||||
DateTimeOffset.UtcNow.Add(vis));
|
||||
return Task.FromResult(Response.FromValue(updated, new Mock<Response>().Object));
|
||||
});
|
||||
|
||||
var adminConfig = new Mock<AdminConfigurationService>(
|
||||
Mock.Of<IConfigRepository>(),
|
||||
NullLogger<AdminConfigurationService>.Instance,
|
||||
new MemoryCache(new MemoryCacheOptions()));
|
||||
adminConfig.Setup(a => a.GetConfigurationAsync())
|
||||
.ReturnsAsync(new AdminConfiguration { ImeMsiArchivingEnabled = archivingEnabled });
|
||||
|
||||
Sut = new ImeMsiArchiveQueueWorker(
|
||||
MainQueue.Object, PoisonQueue.Object,
|
||||
Archiver, Repo.Object, adminConfig.Object,
|
||||
NullLogger<ImeMsiArchiveQueueWorker>.Instance,
|
||||
pollInterval: TimeSpan.FromMilliseconds(50));
|
||||
}
|
||||
|
||||
public void EnqueueMessage(string body)
|
||||
{
|
||||
var msg = QueuesModelFactory.QueueMessage(
|
||||
messageId: "msg-" + Guid.NewGuid().ToString("N"),
|
||||
popReceipt: "pop-" + Guid.NewGuid().ToString("N"),
|
||||
body: new BinaryData(body),
|
||||
dequeueCount: 1);
|
||||
lock (_pendingMessages) _pendingMessages.Enqueue(msg);
|
||||
}
|
||||
|
||||
public async Task RunForAsync(TimeSpan duration)
|
||||
{
|
||||
using var cts = new CancellationTokenSource(duration);
|
||||
try { await Sut.StartAsync(cts.Token); }
|
||||
catch (OperationCanceledException) { }
|
||||
try { await Task.Delay(duration, cts.Token); }
|
||||
catch (OperationCanceledException) { }
|
||||
try { await Sut.StopAsync(CancellationToken.None); }
|
||||
catch (OperationCanceledException) { }
|
||||
}
|
||||
|
||||
public async Task RunUntilAsync(Func<bool> condition, TimeSpan? timeout = null)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromSeconds(10));
|
||||
using var cts = new CancellationTokenSource();
|
||||
try { await Sut.StartAsync(cts.Token); }
|
||||
catch (OperationCanceledException) { }
|
||||
while (!condition() && DateTime.UtcNow < deadline)
|
||||
await Task.Delay(25);
|
||||
cts.Cancel();
|
||||
try { await Sut.StopAsync(CancellationToken.None); }
|
||||
catch (OperationCanceledException) { }
|
||||
}
|
||||
|
||||
public bool MainQueueDeleted() =>
|
||||
MainQueue.Invocations.Any(i => i.Method.Name == nameof(QueueClient.DeleteMessageAsync));
|
||||
}
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
using AutopilotMonitor.Functions.DataAccess.TableStorage;
|
||||
using AutopilotMonitor.Functions.Services.Indexing;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// <b>M5 release-gate</b> (Plan §M5-Pflicht line 1395): per-index-table PK/RK consistency
|
||||
/// between primary rows and their derived index rows. For each index table, walk a
|
||||
/// canonical primary row through the Factory + Handler pipeline and verify that the
|
||||
/// captured index record carries enough back-ref information to reconstruct the
|
||||
/// primary's <c>(PartitionKey, RowKey)</c> via <see cref="TableSignalRepository"/> /
|
||||
/// <see cref="TableDecisionTransitionRepository"/> key builders.
|
||||
/// <para>
|
||||
/// Also asserts pipeline idempotency: running the same primary row through twice
|
||||
/// produces identical upsert keys — the consumer's <c>UpsertReplace</c> batches stay
|
||||
/// deduplicating even under timer-triggered resubmits.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public class IndexDualWriteConsistencyTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "b2c3d4e5-f6a7-8901-bcde-f12345678901";
|
||||
|
||||
private static readonly DateTime Occurred =
|
||||
new(2026, 4, 21, 14, 7, 33, DateTimeKind.Utc);
|
||||
|
||||
private static (IndexReconcileHandler handler, FakeIndexTableRepository repo) Sut()
|
||||
{
|
||||
var repo = new FakeIndexTableRepository();
|
||||
var handler = new IndexReconcileHandler(repo, NullLogger<IndexReconcileHandler>.Instance);
|
||||
return (handler, repo);
|
||||
}
|
||||
|
||||
// ============================================================ SignalsByKind ↔ Signals
|
||||
|
||||
[Fact]
|
||||
public async Task SignalsByKind_row_carries_back_ref_to_primary_Signals_row()
|
||||
{
|
||||
var primary = new SignalRecord
|
||||
{
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
SessionSignalOrdinal = 42,
|
||||
Kind = "EspTerminalFailure",
|
||||
OccurredAtUtc = Occurred,
|
||||
SourceOrigin = "EspAndHelloTrackerAdapter",
|
||||
};
|
||||
|
||||
var (handler, repo) = Sut();
|
||||
await handler.HandleAsync(IndexReconcileEnvelopeFactory.FromSignal(primary));
|
||||
|
||||
var index = Assert.Single(repo.SignalsByKind);
|
||||
|
||||
// Back-ref fields on the index row must reconstruct the primary PK/RK.
|
||||
var reconstructedPk = TableSignalRepository.BuildPartitionKey(index.TenantId, index.SessionId);
|
||||
var reconstructedRk = TableSignalRepository.BuildRowKey(index.SessionSignalOrdinal);
|
||||
|
||||
Assert.Equal(
|
||||
TableSignalRepository.BuildPartitionKey(primary.TenantId, primary.SessionId),
|
||||
reconstructedPk);
|
||||
Assert.Equal(
|
||||
TableSignalRepository.BuildRowKey(primary.SessionSignalOrdinal),
|
||||
reconstructedRk);
|
||||
}
|
||||
|
||||
// ============================================================ SessionsByTerminal ↔ DecisionTransitions
|
||||
|
||||
[Fact]
|
||||
public async Task SessionsByTerminal_row_carries_back_ref_to_primary_DecisionTransitions_row()
|
||||
{
|
||||
var primary = TerminalTransition();
|
||||
|
||||
var (handler, repo) = Sut();
|
||||
await handler.HandleAsync(IndexReconcileEnvelopeFactory.FromDecisionTransition(primary));
|
||||
|
||||
var index = Assert.Single(repo.SessionsByTerminal);
|
||||
|
||||
var reconstructedPk = TableDecisionTransitionRepository.BuildPartitionKey(index.TenantId, index.SessionId);
|
||||
var reconstructedRk = TableDecisionTransitionRepository.BuildRowKey(index.StepIndex);
|
||||
|
||||
Assert.Equal(
|
||||
TableDecisionTransitionRepository.BuildPartitionKey(primary.TenantId, primary.SessionId),
|
||||
reconstructedPk);
|
||||
Assert.Equal(
|
||||
TableDecisionTransitionRepository.BuildRowKey(primary.StepIndex),
|
||||
reconstructedRk);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SessionsByStage_row_carries_back_ref_to_primary_DecisionTransitions_row()
|
||||
{
|
||||
var primary = new DecisionTransitionRecord
|
||||
{
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
StepIndex = 3,
|
||||
FromStage = "AwaitingEsp",
|
||||
ToStage = "EspInProgress",
|
||||
Taken = true,
|
||||
IsTerminal = false,
|
||||
OccurredAtUtc = Occurred,
|
||||
};
|
||||
|
||||
var (handler, repo) = Sut();
|
||||
await handler.HandleAsync(IndexReconcileEnvelopeFactory.FromDecisionTransition(primary));
|
||||
|
||||
var index = Assert.Single(repo.SessionsByStage);
|
||||
|
||||
var reconstructedPk = TableDecisionTransitionRepository.BuildPartitionKey(index.TenantId, index.SessionId);
|
||||
var reconstructedRk = TableDecisionTransitionRepository.BuildRowKey(index.StepIndex);
|
||||
|
||||
Assert.Equal(
|
||||
TableDecisionTransitionRepository.BuildPartitionKey(primary.TenantId, primary.SessionId),
|
||||
reconstructedPk);
|
||||
Assert.Equal(
|
||||
TableDecisionTransitionRepository.BuildRowKey(primary.StepIndex),
|
||||
reconstructedRk);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeadEndsByReason_row_carries_back_ref_to_primary_DecisionTransitions_row()
|
||||
{
|
||||
var primary = new DecisionTransitionRecord
|
||||
{
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
StepIndex = 5,
|
||||
FromStage = "EspInProgress",
|
||||
ToStage = "EspInProgress",
|
||||
Taken = false,
|
||||
IsTerminal = false,
|
||||
DeadEndReason = "hybrid_reboot_gate_blocking",
|
||||
OccurredAtUtc = Occurred,
|
||||
};
|
||||
|
||||
var (handler, repo) = Sut();
|
||||
await handler.HandleAsync(IndexReconcileEnvelopeFactory.FromDecisionTransition(primary));
|
||||
|
||||
var index = Assert.Single(repo.DeadEndsByReason);
|
||||
|
||||
Assert.Equal(
|
||||
TableDecisionTransitionRepository.BuildPartitionKey(primary.TenantId, primary.SessionId),
|
||||
TableDecisionTransitionRepository.BuildPartitionKey(index.TenantId, index.SessionId));
|
||||
Assert.Equal(
|
||||
TableDecisionTransitionRepository.BuildRowKey(primary.StepIndex),
|
||||
TableDecisionTransitionRepository.BuildRowKey(index.StepIndex));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClassifierVerdictsByIdLevel_row_carries_back_ref_to_primary_DecisionTransitions_row()
|
||||
{
|
||||
var primary = new DecisionTransitionRecord
|
||||
{
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
StepIndex = 7,
|
||||
FromStage = "EspInProgress",
|
||||
ToStage = "WhiteGloveSealed",
|
||||
Taken = true,
|
||||
IsTerminal = true,
|
||||
ClassifierVerdictId = "whiteglove-sealing",
|
||||
ClassifierHypothesisLevel = "Strong",
|
||||
OccurredAtUtc = Occurred,
|
||||
};
|
||||
|
||||
var (handler, repo) = Sut();
|
||||
await handler.HandleAsync(IndexReconcileEnvelopeFactory.FromDecisionTransition(primary));
|
||||
|
||||
var index = Assert.Single(repo.ClassifierVerdictsByIdLevel);
|
||||
|
||||
Assert.Equal(
|
||||
TableDecisionTransitionRepository.BuildPartitionKey(primary.TenantId, primary.SessionId),
|
||||
TableDecisionTransitionRepository.BuildPartitionKey(index.TenantId, index.SessionId));
|
||||
Assert.Equal(
|
||||
TableDecisionTransitionRepository.BuildRowKey(primary.StepIndex),
|
||||
TableDecisionTransitionRepository.BuildRowKey(index.StepIndex));
|
||||
}
|
||||
|
||||
// ============================================================ pipeline idempotency
|
||||
|
||||
[Fact]
|
||||
public async Task Resubmitting_same_primary_rows_produces_same_index_keys()
|
||||
{
|
||||
// Simulates the M5.d.4 timer re-enqueueing primary rows it already handled —
|
||||
// the handler's index-row keys must be key-stable so the real TableIndexRepository's
|
||||
// UpsertReplace collapses duplicates rather than appending rows.
|
||||
var (handler, repo) = Sut();
|
||||
|
||||
var signal = new SignalRecord
|
||||
{
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
SessionSignalOrdinal = 1,
|
||||
Kind = "DesktopArrived",
|
||||
OccurredAtUtc = Occurred,
|
||||
};
|
||||
var transition = TerminalTransition();
|
||||
|
||||
// First pass: initial ingest fan-out.
|
||||
await handler.HandleAsync(IndexReconcileEnvelopeFactory.FromSignal(signal));
|
||||
await handler.HandleAsync(IndexReconcileEnvelopeFactory.FromDecisionTransition(transition));
|
||||
|
||||
// Second pass: 2h-timer reconcile resubmits the same primaries.
|
||||
await handler.HandleAsync(IndexReconcileEnvelopeFactory.FromSignal(signal));
|
||||
await handler.HandleAsync(IndexReconcileEnvelopeFactory.FromDecisionTransition(transition));
|
||||
|
||||
// The fake repo captures one row per call, but all duplicated rows must map to the
|
||||
// same (PK, RK) — the real Azure Tables Upsert would collapse them.
|
||||
Assert.Equal(2, repo.SignalsByKind.Count);
|
||||
var signalKeys = repo.SignalsByKind
|
||||
.Select(r => (
|
||||
Pk: IndexRowKeys.BuildSignalsByKindPk(r.TenantId, r.SignalKind),
|
||||
Rk: IndexRowKeys.BuildSignalsByKindRk(r.OccurredAtUtc, r.SessionId, r.SessionSignalOrdinal)))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
Assert.Single(signalKeys);
|
||||
|
||||
Assert.Equal(2, repo.SessionsByTerminal.Count);
|
||||
var terminalKeys = repo.SessionsByTerminal
|
||||
.Select(r => (
|
||||
Pk: IndexRowKeys.BuildSessionsByTerminalPk(r.TenantId, r.TerminalStage),
|
||||
Rk: IndexRowKeys.BuildSessionsByTerminalRk(r.OccurredAtUtc, r.SessionId)))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
Assert.Single(terminalKeys);
|
||||
|
||||
Assert.Equal(2, repo.SessionsByStage.Count);
|
||||
var stageKeys = repo.SessionsByStage
|
||||
.Select(r => (
|
||||
Pk: IndexRowKeys.BuildSessionsByStagePk(r.TenantId, r.Stage),
|
||||
Rk: IndexRowKeys.BuildSessionsByStageRk(r.LastUpdatedUtc, r.SessionId)))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
Assert.Single(stageKeys);
|
||||
|
||||
Assert.Equal(2, repo.ClassifierVerdictsByIdLevel.Count);
|
||||
var verdictKeys = repo.ClassifierVerdictsByIdLevel
|
||||
.Select(r => (
|
||||
Pk: IndexRowKeys.BuildClassifierVerdictsByIdLevelPk(r.TenantId, r.ClassifierId, r.HypothesisLevel),
|
||||
Rk: IndexRowKeys.BuildClassifierVerdictsByIdLevelRk(r.OccurredAtUtc, r.SessionId, r.StepIndex)))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
Assert.Single(verdictKeys);
|
||||
}
|
||||
|
||||
// ============================================================ helpers
|
||||
|
||||
private static DecisionTransitionRecord TerminalTransition()
|
||||
=> new()
|
||||
{
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
StepIndex = 7,
|
||||
FromStage = "EspInProgress",
|
||||
ToStage = "WhiteGloveSealed",
|
||||
Taken = true,
|
||||
IsTerminal = true,
|
||||
ClassifierVerdictId = "whiteglove-sealing",
|
||||
ClassifierHypothesisLevel = "Strong",
|
||||
OccurredAtUtc = Occurred,
|
||||
};
|
||||
|
||||
private sealed class FakeIndexTableRepository : IIndexTableRepository
|
||||
{
|
||||
public List<SessionsByTerminalRecord> SessionsByTerminal { get; } = new();
|
||||
public List<SessionsByStageRecord> SessionsByStage { get; } = new();
|
||||
public List<DeadEndsByReasonRecord> DeadEndsByReason { get; } = new();
|
||||
public List<ClassifierVerdictsByIdLevelRecord> ClassifierVerdictsByIdLevel { get; } = new();
|
||||
public List<SignalsByKindRecord> SignalsByKind { get; } = new();
|
||||
|
||||
public Task<int> StoreSessionsByTerminalAsync(IReadOnlyList<SessionsByTerminalRecord> records, CancellationToken ct = default)
|
||||
{ SessionsByTerminal.AddRange(records); return Task.FromResult(records.Count); }
|
||||
public Task<int> StoreSessionsByStageAsync(IReadOnlyList<SessionsByStageRecord> records, CancellationToken ct = default)
|
||||
{ SessionsByStage.AddRange(records); return Task.FromResult(records.Count); }
|
||||
public Task<int> StoreDeadEndsByReasonAsync(IReadOnlyList<DeadEndsByReasonRecord> records, CancellationToken ct = default)
|
||||
{ DeadEndsByReason.AddRange(records); return Task.FromResult(records.Count); }
|
||||
public Task<int> StoreClassifierVerdictsByIdLevelAsync(IReadOnlyList<ClassifierVerdictsByIdLevelRecord> records, CancellationToken ct = default)
|
||||
{ ClassifierVerdictsByIdLevel.AddRange(records); return Task.FromResult(records.Count); }
|
||||
public Task<int> StoreSignalsByKindAsync(IReadOnlyList<SignalsByKindRecord> records, CancellationToken ct = default)
|
||||
{ SignalsByKind.AddRange(records); return Task.FromResult(records.Count); }
|
||||
}
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
using AutopilotMonitor.Functions.Services.Indexing;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pure tests for <see cref="IndexReconcileEnvelopeFactory"/> (Plan §2.8, §M5.d).
|
||||
/// Verifies the shape-only projection from primary record → queue envelope — the
|
||||
/// consumer (M5.d.3) relies on these fields being copied verbatim.
|
||||
/// </summary>
|
||||
public class IndexReconcileEnvelopeFactoryTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "b2c3d4e5-f6a7-8901-bcde-f12345678901";
|
||||
|
||||
private static readonly DateTime Occurred =
|
||||
new(2026, 4, 21, 14, 7, 33, DateTimeKind.Utc);
|
||||
|
||||
// ============================================================ FromSignal
|
||||
|
||||
[Fact]
|
||||
public void FromSignal_copies_discriminators_and_back_ref()
|
||||
{
|
||||
var record = new SignalRecord
|
||||
{
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
SessionSignalOrdinal = 42,
|
||||
SessionTraceOrdinal = 117,
|
||||
Kind = "EspTerminalFailure",
|
||||
KindSchemaVersion = 2,
|
||||
OccurredAtUtc = Occurred,
|
||||
SourceOrigin = "EspAndHelloTrackerAdapter",
|
||||
PayloadJson = "{}",
|
||||
};
|
||||
|
||||
var envelope = IndexReconcileEnvelopeFactory.FromSignal(record);
|
||||
|
||||
Assert.Equal("1", envelope.EnvelopeVersion);
|
||||
Assert.Equal("Signal", envelope.SourceKind);
|
||||
Assert.Equal(TenantId, envelope.TenantId);
|
||||
Assert.Equal(SessionId, envelope.SessionId);
|
||||
Assert.Equal(Occurred, envelope.OccurredAtUtc);
|
||||
Assert.Equal(42L, envelope.SessionSignalOrdinal);
|
||||
Assert.Equal("EspTerminalFailure", envelope.SignalKind);
|
||||
Assert.Equal("EspAndHelloTrackerAdapter", envelope.SourceOrigin);
|
||||
|
||||
// DecisionTransition-only fields stay null on Signal envelopes.
|
||||
Assert.Null(envelope.StepIndex);
|
||||
Assert.Null(envelope.FromStage);
|
||||
Assert.Null(envelope.ToStage);
|
||||
Assert.Null(envelope.Taken);
|
||||
Assert.Null(envelope.IsTerminal);
|
||||
Assert.Null(envelope.DeadEndReason);
|
||||
Assert.Null(envelope.ClassifierVerdictId);
|
||||
Assert.Null(envelope.ClassifierHypothesisLevel);
|
||||
}
|
||||
|
||||
// ============================================================ FromDecisionTransition
|
||||
|
||||
[Fact]
|
||||
public void FromDecisionTransition_taken_terminal_with_classifier_copies_all_discriminators()
|
||||
{
|
||||
var record = new DecisionTransitionRecord
|
||||
{
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
StepIndex = 7,
|
||||
SessionTraceOrdinal = 118,
|
||||
SignalOrdinalRef = 42,
|
||||
OccurredAtUtc = Occurred,
|
||||
Trigger = "EspExiting",
|
||||
FromStage = "EspInProgress",
|
||||
ToStage = "WhiteGloveSealed",
|
||||
Taken = true,
|
||||
DeadEndReason = null,
|
||||
ReducerVersion = "1.0.0",
|
||||
IsTerminal = true,
|
||||
ClassifierVerdictId = "whiteglove-sealing",
|
||||
ClassifierHypothesisLevel = "Strong",
|
||||
PayloadJson = "{}",
|
||||
};
|
||||
|
||||
var envelope = IndexReconcileEnvelopeFactory.FromDecisionTransition(record);
|
||||
|
||||
Assert.Equal("1", envelope.EnvelopeVersion);
|
||||
Assert.Equal("DecisionTransition", envelope.SourceKind);
|
||||
Assert.Equal(TenantId, envelope.TenantId);
|
||||
Assert.Equal(SessionId, envelope.SessionId);
|
||||
Assert.Equal(Occurred, envelope.OccurredAtUtc);
|
||||
Assert.Equal(7, envelope.StepIndex);
|
||||
Assert.Equal("EspInProgress", envelope.FromStage);
|
||||
Assert.Equal("WhiteGloveSealed", envelope.ToStage);
|
||||
Assert.Equal(true, envelope.Taken);
|
||||
Assert.Equal(true, envelope.IsTerminal);
|
||||
Assert.Null(envelope.DeadEndReason);
|
||||
Assert.Equal("whiteglove-sealing", envelope.ClassifierVerdictId);
|
||||
Assert.Equal("Strong", envelope.ClassifierHypothesisLevel);
|
||||
|
||||
// Signal-only fields stay null on DecisionTransition envelopes.
|
||||
Assert.Null(envelope.SessionSignalOrdinal);
|
||||
Assert.Null(envelope.SignalKind);
|
||||
Assert.Null(envelope.SourceOrigin);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FromDecisionTransition_dead_end_carries_reason_without_classifier_fields()
|
||||
{
|
||||
var record = new DecisionTransitionRecord
|
||||
{
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
StepIndex = 3,
|
||||
OccurredAtUtc = Occurred,
|
||||
Trigger = "EspExiting",
|
||||
FromStage = "EspInProgress",
|
||||
ToStage = "EspInProgress",
|
||||
Taken = false,
|
||||
DeadEndReason = "hybrid_reboot_gate_blocking",
|
||||
ReducerVersion = "1.0.0",
|
||||
IsTerminal = false,
|
||||
PayloadJson = "{}",
|
||||
};
|
||||
|
||||
var envelope = IndexReconcileEnvelopeFactory.FromDecisionTransition(record);
|
||||
|
||||
Assert.Equal(false, envelope.Taken);
|
||||
Assert.Equal(false, envelope.IsTerminal);
|
||||
Assert.Equal("hybrid_reboot_gate_blocking", envelope.DeadEndReason);
|
||||
Assert.Null(envelope.ClassifierVerdictId);
|
||||
Assert.Null(envelope.ClassifierHypothesisLevel);
|
||||
}
|
||||
|
||||
// ============================================================ BuildBatch
|
||||
|
||||
[Fact]
|
||||
public void BuildBatch_preserves_input_order_and_kind_tags()
|
||||
{
|
||||
var signals = new List<SignalRecord>
|
||||
{
|
||||
new() { TenantId = TenantId, SessionId = SessionId, SessionSignalOrdinal = 1, Kind = "EspPhaseChanged", OccurredAtUtc = Occurred },
|
||||
new() { TenantId = TenantId, SessionId = SessionId, SessionSignalOrdinal = 2, Kind = "DesktopArrived", OccurredAtUtc = Occurred },
|
||||
};
|
||||
var transitions = new List<DecisionTransitionRecord>
|
||||
{
|
||||
new() { TenantId = TenantId, SessionId = SessionId, StepIndex = 1, FromStage = "A", ToStage = "B", Taken = true, OccurredAtUtc = Occurred },
|
||||
};
|
||||
|
||||
var envelopes = IndexReconcileEnvelopeFactory.BuildBatch(signals, transitions);
|
||||
|
||||
Assert.Equal(3, envelopes.Count);
|
||||
Assert.Equal("Signal", envelopes[0].SourceKind);
|
||||
Assert.Equal(1L, envelopes[0].SessionSignalOrdinal);
|
||||
Assert.Equal("Signal", envelopes[1].SourceKind);
|
||||
Assert.Equal(2L, envelopes[1].SessionSignalOrdinal);
|
||||
Assert.Equal("DecisionTransition", envelopes[2].SourceKind);
|
||||
Assert.Equal(1, envelopes[2].StepIndex);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildBatch_returns_empty_for_null_or_empty_inputs()
|
||||
{
|
||||
Assert.Empty(IndexReconcileEnvelopeFactory.BuildBatch(
|
||||
new List<SignalRecord>(), new List<DecisionTransitionRecord>()));
|
||||
Assert.Empty(IndexReconcileEnvelopeFactory.BuildBatch(null!, null!));
|
||||
}
|
||||
}
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// JSON round-trip tests for <see cref="IndexReconcileEnvelope"/> (Plan §2.8, §M5.d).
|
||||
/// The producer (M5.d.2) serializes with Newtonsoft; the queue-triggered consumer
|
||||
/// (M5.d.3) must deserialize the same shape back — verified here so the contract
|
||||
/// doesn't drift silently as fields are added.
|
||||
/// </summary>
|
||||
public class IndexReconcileEnvelopeSerializationTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "b2c3d4e5-f6a7-8901-bcde-f12345678901";
|
||||
|
||||
private static readonly DateTime Occurred =
|
||||
new(2026, 4, 21, 14, 7, 33, DateTimeKind.Utc);
|
||||
|
||||
[Fact]
|
||||
public void Signal_envelope_round_trips_through_newtonsoft()
|
||||
{
|
||||
var original = new IndexReconcileEnvelope
|
||||
{
|
||||
EnvelopeVersion = "1",
|
||||
SourceKind = "Signal",
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
OccurredAtUtc = Occurred,
|
||||
SessionSignalOrdinal = 42,
|
||||
SignalKind = "EspTerminalFailure",
|
||||
SourceOrigin = "EspAndHelloTrackerAdapter",
|
||||
};
|
||||
|
||||
var json = JsonConvert.SerializeObject(original);
|
||||
var restored = JsonConvert.DeserializeObject<IndexReconcileEnvelope>(json);
|
||||
|
||||
Assert.NotNull(restored);
|
||||
Assert.Equal("1", restored!.EnvelopeVersion);
|
||||
Assert.Equal("Signal", restored.SourceKind);
|
||||
Assert.Equal(TenantId, restored.TenantId);
|
||||
Assert.Equal(SessionId, restored.SessionId);
|
||||
Assert.Equal(Occurred, restored.OccurredAtUtc.ToUniversalTime());
|
||||
Assert.Equal(42L, restored.SessionSignalOrdinal);
|
||||
Assert.Equal("EspTerminalFailure", restored.SignalKind);
|
||||
Assert.Equal("EspAndHelloTrackerAdapter", restored.SourceOrigin);
|
||||
Assert.Null(restored.StepIndex);
|
||||
Assert.Null(restored.ClassifierVerdictId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecisionTransition_envelope_round_trips_all_discriminators()
|
||||
{
|
||||
var original = new IndexReconcileEnvelope
|
||||
{
|
||||
EnvelopeVersion = "1",
|
||||
SourceKind = "DecisionTransition",
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
OccurredAtUtc = Occurred,
|
||||
StepIndex = 7,
|
||||
FromStage = "EspInProgress",
|
||||
ToStage = "WhiteGloveSealed",
|
||||
Taken = true,
|
||||
IsTerminal = true,
|
||||
DeadEndReason = null,
|
||||
ClassifierVerdictId = "whiteglove-sealing",
|
||||
ClassifierHypothesisLevel = "Strong",
|
||||
};
|
||||
|
||||
var json = JsonConvert.SerializeObject(original);
|
||||
var restored = JsonConvert.DeserializeObject<IndexReconcileEnvelope>(json);
|
||||
|
||||
Assert.NotNull(restored);
|
||||
Assert.Equal("DecisionTransition", restored!.SourceKind);
|
||||
Assert.Equal(7, restored.StepIndex);
|
||||
Assert.Equal("EspInProgress", restored.FromStage);
|
||||
Assert.Equal("WhiteGloveSealed", restored.ToStage);
|
||||
Assert.Equal(true, restored.Taken);
|
||||
Assert.Equal(true, restored.IsTerminal);
|
||||
Assert.Null(restored.DeadEndReason);
|
||||
Assert.Equal("whiteglove-sealing", restored.ClassifierVerdictId);
|
||||
Assert.Equal("Strong", restored.ClassifierHypothesisLevel);
|
||||
Assert.Null(restored.SessionSignalOrdinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialization_tolerates_missing_optional_fields()
|
||||
{
|
||||
// A minimal envelope from a consumer-compatible-but-older writer should still parse.
|
||||
const string minimal =
|
||||
"{\"envelopeVersion\":\"1\",\"sourceKind\":\"Signal\",\"tenantId\":\"t\",\"sessionId\":\"s\",\"occurredAtUtc\":\"2026-04-21T14:07:33Z\"}";
|
||||
|
||||
var restored = JsonConvert.DeserializeObject<IndexReconcileEnvelope>(minimal);
|
||||
|
||||
Assert.NotNull(restored);
|
||||
Assert.Equal("Signal", restored!.SourceKind);
|
||||
Assert.Null(restored.SessionSignalOrdinal);
|
||||
Assert.Null(restored.SignalKind);
|
||||
Assert.Null(restored.StepIndex);
|
||||
}
|
||||
}
|
||||
@@ -1,321 +0,0 @@
|
||||
using AutopilotMonitor.Functions.Services.Indexing;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Routing tests for <see cref="IndexReconcileHandler"/> (Plan §2.8, §M5.d.3). Verifies
|
||||
/// the 0–3 fan-out decisions per envelope shape using a capture-only fake repo —
|
||||
/// the real <c>TableIndexRepository</c> mapping is covered by <see cref="TableIndexRepositoryMappingTests"/>.
|
||||
/// </summary>
|
||||
public class IndexReconcileHandlerTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "b2c3d4e5-f6a7-8901-bcde-f12345678901";
|
||||
|
||||
private static readonly DateTime Occurred =
|
||||
new(2026, 4, 21, 14, 7, 33, DateTimeKind.Utc);
|
||||
|
||||
private static (IndexReconcileHandler handler, FakeIndexTableRepository repo) Sut()
|
||||
{
|
||||
var repo = new FakeIndexTableRepository();
|
||||
var handler = new IndexReconcileHandler(repo, NullLogger<IndexReconcileHandler>.Instance);
|
||||
return (handler, repo);
|
||||
}
|
||||
|
||||
// ============================================================ Signal routing
|
||||
|
||||
[Fact]
|
||||
public async Task Signal_envelope_writes_exactly_one_SignalsByKind_row()
|
||||
{
|
||||
var (handler, repo) = Sut();
|
||||
|
||||
await handler.HandleAsync(new IndexReconcileEnvelope
|
||||
{
|
||||
SourceKind = "Signal",
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
OccurredAtUtc = Occurred,
|
||||
SessionSignalOrdinal = 42,
|
||||
SignalKind = "EspTerminalFailure",
|
||||
SourceOrigin = "EspAndHelloTrackerAdapter",
|
||||
});
|
||||
|
||||
Assert.Single(repo.SignalsByKind);
|
||||
var row = repo.SignalsByKind[0];
|
||||
Assert.Equal(TenantId, row.TenantId);
|
||||
Assert.Equal(SessionId, row.SessionId);
|
||||
Assert.Equal("EspTerminalFailure", row.SignalKind);
|
||||
Assert.Equal(42L, row.SessionSignalOrdinal);
|
||||
Assert.Equal("EspAndHelloTrackerAdapter", row.SourceOrigin);
|
||||
Assert.Equal(Occurred, row.OccurredAtUtc);
|
||||
|
||||
// Other tables untouched.
|
||||
Assert.Empty(repo.SessionsByTerminal);
|
||||
Assert.Empty(repo.SessionsByStage);
|
||||
Assert.Empty(repo.DeadEndsByReason);
|
||||
Assert.Empty(repo.ClassifierVerdictsByIdLevel);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Signal_envelope_missing_ordinal_is_dropped()
|
||||
{
|
||||
var (handler, repo) = Sut();
|
||||
|
||||
await handler.HandleAsync(new IndexReconcileEnvelope
|
||||
{
|
||||
SourceKind = "Signal",
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
OccurredAtUtc = Occurred,
|
||||
SessionSignalOrdinal = null,
|
||||
SignalKind = "EspPhaseChanged",
|
||||
});
|
||||
|
||||
Assert.Empty(repo.SignalsByKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Signal_envelope_missing_kind_is_dropped()
|
||||
{
|
||||
var (handler, repo) = Sut();
|
||||
|
||||
await handler.HandleAsync(new IndexReconcileEnvelope
|
||||
{
|
||||
SourceKind = "Signal",
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
OccurredAtUtc = Occurred,
|
||||
SessionSignalOrdinal = 1,
|
||||
SignalKind = string.Empty,
|
||||
});
|
||||
|
||||
Assert.Empty(repo.SignalsByKind);
|
||||
}
|
||||
|
||||
// ============================================================ DecisionTransition routing — all 4 paths
|
||||
|
||||
[Fact]
|
||||
public async Task DecisionTransition_terminal_taken_with_classifier_writes_three_index_rows()
|
||||
{
|
||||
var (handler, repo) = Sut();
|
||||
|
||||
// WhiteGlove-sealing: Taken=true, IsTerminal=true, classifier verdict attached.
|
||||
// Expected: SessionsByTerminal + SessionsByStage + ClassifierVerdictsByIdLevel (3 rows).
|
||||
await handler.HandleAsync(new IndexReconcileEnvelope
|
||||
{
|
||||
SourceKind = "DecisionTransition",
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
OccurredAtUtc = Occurred,
|
||||
StepIndex = 7,
|
||||
FromStage = "EspInProgress",
|
||||
ToStage = "WhiteGloveSealed",
|
||||
Taken = true,
|
||||
IsTerminal = true,
|
||||
ClassifierVerdictId = "whiteglove-sealing",
|
||||
ClassifierHypothesisLevel = "Strong",
|
||||
});
|
||||
|
||||
Assert.Single(repo.SessionsByTerminal);
|
||||
Assert.Equal("WhiteGloveSealed", repo.SessionsByTerminal[0].TerminalStage);
|
||||
Assert.Equal(7, repo.SessionsByTerminal[0].StepIndex);
|
||||
|
||||
Assert.Single(repo.SessionsByStage);
|
||||
Assert.Equal("WhiteGloveSealed", repo.SessionsByStage[0].Stage);
|
||||
Assert.Equal(Occurred, repo.SessionsByStage[0].LastUpdatedUtc);
|
||||
|
||||
Assert.Single(repo.ClassifierVerdictsByIdLevel);
|
||||
Assert.Equal("whiteglove-sealing", repo.ClassifierVerdictsByIdLevel[0].ClassifierId);
|
||||
Assert.Equal("Strong", repo.ClassifierVerdictsByIdLevel[0].HypothesisLevel);
|
||||
|
||||
// Dead-end path not triggered for Taken=true.
|
||||
Assert.Empty(repo.DeadEndsByReason);
|
||||
// Signal path never touched on a DecisionTransition envelope.
|
||||
Assert.Empty(repo.SignalsByKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DecisionTransition_taken_non_terminal_no_classifier_writes_only_SessionsByStage()
|
||||
{
|
||||
var (handler, repo) = Sut();
|
||||
|
||||
await handler.HandleAsync(new IndexReconcileEnvelope
|
||||
{
|
||||
SourceKind = "DecisionTransition",
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
OccurredAtUtc = Occurred,
|
||||
StepIndex = 3,
|
||||
FromStage = "AwaitingEsp",
|
||||
ToStage = "EspInProgress",
|
||||
Taken = true,
|
||||
IsTerminal = false,
|
||||
});
|
||||
|
||||
Assert.Empty(repo.SessionsByTerminal);
|
||||
Assert.Single(repo.SessionsByStage);
|
||||
Assert.Empty(repo.DeadEndsByReason);
|
||||
Assert.Empty(repo.ClassifierVerdictsByIdLevel);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DecisionTransition_dead_end_with_classifier_writes_DeadEndsByReason_and_verdict()
|
||||
{
|
||||
var (handler, repo) = Sut();
|
||||
|
||||
await handler.HandleAsync(new IndexReconcileEnvelope
|
||||
{
|
||||
SourceKind = "DecisionTransition",
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
OccurredAtUtc = Occurred,
|
||||
StepIndex = 5,
|
||||
FromStage = "EspInProgress",
|
||||
ToStage = "EspInProgress",
|
||||
Taken = false,
|
||||
IsTerminal = false,
|
||||
DeadEndReason = "hybrid_reboot_gate_blocking",
|
||||
ClassifierVerdictId = "whiteglove-sealing",
|
||||
ClassifierHypothesisLevel = "Weak",
|
||||
});
|
||||
|
||||
Assert.Single(repo.DeadEndsByReason);
|
||||
Assert.Equal("hybrid_reboot_gate_blocking", repo.DeadEndsByReason[0].DeadEndReason);
|
||||
Assert.Equal("EspInProgress", repo.DeadEndsByReason[0].FromStage);
|
||||
Assert.Equal("EspInProgress", repo.DeadEndsByReason[0].AttemptedToStage);
|
||||
|
||||
Assert.Single(repo.ClassifierVerdictsByIdLevel);
|
||||
Assert.Equal("Weak", repo.ClassifierVerdictsByIdLevel[0].HypothesisLevel);
|
||||
|
||||
// Taken=false → SessionsByStage is NOT updated (no stage entry).
|
||||
Assert.Empty(repo.SessionsByStage);
|
||||
Assert.Empty(repo.SessionsByTerminal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DecisionTransition_dead_end_without_reason_writes_nothing_to_DeadEnds()
|
||||
{
|
||||
// Defense in depth: an envelope with Taken=false but no reason should not create a
|
||||
// DeadEnd row (empty reason would collide into a single PK across unrelated blocks).
|
||||
var (handler, repo) = Sut();
|
||||
|
||||
await handler.HandleAsync(new IndexReconcileEnvelope
|
||||
{
|
||||
SourceKind = "DecisionTransition",
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
OccurredAtUtc = Occurred,
|
||||
StepIndex = 1,
|
||||
FromStage = "A",
|
||||
ToStage = "A",
|
||||
Taken = false,
|
||||
DeadEndReason = null,
|
||||
});
|
||||
|
||||
Assert.Empty(repo.DeadEndsByReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DecisionTransition_missing_stepIndex_is_dropped_entirely()
|
||||
{
|
||||
var (handler, repo) = Sut();
|
||||
|
||||
await handler.HandleAsync(new IndexReconcileEnvelope
|
||||
{
|
||||
SourceKind = "DecisionTransition",
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
OccurredAtUtc = Occurred,
|
||||
StepIndex = null,
|
||||
ToStage = "WhiteGloveSealed",
|
||||
Taken = true,
|
||||
IsTerminal = true,
|
||||
});
|
||||
|
||||
Assert.Empty(repo.SessionsByTerminal);
|
||||
Assert.Empty(repo.SessionsByStage);
|
||||
Assert.Empty(repo.DeadEndsByReason);
|
||||
Assert.Empty(repo.ClassifierVerdictsByIdLevel);
|
||||
}
|
||||
|
||||
// ============================================================ Misc
|
||||
|
||||
[Fact]
|
||||
public async Task Unknown_SourceKind_is_logged_and_dropped()
|
||||
{
|
||||
var (handler, repo) = Sut();
|
||||
|
||||
await handler.HandleAsync(new IndexReconcileEnvelope
|
||||
{
|
||||
SourceKind = "FutureThingWeDontKnowAbout",
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
OccurredAtUtc = Occurred,
|
||||
});
|
||||
|
||||
Assert.Empty(repo.SignalsByKind);
|
||||
Assert.Empty(repo.SessionsByTerminal);
|
||||
Assert.Empty(repo.SessionsByStage);
|
||||
Assert.Empty(repo.DeadEndsByReason);
|
||||
Assert.Empty(repo.ClassifierVerdictsByIdLevel);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Null_envelope_is_logged_and_dropped()
|
||||
{
|
||||
var (handler, repo) = Sut();
|
||||
|
||||
await handler.HandleAsync(null!);
|
||||
|
||||
Assert.Empty(repo.SignalsByKind);
|
||||
}
|
||||
|
||||
// ============================================================ FakeIndexTableRepository
|
||||
|
||||
private sealed class FakeIndexTableRepository : IIndexTableRepository
|
||||
{
|
||||
public List<SessionsByTerminalRecord> SessionsByTerminal { get; } = new();
|
||||
public List<SessionsByStageRecord> SessionsByStage { get; } = new();
|
||||
public List<DeadEndsByReasonRecord> DeadEndsByReason { get; } = new();
|
||||
public List<ClassifierVerdictsByIdLevelRecord> ClassifierVerdictsByIdLevel { get; } = new();
|
||||
public List<SignalsByKindRecord> SignalsByKind { get; } = new();
|
||||
|
||||
public Task<int> StoreSessionsByTerminalAsync(
|
||||
IReadOnlyList<SessionsByTerminalRecord> records, CancellationToken cancellationToken = default)
|
||||
{
|
||||
SessionsByTerminal.AddRange(records);
|
||||
return Task.FromResult(records.Count);
|
||||
}
|
||||
|
||||
public Task<int> StoreSessionsByStageAsync(
|
||||
IReadOnlyList<SessionsByStageRecord> records, CancellationToken cancellationToken = default)
|
||||
{
|
||||
SessionsByStage.AddRange(records);
|
||||
return Task.FromResult(records.Count);
|
||||
}
|
||||
|
||||
public Task<int> StoreDeadEndsByReasonAsync(
|
||||
IReadOnlyList<DeadEndsByReasonRecord> records, CancellationToken cancellationToken = default)
|
||||
{
|
||||
DeadEndsByReason.AddRange(records);
|
||||
return Task.FromResult(records.Count);
|
||||
}
|
||||
|
||||
public Task<int> StoreClassifierVerdictsByIdLevelAsync(
|
||||
IReadOnlyList<ClassifierVerdictsByIdLevelRecord> records, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ClassifierVerdictsByIdLevel.AddRange(records);
|
||||
return Task.FromResult(records.Count);
|
||||
}
|
||||
|
||||
public Task<int> StoreSignalsByKindAsync(
|
||||
IReadOnlyList<SignalsByKindRecord> records, CancellationToken cancellationToken = default)
|
||||
{
|
||||
SignalsByKind.AddRange(records);
|
||||
return Task.FromResult(records.Count);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
using AutopilotMonitor.Functions.Functions.Admin;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the 2h safety-net <see cref="IndexReconcileTimer"/> (Plan §2.8, §M5.d.4).
|
||||
/// Covers the flag-gate short-circuit, the happy path (enqueue every primary row
|
||||
/// in the window), and the empty-window case.
|
||||
/// </summary>
|
||||
public class IndexReconcileTimerTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "b2c3d4e5-f6a7-8901-bcde-f12345678901";
|
||||
|
||||
private static readonly DateTime Cutoff = new(2026, 4, 21, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
// ============================================================ flag-off short-circuit
|
||||
|
||||
[Fact]
|
||||
public async Task Feature_flag_off_skips_queries_and_enqueue()
|
||||
{
|
||||
var adminConfigSvc = BuildAdminConfigService(enableIndexDualWrite: false);
|
||||
var signalRepo = new Mock<ISignalRepository>(MockBehavior.Strict);
|
||||
var transitionRepo = new Mock<IDecisionTransitionRepository>(MockBehavior.Strict);
|
||||
var producer = new Mock<IIndexReconcileProducer>(MockBehavior.Strict);
|
||||
|
||||
var timer = new IndexReconcileTimer(
|
||||
adminConfigSvc,
|
||||
signalRepo.Object,
|
||||
transitionRepo.Object,
|
||||
producer.Object,
|
||||
NullLogger<IndexReconcileTimer>.Instance);
|
||||
|
||||
await timer.RunReconcileAsync(Cutoff, default);
|
||||
|
||||
// Strict mocks throw if any unconfigured call happens — so zero setups + no throw
|
||||
// proves the timer short-circuited before any query / enqueue.
|
||||
signalRepo.VerifyNoOtherCalls();
|
||||
transitionRepo.VerifyNoOtherCalls();
|
||||
producer.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
// ============================================================ happy path
|
||||
|
||||
[Fact]
|
||||
public async Task Flag_on_with_primary_rows_enqueues_all_envelopes()
|
||||
{
|
||||
var adminConfigSvc = BuildAdminConfigService(enableIndexDualWrite: true);
|
||||
|
||||
var signals = new List<SignalRecord>
|
||||
{
|
||||
new() { TenantId = TenantId, SessionId = SessionId, SessionSignalOrdinal = 1, Kind = "EspPhaseChanged", OccurredAtUtc = Cutoff.AddMinutes(5) },
|
||||
new() { TenantId = TenantId, SessionId = SessionId, SessionSignalOrdinal = 2, Kind = "DesktopArrived", OccurredAtUtc = Cutoff.AddMinutes(10) },
|
||||
};
|
||||
var transitions = new List<DecisionTransitionRecord>
|
||||
{
|
||||
new() { TenantId = TenantId, SessionId = SessionId, StepIndex = 1, Taken = true, FromStage = "A", ToStage = "B", OccurredAtUtc = Cutoff.AddMinutes(7) },
|
||||
};
|
||||
|
||||
var signalRepo = new Mock<ISignalRepository>();
|
||||
signalRepo
|
||||
.Setup(r => r.QueryByTimestampAtOrAfterAsync(Cutoff, It.IsAny<int>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(signals);
|
||||
var transitionRepo = new Mock<IDecisionTransitionRepository>();
|
||||
transitionRepo
|
||||
.Setup(r => r.QueryByTimestampAtOrAfterAsync(Cutoff, It.IsAny<int>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(transitions);
|
||||
|
||||
List<IndexReconcileEnvelope>? captured = null;
|
||||
var producer = new Mock<IIndexReconcileProducer>();
|
||||
producer
|
||||
.Setup(p => p.EnqueueBatchAsync(It.IsAny<IReadOnlyList<IndexReconcileEnvelope>>(), It.IsAny<CancellationToken>()))
|
||||
.Callback<IReadOnlyList<IndexReconcileEnvelope>, CancellationToken>((e, _) => captured = e.ToList())
|
||||
.ReturnsAsync(3);
|
||||
|
||||
var timer = new IndexReconcileTimer(
|
||||
adminConfigSvc,
|
||||
signalRepo.Object,
|
||||
transitionRepo.Object,
|
||||
producer.Object,
|
||||
NullLogger<IndexReconcileTimer>.Instance);
|
||||
|
||||
await timer.RunReconcileAsync(Cutoff, default);
|
||||
|
||||
Assert.NotNull(captured);
|
||||
Assert.Equal(3, captured!.Count);
|
||||
Assert.Equal("Signal", captured[0].SourceKind);
|
||||
Assert.Equal(1L, captured[0].SessionSignalOrdinal);
|
||||
Assert.Equal("Signal", captured[1].SourceKind);
|
||||
Assert.Equal(2L, captured[1].SessionSignalOrdinal);
|
||||
Assert.Equal("DecisionTransition", captured[2].SourceKind);
|
||||
Assert.Equal(1, captured[2].StepIndex);
|
||||
}
|
||||
|
||||
// ============================================================ empty-window: no enqueue
|
||||
|
||||
[Fact]
|
||||
public async Task Flag_on_empty_window_skips_enqueue()
|
||||
{
|
||||
var adminConfigSvc = BuildAdminConfigService(enableIndexDualWrite: true);
|
||||
|
||||
var signalRepo = new Mock<ISignalRepository>();
|
||||
signalRepo
|
||||
.Setup(r => r.QueryByTimestampAtOrAfterAsync(Cutoff, It.IsAny<int>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<SignalRecord>());
|
||||
var transitionRepo = new Mock<IDecisionTransitionRepository>();
|
||||
transitionRepo
|
||||
.Setup(r => r.QueryByTimestampAtOrAfterAsync(Cutoff, It.IsAny<int>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<DecisionTransitionRecord>());
|
||||
|
||||
var producer = new Mock<IIndexReconcileProducer>(MockBehavior.Strict);
|
||||
|
||||
var timer = new IndexReconcileTimer(
|
||||
adminConfigSvc,
|
||||
signalRepo.Object,
|
||||
transitionRepo.Object,
|
||||
producer.Object,
|
||||
NullLogger<IndexReconcileTimer>.Instance);
|
||||
|
||||
await timer.RunReconcileAsync(Cutoff, default);
|
||||
|
||||
// Empty batch → no producer call (strict mock throws otherwise).
|
||||
producer.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
// ============================================================ cutoff window invariant
|
||||
|
||||
[Fact]
|
||||
public void ReconcileWindow_is_4_hours_and_larger_than_timer_cadence()
|
||||
{
|
||||
// The 2h cron fires every 2h but scans a 4h window — so every primary row is
|
||||
// re-checked at least twice before falling out of range. Protect the invariant.
|
||||
Assert.Equal(TimeSpan.FromHours(4), IndexReconcileTimer.ReconcileWindow);
|
||||
}
|
||||
|
||||
// ============================================================ helpers
|
||||
|
||||
private static AdminConfigurationService BuildAdminConfigService(bool enableIndexDualWrite)
|
||||
{
|
||||
var mock = new Mock<AdminConfigurationService>(
|
||||
Mock.Of<IConfigRepository>(),
|
||||
NullLogger<AdminConfigurationService>.Instance,
|
||||
new MemoryCache(new MemoryCacheOptions()));
|
||||
|
||||
mock.Setup(s => s.GetConfigurationAsync())
|
||||
.ReturnsAsync(new AdminConfiguration { EnableIndexDualWrite = enableIndexDualWrite });
|
||||
|
||||
return mock.Object;
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
using AutopilotMonitor.Functions.DataAccess.TableStorage;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pure PK/RK format tests for <see cref="IndexRowKeys"/> (Plan §2.8 query matrix, §M5.d).
|
||||
/// These verify the string shape contract the queue-driven index writer + the reconciliation
|
||||
/// timer both depend on — any drift here silently breaks cross-session queries.
|
||||
/// </summary>
|
||||
public class IndexRowKeysTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "b2c3d4e5-f6a7-8901-bcde-f12345678901";
|
||||
|
||||
private static readonly DateTime Occurred =
|
||||
new(2026, 4, 21, 14, 7, 33, DateTimeKind.Utc);
|
||||
|
||||
// ============================================================ SessionsByTerminal
|
||||
|
||||
[Fact]
|
||||
public void SessionsByTerminal_pk_is_tenant_underscore_terminalStage()
|
||||
{
|
||||
Assert.Equal(
|
||||
$"{TenantId}_WhiteGloveSealed",
|
||||
IndexRowKeys.BuildSessionsByTerminalPk(TenantId, "WhiteGloveSealed"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SessionsByTerminal_rk_is_yyyyMMddHHmmss_underscore_sessionId()
|
||||
{
|
||||
Assert.Equal(
|
||||
$"20260421140733_{SessionId}",
|
||||
IndexRowKeys.BuildSessionsByTerminalRk(Occurred, SessionId));
|
||||
}
|
||||
|
||||
// ============================================================ SessionsByStage
|
||||
|
||||
[Fact]
|
||||
public void SessionsByStage_pk_is_tenant_underscore_stage()
|
||||
{
|
||||
Assert.Equal(
|
||||
$"{TenantId}_EspInProgress",
|
||||
IndexRowKeys.BuildSessionsByStagePk(TenantId, "EspInProgress"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SessionsByStage_rk_pads_ticks_to_19_digits_for_lex_ordering()
|
||||
{
|
||||
var rk = IndexRowKeys.BuildSessionsByStageRk(Occurred, SessionId);
|
||||
|
||||
// 19-digit zero-padding is the contract — string comparison then matches numeric time order.
|
||||
var parts = rk.Split('_');
|
||||
Assert.Equal(19, parts[0].Length);
|
||||
Assert.Equal(Occurred.Ticks.ToString("D19"), parts[0]);
|
||||
Assert.Equal(SessionId, parts[1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SessionsByStage_rk_orders_lexicographically_matching_chronology()
|
||||
{
|
||||
var earlier = IndexRowKeys.BuildSessionsByStageRk(Occurred, SessionId);
|
||||
var later = IndexRowKeys.BuildSessionsByStageRk(Occurred.AddSeconds(1), SessionId);
|
||||
|
||||
Assert.True(string.CompareOrdinal(earlier, later) < 0);
|
||||
}
|
||||
|
||||
// ============================================================ DeadEndsByReason
|
||||
|
||||
[Fact]
|
||||
public void DeadEndsByReason_pk_is_tenant_underscore_reason()
|
||||
{
|
||||
Assert.Equal(
|
||||
$"{TenantId}_hybrid_reboot_gate_blocking",
|
||||
IndexRowKeys.BuildDeadEndsByReasonPk(TenantId, "hybrid_reboot_gate_blocking"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeadEndsByReason_rk_combines_timestamp_session_stepIndex_padded_to_6()
|
||||
{
|
||||
Assert.Equal(
|
||||
$"20260421140733_{SessionId}_000042",
|
||||
IndexRowKeys.BuildDeadEndsByReasonRk(Occurred, SessionId, 42));
|
||||
}
|
||||
|
||||
// ============================================================ ClassifierVerdictsByIdLevel
|
||||
|
||||
[Fact]
|
||||
public void ClassifierVerdictsByIdLevel_pk_is_tenant_underscore_classifierId_underscore_level()
|
||||
{
|
||||
Assert.Equal(
|
||||
$"{TenantId}_whiteglove-sealing_Weak",
|
||||
IndexRowKeys.BuildClassifierVerdictsByIdLevelPk(TenantId, "whiteglove-sealing", "Weak"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClassifierVerdictsByIdLevel_rk_combines_timestamp_session_stepIndex_padded_to_6()
|
||||
{
|
||||
Assert.Equal(
|
||||
$"20260421140733_{SessionId}_000007",
|
||||
IndexRowKeys.BuildClassifierVerdictsByIdLevelRk(Occurred, SessionId, 7));
|
||||
}
|
||||
|
||||
// ============================================================ SignalsByKind
|
||||
|
||||
[Fact]
|
||||
public void SignalsByKind_pk_is_tenant_underscore_signalKind()
|
||||
{
|
||||
Assert.Equal(
|
||||
$"{TenantId}_EspTerminalFailure",
|
||||
IndexRowKeys.BuildSignalsByKindPk(TenantId, "EspTerminalFailure"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SignalsByKind_rk_combines_timestamp_session_ordinal_padded_to_10()
|
||||
{
|
||||
Assert.Equal(
|
||||
$"20260421140733_{SessionId}_0000000123",
|
||||
IndexRowKeys.BuildSignalsByKindRk(Occurred, SessionId, 123));
|
||||
}
|
||||
|
||||
// ============================================================ UTC coercion + sanitizing
|
||||
|
||||
[Fact]
|
||||
public void Timestamp_always_normalizes_to_UTC()
|
||||
{
|
||||
// If a caller passes Local-kind DateTime, conversion must still produce the UTC wall clock.
|
||||
var localKind = DateTime.SpecifyKind(Occurred, DateTimeKind.Local);
|
||||
var rk = IndexRowKeys.BuildSessionsByTerminalRk(localKind, SessionId);
|
||||
|
||||
Assert.Equal($"{localKind.ToUniversalTime():yyyyMMddHHmmss}_{SessionId}", rk);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("foo/bar", "foo_bar")]
|
||||
[InlineData("foo\\bar", "foo_bar")]
|
||||
[InlineData("foo#bar", "foo_bar")]
|
||||
[InlineData("foo?bar", "foo_bar")]
|
||||
[InlineData("clean_name", "clean_name")]
|
||||
[InlineData("", "")]
|
||||
public void Sanitize_replaces_forbidden_key_chars_with_underscore(string input, string expected)
|
||||
{
|
||||
Assert.Equal(expected, IndexRowKeys.Sanitize(input));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sanitize_preserves_enum_style_identifiers_unchanged()
|
||||
{
|
||||
// Discriminators are overwhelmingly enum names — sanitize must not mangle them.
|
||||
Assert.Equal("WhiteGloveSealed", IndexRowKeys.Sanitize("WhiteGloveSealed"));
|
||||
Assert.Equal("EspTerminalFailure", IndexRowKeys.Sanitize("EspTerminalFailure"));
|
||||
Assert.Equal("hybrid_reboot_gate_blocking", IndexRowKeys.Sanitize("hybrid_reboot_gate_blocking"));
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user