diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core.Tests/Monitoring/Ime/DownloadProgressBudgetTests.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core.Tests/Monitoring/Ime/DownloadProgressBudgetTests.cs
new file mode 100644
index 000000000..21bfbf241
--- /dev/null
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core.Tests/Monitoring/Ime/DownloadProgressBudgetTests.cs
@@ -0,0 +1,68 @@
+using System.Collections.Generic;
+using System.IO;
+using AutopilotMonitor.Agent.V2.Core.Logging;
+using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
+using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
+using AutopilotMonitor.Shared.Logging;
+using AutopilotMonitor.Shared.Models;
+using Xunit;
+
+namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
+{
+ ///
+ /// D-444: the session's download_progress total and stage ride in the tracker state, so a restart
+ /// (or WhiteGlove Part 2) neither resets a throttled session to 3 s nor announces a stage twice.
+ ///
+ public sealed class DownloadProgressBudgetTests
+ {
+ [Fact]
+ public void Total_and_stage_survive_a_restart_with_the_tracker_state()
+ {
+ using var tmp = new TempDirectory();
+ var stateDir = Path.Combine(tmp.Path, "state");
+ var logger = new AgentLogger(Path.Combine(tmp.Path, "agent"), AgentLogLevel.Info);
+
+ using (var tracker = new ImeLogTracker(tmp.Path, new List(), logger, stateDirectory: stateDir))
+ {
+ for (var i = 0; i < 401; i++) tracker.DownloadProgressBudget.RecordEvent();
+ Assert.True(tracker.DownloadProgressBudget.TryAdvanceStage(1));
+ tracker.SaveStateForTest();
+ }
+
+ using var restarted = new ImeLogTracker(tmp.Path, new List(), logger, stateDirectory: stateDir);
+ restarted.LoadStateForTest();
+
+ Assert.Equal(401, restarted.DownloadProgressBudget.EventsSent);
+ Assert.Equal(1, restarted.DownloadProgressBudget.Stage);
+ Assert.False(restarted.DownloadProgressBudget.TryAdvanceStage(1));
+ }
+
+ [Fact]
+ public void A_missing_or_broken_persisted_budget_starts_at_zero()
+ {
+ var budget = new DownloadProgressBudget();
+ budget.Restore(null);
+ Assert.Equal(0, budget.EventsSent);
+
+ budget.Restore(new DownloadProgressBudgetState { EventsSent = -5, Stage = -1 });
+ Assert.Equal(0, budget.EventsSent);
+ Assert.Equal(0, budget.Stage);
+ }
+
+ [Fact]
+ public void Each_change_marks_the_state_dirty_once()
+ {
+ var budget = new DownloadProgressBudget();
+ Assert.False(budget.ConsumeDirty());
+
+ budget.RecordEvent();
+ Assert.True(budget.ConsumeDirty());
+ Assert.False(budget.ConsumeDirty());
+
+ Assert.False(budget.TryAdvanceStage(0));
+ Assert.False(budget.ConsumeDirty());
+ Assert.True(budget.TryAdvanceStage(2));
+ Assert.True(budget.ConsumeDirty());
+ }
+ }
+}
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core.Tests/Orchestration/SignalActivityClassifierTests.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core.Tests/Orchestration/SignalActivityClassifierTests.cs
index e35c7667c..7879e934f 100644
--- a/src/Agent/AutopilotMonitor.Agent.V2.Core.Tests/Orchestration/SignalActivityClassifierTests.cs
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core.Tests/Orchestration/SignalActivityClassifierTests.cs
@@ -43,6 +43,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
[InlineData("network_connectivity_check")]
// Bookkeeping of health-script runs that were deliberately not reported.
[InlineData("script_recurrence_summary")]
+ // Notice that download_progress is now sent less often (D-444).
+ [InlineData("download_progress_throttled")]
// Counted short-lived console processes — a spawning script is not enrollment progress.
[InlineData("console_script_activity")]
// Agent health / control / transport — not device/enrollment progress (P2).
@@ -68,10 +70,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
Assert.False(SignalActivityClassifier.IsRealActivity(DecisionSignalKind.InformationalEvent, payload));
}
- [Fact]
- public void Non_periodic_informational_event_is_activity()
+ [Theory]
+ [InlineData("esp_phase_changed")]
+ // Progress itself stays activity: a moving download must keep the stall clock at zero,
+ // also at the slowest throttle stage (60 s < first 2-minute probe, D-444).
+ [InlineData("download_progress")]
+ public void Non_periodic_informational_event_is_activity(string eventType)
{
- var payload = new Dictionary { [SignalPayloadKeys.EventType] = "esp_phase_changed" };
+ var payload = new Dictionary { [SignalPayloadKeys.EventType] = eventType };
Assert.True(SignalActivityClassifier.IsRealActivity(DecisionSignalKind.InformationalEvent, payload));
}
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core.Tests/SignalAdapters/DownloadProgressGateTests.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core.Tests/SignalAdapters/DownloadProgressGateTests.cs
new file mode 100644
index 000000000..1e2db6748
--- /dev/null
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core.Tests/SignalAdapters/DownloadProgressGateTests.cs
@@ -0,0 +1,213 @@
+#nullable enable
+using System;
+using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
+using AutopilotMonitor.Agent.V2.Core.SignalAdapters;
+using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
+using Xunit;
+
+namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
+{
+ ///
+ /// D-444: which download progress samples become download_progress events — one stream per
+ /// download, 3 s for almost every session, slower stages for long downloads, a live first minute
+ /// for every download.
+ ///
+ public sealed class DownloadProgressGateTests
+ {
+ private static readonly DateTime T0 = new DateTime(2026, 11, 18, 12, 0, 0, DateTimeKind.Utc);
+ private const string App = "app-1";
+ private const long Total = 1_000_000_000;
+
+ private static (DownloadProgressGate Gate, DownloadProgressBudget Budget, VirtualClock Clock) Make(int eventsSent = 0)
+ {
+ var budget = new DownloadProgressBudget();
+ if (eventsSent > 0)
+ budget.Restore(new DownloadProgressBudgetState { EventsSent = eventsSent, Stage = DownloadProgressGate.StageFor(eventsSent) });
+ var clock = new VirtualClock(T0);
+ return (new DownloadProgressGate(budget, clock), budget, clock);
+ }
+
+ private static DownloadProgressVerdict EmitIfAllowed(DownloadProgressGate gate, DownloadProgressSource source, long bytes, DateTime at)
+ {
+ var verdict = gate.Evaluate(App, source, bytes, Total, at);
+ if (verdict == DownloadProgressVerdict.Emit) gate.RecordEmitted(App, bytes, Total, at);
+ return verdict;
+ }
+
+ [Theory]
+ [InlineData(0, 0)]
+ [InlineData(399, 0)]
+ [InlineData(400, 1)]
+ [InlineData(639, 1)]
+ [InlineData(640, 2)]
+ [InlineData(759, 2)]
+ [InlineData(760, 3)]
+ [InlineData(100_000, 3)]
+ public void Stage_follows_the_session_total_at_its_thresholds(int eventsSent, int expectedStage)
+ {
+ Assert.Equal(expectedStage, DownloadProgressGate.StageFor(eventsSent));
+ }
+
+ [Fact]
+ public void No_interval_reaches_the_first_stall_probe()
+ {
+ // Progress counts as activity; a slower stage must not let the stall probe fire mid-download.
+ var firstProbe = TimeSpan.FromMinutes(new AutopilotMonitor.Shared.Models.CollectorConfiguration().StallProbeThresholdsMinutes[0]);
+ foreach (var (_, intervalSeconds) in DownloadProgressGate.Stages)
+ Assert.True(TimeSpan.FromSeconds(intervalSeconds) < firstProbe);
+ Assert.True(DownloadProgressGate.LiveStart < firstProbe);
+ }
+
+ [Fact]
+ public void Interval_is_3_10_30_60_seconds_and_clamped()
+ {
+ Assert.Equal(3, DownloadProgressGate.IntervalSecondsFor(-1));
+ Assert.Equal(3, DownloadProgressGate.IntervalSecondsFor(0));
+ Assert.Equal(10, DownloadProgressGate.IntervalSecondsFor(1));
+ Assert.Equal(30, DownloadProgressGate.IntervalSecondsFor(2));
+ Assert.Equal(60, DownloadProgressGate.IntervalSecondsFor(3));
+ Assert.Equal(60, DownloadProgressGate.IntervalSecondsFor(9));
+ }
+
+ [Fact]
+ public void Stage_0_sends_every_3_second_DO_sample_like_before()
+ {
+ var (gate, _, _) = Make();
+ for (var i = 0; i < 40; i++)
+ {
+ var verdict = EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, (i + 1) * 1_048_576L, T0.AddSeconds(i * 3));
+ Assert.Equal(DownloadProgressVerdict.Emit, verdict);
+ }
+ }
+
+ [Fact]
+ public void First_sample_is_sent_and_an_unchanged_repeat_never()
+ {
+ var (gate, _, _) = Make();
+ Assert.Equal(DownloadProgressVerdict.Emit, EmitIfAllowed(gate, DownloadProgressSource.Ime, 0, T0));
+ Assert.Equal(DownloadProgressVerdict.Drop, gate.Evaluate(App, DownloadProgressSource.Ime, 0, Total, T0.AddMinutes(5)));
+ }
+
+ [Fact]
+ public void A_sample_inside_the_interval_is_held()
+ {
+ var (gate, _, _) = Make();
+ EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 1_000, T0);
+ Assert.Equal(DownloadProgressVerdict.Hold, gate.Evaluate(App, DownloadProgressSource.DeliveryOptimization, 2_000, Total, T0.AddSeconds(1)));
+ Assert.Equal(DownloadProgressVerdict.Emit, gate.Evaluate(App, DownloadProgressSource.DeliveryOptimization, 3_000, Total, T0.AddSeconds(2.6)));
+ }
+
+ [Fact]
+ public void Completion_is_sent_even_inside_the_interval()
+ {
+ var (gate, _, _) = Make(eventsSent: 760);
+ EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 1_000, T0.AddMinutes(-10));
+ EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 2_000, T0);
+ Assert.Equal(DownloadProgressVerdict.Emit, gate.Evaluate(App, DownloadProgressSource.DeliveryOptimization, Total, Total, T0.AddSeconds(1)));
+ }
+
+ [Fact]
+ public void IME_lines_are_dropped_while_DO_reports_the_app()
+ {
+ var (gate, _, clock) = Make();
+ EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 1_000, clock.UtcNow);
+
+ clock.Advance(TimeSpan.FromSeconds(9));
+ Assert.Equal(DownloadProgressVerdict.Drop, gate.Evaluate(App, DownloadProgressSource.Ime, 5_000, Total, clock.UtcNow));
+ }
+
+ [Fact]
+ public void IME_lines_take_over_when_DO_goes_quiet()
+ {
+ var (gate, _, clock) = Make();
+ EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 1_000, clock.UtcNow);
+
+ clock.Advance(TimeSpan.FromSeconds(11));
+ Assert.Equal(DownloadProgressVerdict.Emit, gate.Evaluate(App, DownloadProgressSource.Ime, 5_000, Total, clock.UtcNow));
+ }
+
+ [Fact]
+ public void DO_preference_is_per_app()
+ {
+ var (gate, _, clock) = Make();
+ gate.Evaluate("app-a", DownloadProgressSource.DeliveryOptimization, 1_000, Total, clock.UtcNow);
+ Assert.Equal(DownloadProgressVerdict.Emit, gate.Evaluate("app-b", DownloadProgressSource.Ime, 1_000, Total, clock.UtcNow));
+ }
+
+ [Fact]
+ public void A_throttled_stage_applies_after_the_live_start()
+ {
+ var (gate, _, _) = Make(eventsSent: 400);
+ EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 1_000, T0); // first byte at T0
+ var t = T0.AddSeconds(61);
+ Assert.Equal(DownloadProgressVerdict.Emit, EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 2_000, t));
+ Assert.Equal(DownloadProgressVerdict.Hold, gate.Evaluate(App, DownloadProgressSource.DeliveryOptimization, 3_000, Total, t.AddSeconds(3)));
+ Assert.Equal(DownloadProgressVerdict.Emit, gate.Evaluate(App, DownloadProgressSource.DeliveryOptimization, 3_000, Total, t.AddSeconds(10)));
+ }
+
+ [Fact]
+ public void Every_download_reports_its_first_minute_every_3_seconds_even_in_the_slowest_stage()
+ {
+ var (gate, _, _) = Make(eventsSent: 760);
+ var sent = 0;
+ for (var i = 0; i <= 30; i++)
+ {
+ if (EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, (i + 1) * 1_000L, T0.AddSeconds(i * 3)) == DownloadProgressVerdict.Emit)
+ sent++;
+ }
+ // 0..57 s: every sample (20); 60..90 s: one per 60 s at most.
+ Assert.Equal(20, sent);
+ }
+
+ [Fact]
+ public void The_live_start_counts_from_the_first_byte_not_from_the_queued_0_percent_line()
+ {
+ var (gate, _, clock) = Make(eventsSent: 760);
+ EmitIfAllowed(gate, DownloadProgressSource.Ime, 0, T0); // queued, no byte yet
+ var firstByte = T0.AddSeconds(63);
+ clock.SetUtcNow(firstByte);
+ Assert.Equal(DownloadProgressVerdict.Emit, EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 3_000_000, firstByte));
+ Assert.Equal(DownloadProgressVerdict.Emit, EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 6_000_000, firstByte.AddSeconds(3)));
+ }
+
+ [Fact]
+ public void A_clock_step_backwards_does_not_mute_the_app()
+ {
+ var (gate, _, _) = Make(eventsSent: 760);
+ EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 1_000, T0.AddHours(7));
+ Assert.Equal(DownloadProgressVerdict.Emit, gate.Evaluate(App, DownloadProgressSource.DeliveryOptimization, 2_000, Total, T0));
+ }
+
+ [Fact]
+ public void Recording_returns_each_stage_once_when_the_session_crosses_it()
+ {
+ var (gate, budget, _) = Make(eventsSent: 398);
+ Assert.Null(gate.RecordSessionEvent()); // 399
+ Assert.Equal(1, gate.RecordSessionEvent()); // 400
+ Assert.Null(gate.RecordSessionEvent()); // 401
+ for (var i = 402; i < 640; i++) Assert.Null(gate.RecordSessionEvent());
+ Assert.Equal(2, gate.RecordSessionEvent()); // 640
+ Assert.Equal(640, budget.EventsSent);
+ }
+
+ [Fact]
+ public void A_restored_stage_is_not_announced_again()
+ {
+ var (gate, _, _) = Make(eventsSent: 700);
+ for (var i = 701; i < 760; i++) Assert.Null(gate.RecordSessionEvent());
+ Assert.Equal(3, gate.RecordSessionEvent()); // 760: next stage only
+ }
+
+ [Fact]
+ public void A_new_download_of_the_same_app_starts_fresh_after_EndDownload()
+ {
+ var (gate, _, _) = Make(eventsSent: 760);
+ EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 1_000, T0.AddMinutes(-30));
+ EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 5_000, T0);
+ gate.EndDownload(App);
+
+ Assert.Equal(DownloadProgressVerdict.Emit, EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 5_000, T0.AddSeconds(1)));
+ Assert.Equal(DownloadProgressVerdict.Emit, EmitIfAllowed(gate, DownloadProgressSource.DeliveryOptimization, 9_000, T0.AddSeconds(4)));
+ }
+ }
+}
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core.Tests/SignalAdapters/DownloadProgressPublisherTests.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core.Tests/SignalAdapters/DownloadProgressPublisherTests.cs
new file mode 100644
index 000000000..b828ea815
--- /dev/null
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core.Tests/SignalAdapters/DownloadProgressPublisherTests.cs
@@ -0,0 +1,302 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
+using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic;
+using AutopilotMonitor.Agent.V2.Core.Orchestration;
+using AutopilotMonitor.Agent.V2.Core.SignalAdapters;
+using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
+using AutopilotMonitor.Agent.V2.Core.Tests.Orchestration;
+using AutopilotMonitor.DecisionCore.Engine;
+using AutopilotMonitor.DecisionCore.Signals;
+using AutopilotMonitor.Shared.Models;
+using Xunit;
+using SharedEventTypes = AutopilotMonitor.Shared.Constants.EventTypes;
+
+namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
+{
+ ///
+ /// D-444: the one sender of download_progress — DO and IME samples in, one stream per download
+ /// out, held samples flushed at the download's end, one notice per slower stage.
+ ///
+ public sealed class DownloadProgressPublisherTests
+ {
+ private static readonly DateTime T0 = new DateTime(2026, 11, 18, 12, 0, 0, DateTimeKind.Utc);
+ private const long MiB = 1_048_576;
+
+ private sealed class Harness
+ {
+ public FakeSignalIngressSink Ingress { get; } = new FakeSignalIngressSink();
+ public VirtualClock Clock { get; } = new VirtualClock(T0);
+ public DownloadProgressBudget Budget { get; } = new DownloadProgressBudget();
+ public DownloadProgressPublisher Publisher { get; }
+
+ public Harness(int eventsSent = 0)
+ {
+ if (eventsSent > 0)
+ Budget.Restore(new DownloadProgressBudgetState { EventsSent = eventsSent, Stage = DownloadProgressGate.StageFor(eventsSent) });
+ Publisher = new DownloadProgressPublisher(new InformationalEventPost(Ingress, Clock), Clock, Budget);
+ }
+
+ public List Events(string eventType) =>
+ Ingress.Posted
+ .Where(p => p.Kind == DecisionSignalKind.InformationalEvent
+ && p.Payload != null
+ && p.Payload.TryGetValue(SignalPayloadKeys.EventType, out var t)
+ && t == eventType)
+ .ToList();
+
+ public List All() =>
+ Ingress.Posted.Where(p => p.Kind == DecisionSignalKind.InformationalEvent).ToList();
+ }
+
+ private static AppPackageState MakeApp(string id = "app-1", AppInstallationState state = AppInstallationState.Downloading,
+ long bytes = 0, long total = 0) =>
+ AppPackageState.Restore(
+ id: id, listPos: 0, name: "Contoso Tool",
+ runAs: AppRunAs.System, intent: AppIntent.Install, targeted: AppTargeted.Device,
+ dependsOn: new HashSet(),
+ installationState: state, downloadingOrInstallingSeen: true,
+ progressPercent: 0, bytesDownloaded: bytes, bytesTotal: total,
+ appType: "Win32");
+
+ private static DoProgressSample Do(long bytes, long total, int mode = 1, string? cacheHost = null) =>
+ new DoProgressSample(bytes, total, 0, bytes, 0, mode, 0, 0, 0, 0, 0, cacheHost);
+
+ private static IReadOnlyDictionary Typed(FakeSignalIngressSink.PostedSignal s) =>
+ Assert.IsAssignableFrom>(s.TypedPayload);
+
+ private static long BytesOf(FakeSignalIngressSink.PostedSignal s) =>
+ s.TypedPayload is IReadOnlyDictionary typed
+ ? Convert.ToInt64(typed["bytesDownloaded"])
+ : long.Parse(s.Payload!["bytesDownloaded"]);
+
+ [Fact]
+ public void A_DO_sample_becomes_one_event_with_the_DO_values_and_the_app_state()
+ {
+ var h = new Harness();
+ var app = MakeApp();
+
+ h.Publisher.OfferDoSample(app, Do(5 * MiB, 100 * MiB));
+
+ var ev = Assert.Single(h.Events(SharedEventTypes.DownloadProgress));
+ Assert.Equal("DeliveryOptimizationCollector", ev.Payload![SignalPayloadKeys.Source]);
+ Assert.Equal(EventSeverity.Debug.ToString(), ev.Payload[SignalPayloadKeys.Severity]);
+ Assert.Equal("true", ev.Payload[SignalPayloadKeys.ImmediateUpload]);
+ Assert.Equal("Contoso Tool: 5% (5242880/104857600) peers=0% mode=1", ev.Payload[SignalPayloadKeys.Message]);
+ Assert.Equal(T0, ev.OccurredAtUtc);
+
+ var data = Typed(ev);
+ Assert.Equal(5 * MiB, Convert.ToInt64(data["bytesDownloaded"]));
+ Assert.Equal(100 * MiB, Convert.ToInt64(data["bytesTotal"]));
+ Assert.Equal(1, Convert.ToInt32(data["doDownloadMode"]));
+ Assert.Equal("os_cmdlet", data["doSource"]);
+ Assert.Equal("Downloading", data["state"]);
+ Assert.Equal("Install", data["intent"]);
+ Assert.Equal("Device", data["targeted"]);
+ Assert.Equal("Win32", data["appType"]);
+ Assert.False(data.ContainsKey("doCacheHost"));
+ }
+
+ [Fact]
+ public void An_IME_line_is_dropped_while_DO_reports_and_takes_over_with_the_last_DO_values_when_DO_is_quiet()
+ {
+ var h = new Harness();
+ var app = MakeApp(total: 100 * MiB);
+ h.Publisher.OfferDoSample(app, Do(5 * MiB, 100 * MiB, cacheHost: "http://10.0.0.5/"));
+
+ h.Clock.Advance(TimeSpan.FromSeconds(5));
+ app.UpdateState(AppInstallationState.Downloading, 6, bytesDownloaded: 6 * MiB, bytesTotal: 100 * MiB);
+ h.Publisher.OfferImeSample(app, ImePayload(app), "Contoso Tool: 6%", h.Clock.UtcNow);
+ Assert.Single(h.Events(SharedEventTypes.DownloadProgress));
+
+ h.Clock.Advance(TimeSpan.FromSeconds(11));
+ app.UpdateState(AppInstallationState.Downloading, 9, bytesDownloaded: 9 * MiB, bytesTotal: 100 * MiB);
+ h.Publisher.OfferImeSample(app, ImePayload(app), "Contoso Tool: 9%", h.Clock.UtcNow);
+
+ var ime = h.Events(SharedEventTypes.DownloadProgress).Last();
+ Assert.Equal("ImeLogTracker", ime.Payload![SignalPayloadKeys.Source]);
+ Assert.Equal((9 * MiB).ToString(), ime.Payload["bytesDownloaded"]);
+ Assert.Equal("1", ime.Payload["doDownloadMode"]);
+ Assert.Equal("http://10.0.0.5/", ime.Payload["doCacheHost"]);
+ }
+
+ [Fact]
+ public void A_sample_held_by_the_interval_is_sent_when_the_download_ends()
+ {
+ var h = new Harness(eventsSent: 760);
+ var app = MakeApp();
+ h.Publisher.OfferDoSample(app, Do(1 * MiB, 100 * MiB));
+ h.Clock.Advance(TimeSpan.FromSeconds(61));
+ h.Publisher.OfferDoSample(app, Do(2 * MiB, 100 * MiB));
+ h.Clock.Advance(TimeSpan.FromSeconds(3));
+ h.Publisher.OfferDoSample(app, Do(3 * MiB, 100 * MiB));
+ Assert.Equal(2, h.Events(SharedEventTypes.DownloadProgress).Count);
+
+ h.Publisher.EndDownload(app.Id);
+
+ var sent = h.Events(SharedEventTypes.DownloadProgress);
+ Assert.Equal(3, sent.Count);
+ Assert.Equal(3 * MiB, BytesOf(sent.Last()));
+ }
+
+ [Fact]
+ public void Held_samples_are_sent_when_the_DO_collector_goes_idle()
+ {
+ var h = new Harness(eventsSent: 760);
+ var a = MakeApp("app-a");
+ var b = MakeApp("app-b");
+ foreach (var app in new[] { a, b })
+ {
+ h.Publisher.OfferDoSample(app, Do(1 * MiB, 100 * MiB));
+ }
+ h.Clock.Advance(TimeSpan.FromSeconds(61));
+ foreach (var app in new[] { a, b })
+ {
+ h.Publisher.OfferDoSample(app, Do(2 * MiB, 100 * MiB));
+ }
+ h.Clock.Advance(TimeSpan.FromSeconds(3));
+ foreach (var app in new[] { a, b })
+ {
+ h.Publisher.OfferDoSample(app, Do(3 * MiB, 100 * MiB));
+ }
+ Assert.Equal(4, h.Events(SharedEventTypes.DownloadProgress).Count);
+
+ h.Publisher.FlushPending();
+ h.Publisher.FlushPending(); // idempotent
+
+ Assert.Equal(6, h.Events(SharedEventTypes.DownloadProgress).Count);
+ }
+
+ [Fact]
+ public void Crossing_a_stage_sends_one_throttled_notice_after_the_event_that_crossed_it()
+ {
+ var h = new Harness(eventsSent: 399);
+ var app = MakeApp();
+
+ h.Publisher.OfferDoSample(app, Do(1 * MiB, 100 * MiB));
+ h.Clock.Advance(TimeSpan.FromSeconds(3));
+ h.Publisher.OfferDoSample(app, Do(2 * MiB, 100 * MiB));
+
+ var all = h.All();
+ Assert.Equal(SharedEventTypes.DownloadProgress, all[0].Payload![SignalPayloadKeys.EventType]);
+ var notice = Assert.Single(h.Events(SharedEventTypes.DownloadProgressThrottled));
+ Assert.Same(all[1], notice);
+ Assert.Equal("DownloadProgressPublisher", notice.Payload![SignalPayloadKeys.Source]);
+ Assert.Equal(EventSeverity.Info.ToString(), notice.Payload[SignalPayloadKeys.Severity]);
+ Assert.Equal("true", notice.Payload[SignalPayloadKeys.ImmediateUpload]);
+ Assert.Equal("1", notice.Payload["stage"]);
+ Assert.Equal("10", notice.Payload["intervalSeconds"]);
+ Assert.Equal("400", notice.Payload["progressEventsSent"]);
+ Assert.Equal("400", notice.Payload["stageThreshold"]);
+ Assert.Equal("60", notice.Payload["liveStartSeconds"]);
+ Assert.Equal(401, h.Budget.EventsSent);
+ }
+
+ [Fact]
+ public void The_terminal_tick_is_always_sent_and_counts_toward_the_session()
+ {
+ var h = new Harness(eventsSent: 759);
+ var app = MakeApp(state: AppInstallationState.Installed, bytes: 100, total: 100);
+ var payload = ImePayload(app).ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.Ordinal);
+ payload["status"] = "completed";
+
+ h.Publisher.EmitTerminalTick(app, payload, "Contoso Tool: completed", T0);
+
+ var tick = Assert.Single(h.Events(SharedEventTypes.DownloadProgress));
+ Assert.Equal("completed", tick.Payload!["status"]);
+ Assert.Equal("ImeLogTracker", tick.Payload[SignalPayloadKeys.Source]);
+ Assert.Equal("3", Assert.Single(h.Events(SharedEventTypes.DownloadProgressThrottled)).Payload!["stage"]);
+ Assert.Equal(760, h.Budget.EventsSent);
+ }
+
+ [Fact]
+ public void A_synthetic_hour_long_download_stays_far_below_the_event_limit()
+ {
+ // 1,100 MiB at about 350 KB/s: DO every 3 s (1 MiB steps) and the IME line every 5 s,
+ // like the field session that hit the limit. Today: one event per DO poll plus one per
+ // IME line (about 1,760).
+ var h = new Harness();
+ var app = MakeApp(total: 1_100 * MiB);
+ var start = h.Clock.UtcNow;
+ for (var second = 0; second <= 3_300; second++)
+ {
+ h.Clock.SetUtcNow(start.AddSeconds(second));
+ if (second % 3 == 0)
+ {
+ var bytes = Math.Min(1_100 * MiB, (second / 3 + 1) * MiB);
+ h.Publisher.OfferDoSample(app, Do(bytes, 1_100 * MiB));
+ }
+ if (second % 5 == 0)
+ {
+ var bytes = Math.Min(1_100 * MiB, (second / 3) * MiB);
+ app.UpdateState(AppInstallationState.Downloading, (int)(bytes * 100 / (1_100 * MiB)), bytesDownloaded: bytes, bytesTotal: 1_100 * MiB);
+ h.Publisher.OfferImeSample(app, ImePayload(app), "Contoso Tool", h.Clock.UtcNow);
+ }
+ }
+
+ var sent = h.Events(SharedEventTypes.DownloadProgress);
+ Assert.DoesNotContain(sent, e => e.Payload![SignalPayloadKeys.Source] == "ImeLogTracker");
+ Assert.InRange(sent.Count, 450, 700);
+ Assert.Equal(1_100 * MiB, BytesOf(sent.Last())); // completion always sent
+
+ var notice = Assert.Single(h.Events(SharedEventTypes.DownloadProgressThrottled));
+ Assert.Equal("1", notice.Payload!["stage"]);
+ var noticeIndex = h.All().IndexOf(notice);
+ Assert.Equal(400, h.All().Take(noticeIndex).Count(e => e.Payload![SignalPayloadKeys.EventType] == SharedEventTypes.DownloadProgress));
+
+ // After the notice: at least 9.5 s between two progress events, except the completion.
+ var afterNotice = h.All().Skip(noticeIndex + 1).ToList();
+ for (var i = 1; i < afterNotice.Count - 1; i++)
+ Assert.True((afterNotice[i].OccurredAtUtc - afterNotice[i - 1].OccurredAtUtc) >= TimeSpan.FromSeconds(9.5));
+ }
+
+ [Fact]
+ public void Adapter_sends_the_held_progress_before_the_app_leaves_Downloading()
+ {
+ using var f = new ImeLogTrackerAdapterFixture(T0);
+ f.Tracker.DownloadProgressBudget.Restore(new DownloadProgressBudgetState { EventsSent = 760, Stage = 3 });
+ using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
+ var app = MakeApp(total: 100 * MiB);
+
+ adapter.TriggerAppStateFromTest(app, AppInstallationState.Unknown, AppInstallationState.Downloading);
+ f.Clock.Advance(TimeSpan.FromSeconds(1));
+ app.UpdateState(AppInstallationState.Downloading, 1, bytesDownloaded: 1 * MiB, bytesTotal: 100 * MiB);
+ adapter.TriggerAppStateFromTest(app, AppInstallationState.Downloading, AppInstallationState.Downloading);
+ f.Clock.Advance(TimeSpan.FromSeconds(61));
+ app.UpdateState(AppInstallationState.Downloading, 2, bytesDownloaded: 2 * MiB, bytesTotal: 100 * MiB);
+ adapter.TriggerAppStateFromTest(app, AppInstallationState.Downloading, AppInstallationState.Downloading);
+ f.Clock.Advance(TimeSpan.FromSeconds(3));
+ app.UpdateState(AppInstallationState.Downloading, 3, bytesDownloaded: 3 * MiB, bytesTotal: 100 * MiB);
+ adapter.TriggerAppStateFromTest(app, AppInstallationState.Downloading, AppInstallationState.Downloading); // held
+ f.Clock.Advance(TimeSpan.FromSeconds(2));
+ app.UpdateState(AppInstallationState.Installing);
+ adapter.TriggerAppStateFromTest(app, AppInstallationState.Downloading, AppInstallationState.Installing);
+
+ var types = f.AllInfoEvents()
+ .Select(e => e.Payload![SignalPayloadKeys.EventType])
+ .Where(t => t == SharedEventTypes.DownloadProgress || t == SharedEventTypes.AppDownloadStarted || t == SharedEventTypes.AppInstallStart)
+ .ToList();
+ Assert.Equal(new[]
+ {
+ SharedEventTypes.AppDownloadStarted,
+ SharedEventTypes.DownloadProgress,
+ SharedEventTypes.DownloadProgress,
+ SharedEventTypes.DownloadProgress, // the held 3 MiB line, flushed first
+ SharedEventTypes.AppInstallStart,
+ }, types);
+ Assert.Equal((3 * MiB).ToString(), f.InfoEvents(SharedEventTypes.DownloadProgress).Last().Payload!["bytesDownloaded"]);
+ }
+
+ private static IReadOnlyDictionary ImePayload(AppPackageState app) =>
+ new Dictionary(StringComparer.Ordinal)
+ {
+ ["appId"] = app.Id,
+ ["appName"] = app.Name ?? string.Empty,
+ ["state"] = app.InstallationState.ToString(),
+ ["bytesDownloaded"] = app.BytesDownloaded.ToString(),
+ ["bytesTotal"] = app.BytesTotal.ToString(),
+ };
+ }
+}
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Enrollment/Ime/DownloadProgressBudget.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Enrollment/Ime/DownloadProgressBudget.cs
new file mode 100644
index 000000000..a21f6a131
--- /dev/null
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Enrollment/Ime/DownloadProgressBudget.cs
@@ -0,0 +1,62 @@
+using System.Threading;
+
+namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
+{
+ ///
+ /// Session-wide count of emitted download_progress events and the throttle stage reached.
+ /// Owned by the tracker so it is saved with the tracker state: the event limit counts the whole
+ /// session, and one enrollment spans agent restarts and both WhiteGlove parts. Written by the
+ /// download-progress publisher from the DO poll thread and the tracker thread, read by the
+ /// tracker's state save — hence the lock.
+ ///
+ internal sealed class DownloadProgressBudget
+ {
+ private readonly object _lock = new object();
+ private int _eventsSent;
+ private int _stage;
+ private int _dirty;
+
+ public int EventsSent { get { lock (_lock) return _eventsSent; } }
+
+ public int Stage { get { lock (_lock) return _stage; } }
+
+ /// Counts one emitted event and returns the new session total.
+ public int RecordEvent()
+ {
+ int total;
+ lock (_lock) total = ++_eventsSent;
+ Interlocked.Exchange(ref _dirty, 1);
+ return total;
+ }
+
+ /// Raises the stage. False when is not above the current one.
+ public bool TryAdvanceStage(int stage)
+ {
+ lock (_lock)
+ {
+ if (stage <= _stage) return false;
+ _stage = stage;
+ }
+ Interlocked.Exchange(ref _dirty, 1);
+ return true;
+ }
+
+ /// True once per change since the last call; the tracker then saves its state.
+ public bool ConsumeDirty() => Interlocked.Exchange(ref _dirty, 0) == 1;
+
+ public void Restore(DownloadProgressBudgetState state)
+ {
+ if (state == null) return;
+ lock (_lock)
+ {
+ _eventsSent = state.EventsSent > 0 ? state.EventsSent : 0;
+ _stage = state.Stage > 0 ? state.Stage : 0;
+ }
+ }
+
+ public DownloadProgressBudgetState ToPersisted()
+ {
+ lock (_lock) return new DownloadProgressBudgetState { EventsSent = _eventsSent, Stage = _stage };
+ }
+ }
+}
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Enrollment/Ime/ImeLogTracker.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Enrollment/Ime/ImeLogTracker.cs
index 1aca4a82f..0db366354 100644
--- a/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Enrollment/Ime/ImeLogTracker.cs
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Enrollment/Ime/ImeLogTracker.cs
@@ -221,6 +221,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
// Collapses recurring health-script runs; persisted with the file positions.
private readonly RecurringScriptGate _recurringScripts = new RecurringScriptGate();
+ ///
+ /// Session count of emitted download_progress events and the throttle stage reached. The
+ /// download-progress publisher writes it; the tracker only persists it with its state.
+ ///
+ internal DownloadProgressBudget DownloadProgressBudget { get; } = new DownloadProgressBudget();
+
// Set for the duration of one pattern dispatch: the matched line is older than
// HistoricReplayThreshold, so the adapter drops whatever it produces.
private bool _currentLineIsHistoricReplay;
@@ -1044,7 +1050,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
try { FlushRecurringScripts(UtcNowProvider(), shuttingDown: true); }
catch (Exception ex) { _logger.Warning($"ImeLogTracker: shutdown recurring-script flush failed: {ex.Message}"); }
- // Final state save on shutdown
+ // Final state save on shutdown. The download-progress budget is written from the DO
+ // poll thread too, so a change after the last pass is picked up here.
+ if (DownloadProgressBudget.ConsumeDirty()) _stateDirty = true;
if (_stateDirty)
{
SaveState();
@@ -1083,6 +1091,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
// registry reconciliation waits for such a pass before it pairs an IME save with a run.
if (!token.IsCancellationRequested) ScriptRuns.NotePassCompleted(passStartedUtc);
if (ScriptRuns.ConsumeCountersChanged()) _stateDirty = true;
+ if (DownloadProgressBudget.ConsumeDirty()) _stateDirty = true;
var endMs = MonotonicMillisProvider();
if (endMs - startMs > _passMaxMs)
@@ -1233,6 +1242,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
}
_recurringScripts.Restore(state.RecurringScripts);
+ DownloadProgressBudget.Restore(state.DownloadProgress);
// Health counters + histogram: a restart (or WhiteGlove Part 2) must report the
// whole session, not only the lines seen since the last start. Null on state files
@@ -1313,6 +1323,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
ParkedPlatformScripts = _parkedPlatformScripts.ToList(),
ScriptTimeoutSuspectedPosted = _scriptTimeoutSuspectedPosted.ToList(),
RecurringScripts = _recurringScripts.ToPersisted(),
+ DownloadProgress = DownloadProgressBudget.ToPersisted(),
};
lock (_healthLock)
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Enrollment/Ime/ImeTrackerStatePersistence.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Enrollment/Ime/ImeTrackerStatePersistence.cs
index 382b6e9f3..d353e051c 100644
--- a/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Enrollment/Ime/ImeTrackerStatePersistence.cs
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Enrollment/Ime/ImeTrackerStatePersistence.cs
@@ -167,6 +167,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
// one-shot degraded event must not fire twice. Null on older state files → zero.
public TrackerHealthData Health { get; set; }
public Dictionary PatternHits { get; set; }
+
+ // Session total of emitted download_progress events and the throttle stage reached. Restart-
+ // and WhiteGlove-safe on purpose: the event limit counts the whole session, and a restart must
+ // not reset a throttled session to the 3 s interval. Null on older state files → zero.
+ public DownloadProgressBudgetState DownloadProgress { get; set; }
+ }
+
+ public class DownloadProgressBudgetState
+ {
+ public int EventsSent { get; set; }
+ public int Stage { get; set; }
}
public class TrackerHealthData
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Telemetry/Periodic/DeliveryOptimizationCollector.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Telemetry/Periodic/DeliveryOptimizationCollector.cs
index a9bf4b0ba..1bfb74ac6 100644
--- a/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Telemetry/Periodic/DeliveryOptimizationCollector.cs
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Telemetry/Periodic/DeliveryOptimizationCollector.cs
@@ -22,8 +22,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic
///
/// Polls OS-level Delivery Optimization status via a persistent PowerShell Runspace.
/// Matches DO entries to tracked IME app downloads using the intunewin-bin FileId format.
- /// Emits download_progress events on every poll (for live UI) and do_telemetry once per app
- /// when the download completes.
+ /// Hands every changed byte count to the download-progress publisher, which sends the
+ /// download_progress events (D-444), and triggers do_telemetry once per app when the download
+ /// completes.
///
/// Lifecycle: starts dormant, wakes up when ImeLogTracker detects a download,
/// goes dormant again when all downloads are enriched.
@@ -35,6 +36,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic
private readonly Func _getPackageStates;
private readonly Action _onDoTelemetryReceived;
+ // Live progress goes through the publisher; it is told when the collector goes idle or
+ // stops, so a sample it held back is still sent.
+ private readonly Action _onDoProgressSample;
+ private readonly Action _onDownloadsIdle;
private readonly string _logFilePath;
// Office C2R DO support (Rev 3): the Office-CDN download is visible in DO long before the
@@ -101,11 +106,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic
Action onDoTelemetryReceived,
string logDirectory,
Action onOfficeDoSample = null,
- BandwidthStatePersistence bandwidthStatePersistence = null)
+ BandwidthStatePersistence bandwidthStatePersistence = null,
+ Action onDoProgressSample = null,
+ Action onDownloadsIdle = null)
: base(sessionId, tenantId, post, logger, intervalSeconds)
{
_getPackageStates = getPackageStates ?? throw new ArgumentNullException(nameof(getPackageStates));
_onDoTelemetryReceived = onDoTelemetryReceived;
+ _onDoProgressSample = onDoProgressSample;
+ _onDownloadsIdle = onDownloadsIdle;
_logFilePath = Path.Combine(logDirectory, LogFileName);
_onOfficeDoSample = onOfficeDoSample;
_pollIntervalSeconds = intervalSeconds;
@@ -136,6 +145,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic
protected override void OnAfterStop()
{
+ NotifyDownloadsIdle();
// Emit before the runspace teardown: the termination handler stops peripheral
// collectors BEFORE the diagnostics ZIP is built, so this one-shot still lands
// ahead of diagnostics_collecting in the timeline.
@@ -246,6 +256,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic
Logger.Debug("[DeliveryOptimizationCollector] Going dormant — no active downloads, pending enrichment or Office install");
_dormant = true;
PauseTimer();
+ NotifyDownloadsIdle();
// Natural persistence point: all downloads are done — which is exactly when an
// app-forced reboot becomes possible. Saves the accumulated samples so a reboot
// before the interim/final emission does not discard them (reboot survivor).
@@ -471,7 +482,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic
continue;
}
- // --- Live download_progress (every poll where bytes changed) ---
+ // --- Live progress (every poll where bytes changed) → the publisher decides ---
long lastBytes;
_lastBytesPerApp.TryGetValue(appId, out lastBytes);
@@ -480,24 +491,21 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic
_lastBytesPerApp[appId] = totalBytes;
progressCount++;
- int percentComplete = fileSize > 0 ? (int)((totalBytes * 100) / fileSize) : 0;
-
- Post.Emit(new EnrollmentEvent
+ if (_onDoProgressSample != null)
{
- SessionId = SessionId,
- TenantId = TenantId,
- EventType = Constants.EventTypes.DownloadProgress,
- Severity = EventSeverity.Debug,
- Source = "DeliveryOptimizationCollector",
- Phase = EnrollmentPhase.Unknown,
- Message = $"{pkg.Name ?? appId}: {percentComplete}% ({totalBytes}/{fileSize}) peers={peerCachingPct}% mode={downloadMode}",
- Data = BuildDoEventData(
- appId, pkg.Name, totalBytes, fileSize, percentComplete,
- bytesFromPeers, bytesFromHttp, peerCachingPct, downloadMode,
- bytesLanPeers, bytesGroupPeers, bytesInternetPeers, bytesLinkLocalPeers,
- bytesFromCacheServer, cacheHost),
- ImmediateUpload = true
- });
+ try
+ {
+ _onDoProgressSample(pkg, new DoProgressSample(
+ totalBytes, fileSize,
+ bytesFromPeers, bytesFromHttp, peerCachingPct, downloadMode,
+ bytesLanPeers, bytesGroupPeers, bytesInternetPeers,
+ bytesLinkLocalPeers, bytesFromCacheServer, cacheHost));
+ }
+ catch (Exception ex)
+ {
+ Logger.Warning($"[DeliveryOptimizationCollector] onDoProgressSample threw: {ex.Message}");
+ }
+ }
}
// --- Final DO telemetry (once per app when download is complete) ---
@@ -520,7 +528,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic
$"size={fileSize}, peers={bytesFromPeers} ({peerCachingPct}%), " +
$"http={bytesFromHttp}, mode={downloadMode}, duration={durationStr}");
- // Fire callback → EnrollmentTracker emits do_telemetry + download_progress events
+ // Fire callback → the IME adapter emits do_telemetry
_onDoTelemetryReceived?.Invoke(pkg);
}
}
@@ -792,43 +800,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic
return string.IsNullOrWhiteSpace(s) ? null : s;
}
- // Builds the Data dictionary for download_progress events. Centralised so the
- // download_progress (in-flight) and (potentially future) periodic-snapshot emissions
- // stay symmetric on the breakdown / cache fields the UI now consumes.
- private static Dictionary BuildDoEventData(
- string appId, string appName, long totalBytes, long fileSize, int percentComplete,
- long bytesFromPeers, long bytesFromHttp, int peerCachingPct, int downloadMode,
- long bytesLanPeers, long bytesGroupPeers, long bytesInternetPeers, long bytesLinkLocalPeers,
- long bytesFromCacheServer, string cacheHost)
+ // Tells the publisher that no DO sample follows for now (dormant or stopped), so it sends
+ // the samples it held back. Fail-soft like the other callbacks.
+ private void NotifyDownloadsIdle()
{
- var data = new Dictionary
- {
- ["appId"] = appId,
- ["appName"] = appName,
- // UI-compatible fields (DownloadProgress.tsx reads these)
- ["bytesDownloaded"] = totalBytes,
- ["bytesTotal"] = fileSize,
- ["progressPercent"] = percentComplete,
- // DO-specific fields
- ["doFileSize"] = fileSize,
- ["doTotalBytesDownloaded"] = totalBytes,
- ["doPercentComplete"] = percentComplete,
- ["doBytesFromPeers"] = bytesFromPeers,
- ["doBytesFromHttp"] = bytesFromHttp,
- ["doPercentPeerCaching"] = peerCachingPct,
- ["doDownloadMode"] = downloadMode,
- // Per-source breakdown — the customer-visible bug was these being absent on
- // download_progress while present on do_telemetry, leaving the UI at 0/0/0 mid-flight.
- ["doBytesFromLanPeers"] = bytesLanPeers,
- ["doBytesFromGroupPeers"] = bytesGroupPeers,
- ["doBytesFromInternetPeers"] = bytesInternetPeers,
- ["doBytesFromLinkLocalPeers"] = bytesLinkLocalPeers,
- ["doBytesFromCacheServer"] = bytesFromCacheServer,
- ["doSource"] = "os_cmdlet"
- };
- if (!string.IsNullOrEmpty(cacheHost))
- data["doCacheHost"] = cacheHost;
- return data;
+ if (_onDownloadsIdle == null) return;
+ try { _onDownloadsIdle(); }
+ catch (Exception ex) { Logger.Warning($"[DeliveryOptimizationCollector] onDownloadsIdle threw: {ex.Message}"); }
}
// -----------------------------------------------------------------------
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Telemetry/Periodic/DoProgressSample.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Telemetry/Periodic/DoProgressSample.cs
new file mode 100644
index 000000000..fa93cad4e
--- /dev/null
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core/Monitoring/Telemetry/Periodic/DoProgressSample.cs
@@ -0,0 +1,47 @@
+namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic
+{
+ ///
+ /// One Delivery Optimization poll result for a tracked app whose bytes changed. The collector
+ /// hands it to the download-progress publisher, which decides whether it becomes a
+ /// download_progress event.
+ ///
+ public sealed class DoProgressSample
+ {
+ public DoProgressSample(
+ long totalBytes, long fileSize,
+ long bytesFromPeers, long bytesFromHttp, int percentPeerCaching, int downloadMode,
+ long bytesFromLanPeers, long bytesFromGroupPeers, long bytesFromInternetPeers,
+ long bytesFromLinkLocalPeers, long bytesFromCacheServer, string cacheHost)
+ {
+ TotalBytes = totalBytes;
+ FileSize = fileSize;
+ BytesFromPeers = bytesFromPeers;
+ BytesFromHttp = bytesFromHttp;
+ PercentPeerCaching = percentPeerCaching;
+ DownloadMode = downloadMode;
+ BytesFromLanPeers = bytesFromLanPeers;
+ BytesFromGroupPeers = bytesFromGroupPeers;
+ BytesFromInternetPeers = bytesFromInternetPeers;
+ BytesFromLinkLocalPeers = bytesFromLinkLocalPeers;
+ BytesFromCacheServer = bytesFromCacheServer;
+ CacheHost = cacheHost;
+ }
+
+ public long TotalBytes { get; }
+ public long FileSize { get; }
+ public long BytesFromPeers { get; }
+ public long BytesFromHttp { get; }
+ public int PercentPeerCaching { get; }
+ public int DownloadMode { get; }
+ public long BytesFromLanPeers { get; }
+ public long BytesFromGroupPeers { get; }
+ public long BytesFromInternetPeers { get; }
+ public long BytesFromLinkLocalPeers { get; }
+ public long BytesFromCacheServer { get; }
+
+ /// CacheHost of the Connected Cache node; null when no cache served bytes.
+ public string CacheHost { get; }
+
+ public int PercentComplete => FileSize > 0 ? (int)((TotalBytes * 100) / FileSize) : 0;
+ }
+}
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core/Orchestration/Hosts/DeliveryOptimizationHost.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core/Orchestration/Hosts/DeliveryOptimizationHost.cs
index b4a6e94c5..ffc2db053 100644
--- a/src/Agent/AutopilotMonitor.Agent.V2.Core/Orchestration/Hosts/DeliveryOptimizationHost.cs
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core/Orchestration/Hosts/DeliveryOptimizationHost.cs
@@ -60,7 +60,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
onOfficeDoSample: officeHost != null ? officeHost.SubmitDoSample : (Action?)null,
bandwidthStatePersistence: stateDirectory != null
? new BandwidthStatePersistence(stateDirectory, logger)
- : null);
+ : null,
+ // Live progress: the IME adapter's publisher is the one sender of download_progress
+ // (one stream per download, interval per session stage — D-444).
+ onDoProgressSample: (pkg, sample) => imeHost.DownloadProgress.OfferDoSample(pkg, sample),
+ onDownloadsIdle: () => imeHost.DownloadProgress.FlushPending());
}
public void Start()
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core/Orchestration/Hosts/ImeLogHost.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core/Orchestration/Hosts/ImeLogHost.cs
index 43b70a458..842ab08e3 100644
--- a/src/Agent/AutopilotMonitor.Agent.V2.Core/Orchestration/Hosts/ImeLogHost.cs
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core/Orchestration/Hosts/ImeLogHost.cs
@@ -58,6 +58,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
///
internal ImeLogTracker Tracker => _tracker;
+ ///
+ /// The one sender of download_progress (owned by the adapter). Used by
+ /// DeliveryOptimizationHost to hand over the DO collector's samples.
+ ///
+ internal DownloadProgressPublisher DownloadProgress => _adapter.DownloadProgress;
+
///
/// Session caa6cf50 gate-starvation fix (2026-06-11) — bridge for the
/// EspAndHelloTracker user-ESP-apps-settled probe. True when the tracker's
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core/Orchestration/SignalActivityClassifier.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core/Orchestration/SignalActivityClassifier.cs
index dcf20a7db..6a34484f5 100644
--- a/src/Agent/AutopilotMonitor.Agent.V2.Core/Orchestration/SignalActivityClassifier.cs
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core/Orchestration/SignalActivityClassifier.cs
@@ -92,6 +92,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
SharedConstants.EventTypes.ImePatternHits,
// Bookkeeping of runs that were deliberately not reported as activity.
SharedConstants.EventTypes.ScriptRecurrenceSummary,
+ // Notice that download_progress is now sent less often — about the agent, not progress.
+ // The progress events themselves stay activity.
+ SharedConstants.EventTypes.DownloadProgressThrottled,
// A correction of an already reported script run from IME's saved result (D-316):
// registry observation after the fact, not progress.
SharedConstants.EventTypes.ScriptOutputReconciliation,
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core/SignalAdapters/DownloadProgressGate.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core/SignalAdapters/DownloadProgressGate.cs
new file mode 100644
index 000000000..0cb5658ac
--- /dev/null
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core/SignalAdapters/DownloadProgressGate.cs
@@ -0,0 +1,194 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
+using AutopilotMonitor.DecisionCore.Engine;
+
+namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
+{
+ internal enum DownloadProgressSource
+ {
+ DeliveryOptimization,
+ Ime,
+ }
+
+ internal enum DownloadProgressVerdict
+ {
+ /// Send the sample now.
+ Emit,
+ /// Too soon for this app's interval; keep it as the app's pending sample.
+ Hold,
+ /// Never send: nothing new, or the other source already reports this download.
+ Drop,
+ }
+
+ ///
+ /// Decides which download progress samples become download_progress events.
+ ///
+ /// - One stream per download: while the Delivery Optimization collector reports an app
+ /// (a sample within , agent clock), the IME log's progress
+ /// lines for it are dropped. DO has the finer byte count, the peer values and a fixed poll;
+ /// mixing both made the live speed in the portal jump.
+ /// - Always sent: the first sample of a download and its completion (bytes reach the total).
+ /// A repeat of the last sent byte count is never sent.
+ /// - Otherwise at most one event per app per interval. The interval follows the session's
+ /// emitted total (): 3 s as before for almost every session, then slower,
+ /// so long downloads cannot push the session over the event limit. Each download still
+ /// reports its first from its first byte every 3 s.
+ ///
+ /// Intervals compare event times (the IME line's time for IME samples), so replayed lines get the
+ /// same density as live ones. Not thread-safe: serializes
+ /// every call.
+ ///
+ internal sealed class DownloadProgressGate
+ {
+ ///
+ /// From this many emitted download_progress events in the session on, the interval per
+ /// app applies (D-444). Stage 0 must cover practically every session, so the live tracker stays
+ /// at 3 s; no interval may reach the agent's first 2-minute stall probe, because progress
+ /// counts as activity.
+ ///
+ internal static readonly IReadOnlyList<(int FromEventsSent, int IntervalSeconds)> Stages = new[]
+ {
+ (0, 3),
+ (400, 10),
+ (640, 30),
+ (760, 60),
+ };
+
+ /// How long each download reports every 3 s, counted from its first byte.
+ internal static readonly TimeSpan LiveStart = TimeSpan.FromSeconds(60);
+
+ /// IME progress lines are dropped while a DO sample for the app is younger than this.
+ internal static readonly TimeSpan DoPreferenceWindow = TimeSpan.FromSeconds(10);
+
+ // Samples arrive on a fixed poll (DO 3 s, IME ~5 s): a sample a few ms early still counts.
+ private static readonly TimeSpan IntervalTolerance = TimeSpan.FromMilliseconds(500);
+
+ private readonly DownloadProgressBudget _budget;
+ private readonly IClock _clock;
+ private readonly Dictionary _apps =
+ new Dictionary(StringComparer.OrdinalIgnoreCase);
+
+ public DownloadProgressGate(DownloadProgressBudget budget, IClock clock)
+ {
+ _budget = budget ?? throw new ArgumentNullException(nameof(budget));
+ _clock = clock ?? throw new ArgumentNullException(nameof(clock));
+ }
+
+ public static int StageFor(int eventsSent)
+ {
+ var stage = 0;
+ for (var i = 0; i < Stages.Count; i++)
+ {
+ if (eventsSent >= Stages[i].FromEventsSent) stage = i;
+ }
+ return stage;
+ }
+
+ public static int IntervalSecondsFor(int stage) =>
+ Stages[Math.Max(0, Math.Min(stage, Stages.Count - 1))].IntervalSeconds;
+
+ public DownloadProgressVerdict Evaluate(
+ string appId, DownloadProgressSource source, long bytes, long total, DateTime eventTimeUtc)
+ {
+ var app = GetOrAdd(appId);
+
+ var now = _clock.UtcNow;
+ if (source == DownloadProgressSource.DeliveryOptimization)
+ {
+ app.LastDoSampleAtUtc = now;
+ }
+ else if (app.LastDoSampleAtUtc.HasValue)
+ {
+ var sinceDo = now - app.LastDoSampleAtUtc.Value;
+ if (sinceDo >= TimeSpan.Zero && sinceDo < DoPreferenceWindow)
+ return DownloadProgressVerdict.Drop;
+ }
+
+ // The live start counts from the first byte, not the first sample: IME logs a 0 % line
+ // when the download is queued, up to a minute before any byte moves.
+ if (bytes > 0 && !app.FirstByteAtUtc.HasValue) app.FirstByteAtUtc = eventTimeUtc;
+
+ if (!app.LastEmittedAtUtc.HasValue) return DownloadProgressVerdict.Emit;
+ if (bytes == app.LastEmittedBytes && total == app.LastEmittedTotal) return DownloadProgressVerdict.Drop;
+ if (total > 0 && bytes >= total) return DownloadProgressVerdict.Emit;
+
+ var elapsed = eventTimeUtc - app.LastEmittedAtUtc.Value;
+ // A clock stepped backwards must not mute the app until the clock catches up again.
+ if (elapsed < TimeSpan.Zero) return DownloadProgressVerdict.Emit;
+
+ return elapsed >= CurrentInterval(app, eventTimeUtc) - IntervalTolerance
+ ? DownloadProgressVerdict.Emit
+ : DownloadProgressVerdict.Hold;
+ }
+
+ /// Records a sent progress event; returns the stage it moved the session into, or null.
+ public int? RecordEmitted(string appId, long bytes, long total, DateTime eventTimeUtc)
+ {
+ var app = GetOrAdd(appId);
+ app.LastEmittedAtUtc = eventTimeUtc;
+ app.LastEmittedBytes = bytes;
+ app.LastEmittedTotal = total;
+ return RecordSessionEvent();
+ }
+
+ ///
+ /// Counts a download_progress event sent without a decision (the terminal tick) toward
+ /// the session total; returns the stage it moved the session into, or null.
+ ///
+ public int? RecordSessionEvent()
+ {
+ var sent = _budget.RecordEvent();
+ var stage = StageFor(sent);
+ return _budget.TryAdvanceStage(stage) ? stage : (int?)null;
+ }
+
+ /// The app left Downloading: its next download starts fresh (first tick, live start).
+ public void EndDownload(string appId)
+ {
+ // The DO timestamp stays: a late IME line for the finished download is still the
+ // duplicate of what DO already reported.
+ if (_apps.TryGetValue(appId, out var app)) app.ResetDownload();
+ }
+
+ private TimeSpan CurrentInterval(AppProgress app, DateTime eventTimeUtc)
+ {
+ if (app.FirstByteAtUtc.HasValue)
+ {
+ var sinceFirstByte = eventTimeUtc - app.FirstByteAtUtc.Value;
+ if (sinceFirstByte >= TimeSpan.Zero && sinceFirstByte < LiveStart)
+ return TimeSpan.FromSeconds(Stages[0].IntervalSeconds);
+ }
+ return TimeSpan.FromSeconds(IntervalSecondsFor(StageFor(_budget.EventsSent)));
+ }
+
+ private AppProgress GetOrAdd(string appId)
+ {
+ if (!_apps.TryGetValue(appId, out var app))
+ {
+ app = new AppProgress();
+ _apps[appId] = app;
+ }
+ return app;
+ }
+
+ private sealed class AppProgress
+ {
+ public DateTime? LastEmittedAtUtc;
+ public long LastEmittedBytes = -1;
+ public long LastEmittedTotal = -1;
+ public DateTime? FirstByteAtUtc;
+ // Agent clock of the last DO sample (any verdict), not an event time.
+ public DateTime? LastDoSampleAtUtc;
+
+ public void ResetDownload()
+ {
+ LastEmittedAtUtc = null;
+ LastEmittedBytes = -1;
+ LastEmittedTotal = -1;
+ FirstByteAtUtc = null;
+ }
+ }
+ }
+}
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core/SignalAdapters/DownloadProgressPublisher.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core/SignalAdapters/DownloadProgressPublisher.cs
new file mode 100644
index 000000000..291c60d08
--- /dev/null
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core/SignalAdapters/DownloadProgressPublisher.cs
@@ -0,0 +1,285 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using AutopilotMonitor.Agent.V2.Core.Logging;
+using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
+using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic;
+using AutopilotMonitor.Agent.V2.Core.Orchestration;
+using AutopilotMonitor.DecisionCore.Engine;
+using AutopilotMonitor.Shared.Models;
+using SharedEventTypes = AutopilotMonitor.Shared.Constants.EventTypes;
+
+namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
+{
+ ///
+ /// The one sender of download_progress (D-444). The DO collector and the IME adapter hand
+ /// their samples here; decides what is sent.
+ ///
+ /// A sent event keeps the source label and timestamp of the sample whose byte count it carries:
+ /// "ImeLogTracker" events are stamped with the IME line's time (the backend's clock checks treat
+ /// that label as the log writer's clock), DO events with the agent clock. A DO event also carries
+ /// the app's IME state, an IME event the last DO values when there are any.
+ ///
+ ///
+ /// A sample held back by the interval stays pending and is sent when the download ends or the DO
+ /// collector goes idle, so the last byte count and DO breakdown always reach the backend. When the
+ /// session moves into a slower stage, one download_progress_throttled event says so.
+ /// Thread-safe: the DO poll thread and the IME tracker thread both call in.
+ ///
+ ///
+ internal sealed class DownloadProgressPublisher
+ {
+ internal const string SourceLabel = "DownloadProgressPublisher";
+ internal const string DoSourceLabel = "DeliveryOptimizationCollector";
+ internal const string ImeSourceLabel = "ImeLogTracker";
+
+ private readonly InformationalEventPost _post;
+ private readonly IClock _clock;
+ private readonly AgentLogger? _logger;
+ private readonly DownloadProgressBudget _budget;
+ private readonly DownloadProgressGate _gate;
+ private readonly object _lock = new object();
+ private readonly Dictionary _pending = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ private readonly Dictionary _lastDoSample =
+ new Dictionary(StringComparer.OrdinalIgnoreCase);
+
+ public DownloadProgressPublisher(
+ InformationalEventPost post, IClock clock, DownloadProgressBudget budget, AgentLogger? logger = null)
+ {
+ _post = post ?? throw new ArgumentNullException(nameof(post));
+ _clock = clock ?? throw new ArgumentNullException(nameof(clock));
+ _budget = budget ?? throw new ArgumentNullException(nameof(budget));
+ _logger = logger;
+ _gate = new DownloadProgressGate(budget, clock);
+ }
+
+ /// DO poll: the byte count of a tracked app changed.
+ public void OfferDoSample(AppPackageState app, DoProgressSample sample)
+ {
+ if (app == null || string.IsNullOrEmpty(app.Id) || sample == null) return;
+ lock (_lock)
+ {
+ _lastDoSample[app.Id] = sample;
+ var now = _clock.UtcNow;
+ var verdict = _gate.Evaluate(app.Id, DownloadProgressSource.DeliveryOptimization, sample.TotalBytes, sample.FileSize, now);
+ if (verdict == DownloadProgressVerdict.Drop) return;
+ Apply(verdict, BuildDoTick(app, sample, now));
+ }
+ }
+
+ /// IME log: a progress line for an app that stays in Downloading.
+ public void OfferImeSample(AppPackageState app, IReadOnlyDictionary imePayload, string message, DateTime occurredAtUtc)
+ {
+ if (app == null || string.IsNullOrEmpty(app.Id) || imePayload == null) return;
+ lock (_lock)
+ {
+ var verdict = _gate.Evaluate(app.Id, DownloadProgressSource.Ime, app.BytesDownloaded, app.BytesTotal, occurredAtUtc);
+ if (verdict == DownloadProgressVerdict.Drop) return;
+ Apply(verdict, BuildImeTick(app, imePayload, message, occurredAtUtc));
+ }
+ }
+
+ ///
+ /// The status=completed|failed tick that closes an app in the portal's download panel.
+ /// Always sent; it counts toward the session total.
+ ///
+ public void EmitTerminalTick(AppPackageState app, IReadOnlyDictionary payload, string message, DateTime occurredAtUtc)
+ {
+ if (app == null || string.IsNullOrEmpty(app.Id) || payload == null) return;
+ lock (_lock)
+ {
+ FlushPendingLocked(app.Id);
+ Send(new Tick(app.Id, app.BytesDownloaded, app.BytesTotal, occurredAtUtc, ImeSourceLabel, message,
+ stringData: payload, typedData: null));
+ AnnounceStage(_gate.RecordSessionEvent());
+ _gate.EndDownload(app.Id);
+ }
+ }
+
+ /// The app left Downloading: send its pending sample first, then start its next download fresh.
+ public void EndDownload(string appId)
+ {
+ if (string.IsNullOrEmpty(appId)) return;
+ lock (_lock)
+ {
+ FlushPendingLocked(appId);
+ _gate.EndDownload(appId);
+ }
+ }
+
+ /// The DO collector went idle or stopped: send every pending sample.
+ public void FlushPending()
+ {
+ lock (_lock)
+ {
+ if (_pending.Count == 0) return;
+ foreach (var appId in new List(_pending.Keys))
+ FlushPendingLocked(appId);
+ }
+ }
+
+ private void Apply(DownloadProgressVerdict verdict, Tick tick)
+ {
+ if (verdict == DownloadProgressVerdict.Hold)
+ {
+ _pending[tick.AppId] = tick;
+ return;
+ }
+ _pending.Remove(tick.AppId);
+ SendAndRecord(tick);
+ }
+
+ private void FlushPendingLocked(string appId)
+ {
+ if (!_pending.TryGetValue(appId, out var tick)) return;
+ _pending.Remove(appId);
+ SendAndRecord(tick);
+ }
+
+ private void SendAndRecord(Tick tick)
+ {
+ Send(tick);
+ AnnounceStage(_gate.RecordEmitted(tick.AppId, tick.Bytes, tick.Total, tick.OccurredAtUtc));
+ }
+
+ private void Send(Tick tick)
+ {
+ _post.Emit(
+ eventType: SharedEventTypes.DownloadProgress,
+ source: tick.Source,
+ message: tick.Message,
+ severity: EventSeverity.Debug,
+ // Drives the live download bar in the portal.
+ immediateUpload: true,
+ data: tick.StringData,
+ occurredAtUtc: tick.OccurredAtUtc,
+ typedPayload: tick.TypedData);
+ }
+
+ private void AnnounceStage(int? enteredStage)
+ {
+ if (!enteredStage.HasValue) return;
+
+ var culture = CultureInfo.InvariantCulture;
+ var stage = enteredStage.Value;
+ var interval = DownloadProgressGate.IntervalSecondsFor(stage);
+ var liveStart = (int)DownloadProgressGate.LiveStart.TotalSeconds;
+ var sent = _budget.EventsSent;
+ var data = new Dictionary(StringComparer.Ordinal)
+ {
+ ["stage"] = stage.ToString(culture),
+ ["intervalSeconds"] = interval.ToString(culture),
+ ["progressEventsSent"] = sent.ToString(culture),
+ ["stageThreshold"] = DownloadProgressGate.Stages[stage].FromEventsSent.ToString(culture),
+ ["liveStartSeconds"] = liveStart.ToString(culture),
+ };
+
+ _post.Emit(
+ eventType: SharedEventTypes.DownloadProgressThrottled,
+ source: SourceLabel,
+ message: $"Long downloads: download progress is now reported every {interval} s per app to protect against excessive events; each download still reports its first {liveStart} s live",
+ severity: EventSeverity.Info,
+ immediateUpload: true,
+ data: data,
+ occurredAtUtc: _clock.UtcNow);
+
+ _logger?.Info($"DownloadProgressPublisher: stage {stage} entered after {sent} download_progress events — interval now {interval} s per app (live start {liveStart} s)");
+ }
+
+ private static Tick BuildDoTick(AppPackageState app, DoProgressSample s, DateTime atUtc)
+ {
+ var percent = s.PercentComplete;
+ var data = new Dictionary(StringComparer.Ordinal)
+ {
+ ["appId"] = app.Id,
+ ["appName"] = app.Name,
+ // Fields the portal's download panel reads.
+ ["bytesDownloaded"] = s.TotalBytes,
+ ["bytesTotal"] = s.FileSize,
+ ["progressPercent"] = percent,
+ ["doFileSize"] = s.FileSize,
+ ["doTotalBytesDownloaded"] = s.TotalBytes,
+ ["doPercentComplete"] = percent,
+ ["doBytesFromPeers"] = s.BytesFromPeers,
+ ["doBytesFromHttp"] = s.BytesFromHttp,
+ ["doPercentPeerCaching"] = s.PercentPeerCaching,
+ ["doDownloadMode"] = s.DownloadMode,
+ ["doBytesFromLanPeers"] = s.BytesFromLanPeers,
+ ["doBytesFromGroupPeers"] = s.BytesFromGroupPeers,
+ ["doBytesFromInternetPeers"] = s.BytesFromInternetPeers,
+ ["doBytesFromLinkLocalPeers"] = s.BytesFromLinkLocalPeers,
+ ["doBytesFromCacheServer"] = s.BytesFromCacheServer,
+ ["doSource"] = "os_cmdlet",
+ // The app's IME state, so the event carries the whole picture.
+ ["state"] = app.InstallationState.ToString(),
+ ["intent"] = app.Intent.ToString(),
+ ["targeted"] = app.Targeted.ToString(),
+ ["runAs"] = app.RunAs.ToString(),
+ };
+ if (!string.IsNullOrEmpty(s.CacheHost)) data["doCacheHost"] = s.CacheHost;
+ if (!string.IsNullOrEmpty(app.AppType)) data["appType"] = app.AppType;
+ if (!string.IsNullOrEmpty(app.AppVersion)) data["appVersion"] = app.AppVersion;
+
+ var message = $"{app.Name ?? app.Id}: {percent}% ({s.TotalBytes}/{s.FileSize}) peers={s.PercentPeerCaching}% mode={s.DownloadMode}";
+ return new Tick(app.Id, s.TotalBytes, s.FileSize, atUtc, DoSourceLabel, message, stringData: null, typedData: data);
+ }
+
+ private Tick BuildImeTick(AppPackageState app, IReadOnlyDictionary imePayload, string message, DateTime atUtc)
+ {
+ var data = new Dictionary(imePayload.Count + 16, StringComparer.Ordinal);
+ foreach (var kv in imePayload) data[kv.Key] = kv.Value;
+
+ // Last DO values for the app (DO went quiet, the IME line took over): the breakdown stays
+ // visible. The byte count stays the IME line's.
+ if (_lastDoSample.TryGetValue(app.Id, out var s))
+ {
+ var culture = CultureInfo.InvariantCulture;
+ AddIfAbsent(data, "doFileSize", s.FileSize.ToString(culture));
+ AddIfAbsent(data, "doTotalBytesDownloaded", s.TotalBytes.ToString(culture));
+ AddIfAbsent(data, "doBytesFromPeers", s.BytesFromPeers.ToString(culture));
+ AddIfAbsent(data, "doBytesFromHttp", s.BytesFromHttp.ToString(culture));
+ AddIfAbsent(data, "doPercentPeerCaching", s.PercentPeerCaching.ToString(culture));
+ AddIfAbsent(data, "doDownloadMode", s.DownloadMode.ToString(culture));
+ AddIfAbsent(data, "doBytesFromLanPeers", s.BytesFromLanPeers.ToString(culture));
+ AddIfAbsent(data, "doBytesFromGroupPeers", s.BytesFromGroupPeers.ToString(culture));
+ AddIfAbsent(data, "doBytesFromInternetPeers", s.BytesFromInternetPeers.ToString(culture));
+ AddIfAbsent(data, "doBytesFromLinkLocalPeers", s.BytesFromLinkLocalPeers.ToString(culture));
+ AddIfAbsent(data, "doBytesFromCacheServer", s.BytesFromCacheServer.ToString(culture));
+ if (!string.IsNullOrEmpty(s.CacheHost)) AddIfAbsent(data, "doCacheHost", s.CacheHost!);
+ }
+
+ return new Tick(app.Id, app.BytesDownloaded, app.BytesTotal, atUtc, ImeSourceLabel, message, stringData: data, typedData: null);
+ }
+
+ private static void AddIfAbsent(Dictionary data, string key, string value)
+ {
+ if (!data.ContainsKey(key)) data[key] = value;
+ }
+
+ private sealed class Tick
+ {
+ public Tick(string appId, long bytes, long total, DateTime occurredAtUtc, string source, string message,
+ IReadOnlyDictionary? stringData, Dictionary? typedData)
+ {
+ AppId = appId;
+ Bytes = bytes;
+ Total = total;
+ OccurredAtUtc = occurredAtUtc;
+ Source = source;
+ Message = message;
+ StringData = stringData;
+ TypedData = typedData;
+ }
+
+ public string AppId { get; }
+ public long Bytes { get; }
+ public long Total { get; }
+ public DateTime OccurredAtUtc { get; }
+ public string Source { get; }
+ public string Message { get; }
+ public IReadOnlyDictionary? StringData { get; }
+ public Dictionary? TypedData { get; }
+ }
+ }
+}
diff --git a/src/Agent/AutopilotMonitor.Agent.V2.Core/SignalAdapters/ImeLogTrackerAdapter.cs b/src/Agent/AutopilotMonitor.Agent.V2.Core/SignalAdapters/ImeLogTrackerAdapter.cs
index 31c24410e..e28f0416e 100644
--- a/src/Agent/AutopilotMonitor.Agent.V2.Core/SignalAdapters/ImeLogTrackerAdapter.cs
+++ b/src/Agent/AutopilotMonitor.Agent.V2.Core/SignalAdapters/ImeLogTrackerAdapter.cs
@@ -68,6 +68,8 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
private readonly ISignalIngressSink _ingress;
private readonly IClock _clock;
private readonly InformationalEventPost _post;
+ // The one sender of download_progress; the DO collector feeds it through ImeLogHost.
+ private readonly DownloadProgressPublisher _downloadProgress;
private readonly HashSet _whiteGloveSealingPatternIds;
private readonly object _lock = new object();
// PR3-D4: optional logger so the largest signal adapter (777 LOC, 0 logger calls
@@ -185,6 +187,7 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_post = new InformationalEventPost(ingress, clock);
_logger = logger;
+ _downloadProgress = new DownloadProgressPublisher(_post, clock, tracker.DownloadProgressBudget, logger);
_whiteGloveSealingPatternIds = whiteGloveSealingPatternIds == null
? new HashSet(StringComparer.Ordinal)
@@ -856,18 +859,30 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
var (eventType, severity) = mapped.Value;
var payload = BuildAppStatePayload(app, newState, timing);
TagDerivedTimestamp(payload, derivedFromClock, rawSourceTs);
- // All app-state transitions flush immediately, including `download_progress`:
- // progress ticks run every 3s and only while a download is actively in flight
- // (bounded by download duration), so live UI responsiveness wins over the small
- // extra request volume.
- _post.Emit(
- eventType: eventType,
- source: SourceLabel,
- message: BuildAppStateMessage(app, newState, eventType),
- severity: severity,
- immediateUpload: true,
- data: payload,
- occurredAtUtc: now);
+ var message = BuildAppStateMessage(app, newState, eventType);
+
+ if (string.Equals(eventType, SharedEventTypes.DownloadProgress, StringComparison.Ordinal))
+ {
+ // A progress line: the publisher decides (one stream per download, interval per
+ // session stage — D-444).
+ _downloadProgress.OfferImeSample(app, payload, message, now);
+ }
+ else
+ {
+ // Leaving Downloading: the last held progress sample goes out before the state event.
+ if (oldState == AppInstallationState.Downloading && newState != AppInstallationState.Downloading)
+ _downloadProgress.EndDownload(app.Id);
+
+ // All app-state transitions flush immediately: the live panels show them within seconds.
+ _post.Emit(
+ eventType: eventType,
+ source: SourceLabel,
+ message: message,
+ severity: severity,
+ immediateUpload: true,
+ data: payload,
+ occurredAtUtc: now);
+ }
// V1 parity: on terminal Installed/Error transitions, also emit a shadow
// `download_progress` event tagged with status=completed/failed. The Web UI's
@@ -881,14 +896,7 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
var shadowPayload = new Dictionary(payload.Count + 1, StringComparer.Ordinal);
foreach (var kv in payload) shadowPayload[kv.Key] = kv.Value;
shadowPayload["status"] = status;
- _post.Emit(
- eventType: SharedEventTypes.DownloadProgress,
- source: SourceLabel,
- message: $"{app.Name ?? app.Id}: {status}",
- severity: EventSeverity.Debug,
- immediateUpload: true,
- data: shadowPayload,
- occurredAtUtc: now);
+ _downloadProgress.EmitTerminalTick(app, shadowPayload, $"{app.Name ?? app.Id}: {status}", now);
}
// Event-driven `app_tracking_summary` snapshot: emit a fresh aggregate after
@@ -963,6 +971,12 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
}
}
+ ///
+ /// The sender of every download_progress event. DeliveryOptimizationHost hands
+ /// the DO collector's samples to it.
+ ///
+ internal DownloadProgressPublisher DownloadProgress => _downloadProgress;
+
///
/// Snapshot of per-app install timings captured during this agent run. Fire-once
/// stamps, safe to read concurrently with adapter emissions.
diff --git a/src/Shared/AutopilotMonitor.Shared/Constants.cs b/src/Shared/AutopilotMonitor.Shared/Constants.cs
index acf734050..8a638acbb 100644
--- a/src/Shared/AutopilotMonitor.Shared/Constants.cs
+++ b/src/Shared/AutopilotMonitor.Shared/Constants.cs
@@ -660,6 +660,9 @@ namespace AutopilotMonitor.Shared
public const string LogEntry = "log_entry";
public const string EspStateChange = "esp_state_change";
public const string DownloadProgress = "download_progress";
+ // One per stage change: download_progress is now reported less often per app because the
+ // session's progress volume crossed a stage threshold (long downloads, event-limit guard).
+ public const string DownloadProgressThrottled = "download_progress_throttled";
public const string CertValidation = "cert_validation";
public const string EspUiState = "esp_ui_state";
public const string GatherResult = "gather_result";
diff --git a/src/Web/autopilot-monitor-web/lib/generated/shared-manifests.generated.ts b/src/Web/autopilot-monitor-web/lib/generated/shared-manifests.generated.ts
index d9c7b2eb6..2cbfffe00 100644
--- a/src/Web/autopilot-monitor-web/lib/generated/shared-manifests.generated.ts
+++ b/src/Web/autopilot-monitor-web/lib/generated/shared-manifests.generated.ts
@@ -1103,6 +1103,7 @@ export const SHARED_MANIFEST = {
"do_group_id_auto_set",
"do_telemetry",
"download_progress",
+ "download_progress_throttled",
"enrollment_complete",
"enrollment_failed",
"enrollment_summary_shown",
diff --git a/src/Web/autopilot-monitor-web/lib/generated/shared-manifests.json b/src/Web/autopilot-monitor-web/lib/generated/shared-manifests.json
index a60390894..3c9c352a3 100644
--- a/src/Web/autopilot-monitor-web/lib/generated/shared-manifests.json
+++ b/src/Web/autopilot-monitor-web/lib/generated/shared-manifests.json
@@ -1099,6 +1099,7 @@
"do_group_id_auto_set",
"do_telemetry",
"download_progress",
+ "download_progress_throttled",
"enrollment_complete",
"enrollment_failed",
"enrollment_summary_shown",