Files
ucvl-zonghengjia-open-source/windows/build/StartupLearningWarmupHarness.cs
T

210 lines
9.8 KiB
C#
Raw Normal View History

using System.Text.Json;
using UCVL.VPNPlus;
var checks = new Dictionary<string, bool>();
TaskCompletionSource Signal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
// The real coordinator receives controlled external setup/probe phases. The
// semaphore is the same boundary used by XrayManager to defer rule commits.
using (var epoch = new CancellationTokenSource())
using (var lifecycle = new SemaphoreSlim(1, 1))
{
var tunReady = Signal(); var nrptStarted = Signal(); var finishNrpt = Signal();
var proofFinished = false; var committed = false; var setupFinished = false;
var clock = new ManualClock();
var run = StartupLearningWarmup.RunAsync(async begin => {
await lifecycle.WaitAsync();
try
{
await tunReady.Task;
begin(epoch.Token);
nrptStarted.SetResult();
await finishNrpt.Task;
setupFinished = true;
}
finally { lifecycle.Release(); }
}, async token => {
proofFinished = true;
await lifecycle.WaitAsync(token);
try { token.ThrowIfCancellationRequested(); committed = setupFinished; }
finally { lifecycle.Release(); }
}, CancellationToken.None, clock);
checks["learning_does_not_start_before_tun_ipv4_ready"] = !proofFinished;
tunReady.SetResult(); await nrptStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
checks["readonly_proof_overlaps_pending_nrpt"] = proofFinished;
checks["rule_commit_waits_for_setup_lifecycle_release"] = !committed;
finishNrpt.SetResult(); await run.WaitAsync(TimeSpan.FromSeconds(3));
checks["completed_proof_commits_after_setup"] = committed;
}
{
var clock = new ManualClock(); var setupEntered = Signal(); var finishSetup = Signal();
var learningStarted = Signal(); var cancelled = false;
var run = StartupLearningWarmup.RunAsync(async begin => {
begin(CancellationToken.None); setupEntered.SetResult(); await finishSetup.Task;
}, async token => {
learningStarted.SetResult();
try { await Task.Delay(Timeout.Infinite, token); }
catch (OperationCanceledException) { cancelled = true; }
}, CancellationToken.None, clock);
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
clock.Advance(TimeSpan.FromMinutes(1));
checks["setup_does_not_consume_post_setup_learning_budget"] = !cancelled;
finishSetup.SetResult(); await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
await learningStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
clock.Advance(TimeSpan.FromMilliseconds(14_999));
checks["learning_retains_fifteen_seconds_after_setup"] = !cancelled && !run.IsCompleted;
clock.Advance(TimeSpan.FromMilliseconds(1));
await run.WaitAsync(TimeSpan.FromSeconds(3));
checks["learning_stops_at_post_setup_budget"] = cancelled;
}
{
var learningCalls = 0;
await StartupLearningWarmup.RunAsync(_ => Task.CompletedTask,
_ => { learningCalls++; return Task.CompletedTask; }, CancellationToken.None, new ManualClock());
checks["setup_without_smart_readiness_never_starts_learning"] = learningCalls == 0;
}
foreach (var reason in new[] { "setup_failure", "caller_cancel", "epoch_cancel" })
{
using var caller = new CancellationTokenSource(); using var epoch = new CancellationTokenSource();
var setupEntered = Signal(); var finishSetup = Signal(); var stopped = false; var active = false;
var failure = new IOException("synthetic setup failure"); Exception? observed = null;
var run = StartupLearningWarmup.RunAsync(async begin => {
begin(epoch.Token); setupEntered.SetResult();
await finishSetup.Task.WaitAsync(caller.Token);
if (reason == "setup_failure") throw failure;
}, async token => {
active = true;
try { await Task.Delay(Timeout.Infinite, token); }
finally { active = false; stopped = true; }
}, caller.Token, new ManualClock());
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
if (reason == "caller_cancel") caller.Cancel();
if (reason == "epoch_cancel") epoch.Cancel();
finishSetup.TrySetResult();
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (Exception error) { observed = error; }
checks[reason + "_drains_learning_without_late_work"] = stopped && !active;
checks[reason + "_preserves_original_failure"] = reason == "setup_failure"
? ReferenceEquals(observed, failure) : observed is OperationCanceledException;
}
// Failed NRPT setup cancels the same epoch while still holding the lifecycle
// lock. A proof already waiting to commit must not escape cleanup or apply late.
using (var epoch = new CancellationTokenSource())
using (var lifecycle = new SemaphoreSlim(1, 1))
{
var proofFinished = false; var committed = false; var drained = false;
var failure = new IOException("synthetic NRPT failure"); Exception? observed = null;
try
{
await StartupLearningWarmup.RunAsync(async begin => {
await lifecycle.WaitAsync();
try
{
begin(epoch.Token);
epoch.Cancel();
throw failure;
}
finally { lifecycle.Release(); }
}, async token => {
proofFinished = true;
try
{
await lifecycle.WaitAsync(token);
try { token.ThrowIfCancellationRequested(); committed = true; }
finally { lifecycle.Release(); }
}
finally { drained = true; }
}, CancellationToken.None, new ManualClock());
}
catch (Exception error) { observed = error; }
checks["failed_nrpt_cancels_pending_rule_commit"] = proofFinished && drained && !committed;
checks["pending_commit_cancellation_preserves_setup_error"] = ReferenceEquals(observed, failure);
}
{
var clock = new ManualClock();
using var caller = new CancellationTokenSource(TimeSpan.FromSeconds(45), clock);
var learningStopped = false; var setupStarted = Signal();
var run = StartupLearningWarmup.RunAsync(async begin => {
begin(CancellationToken.None); setupStarted.SetResult();
await Task.Delay(Timeout.Infinite, caller.Token);
}, async token => {
try { await Task.Delay(Timeout.Infinite, token); }
finally { learningStopped = true; }
}, caller.Token, clock);
await setupStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
clock.Advance(TimeSpan.FromSeconds(45));
var cancelled = false;
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (OperationCanceledException) { cancelled = true; }
checks["caller_forty_five_second_bound_remains_active_during_setup"] = cancelled && learningStopped;
}
{
using var caller = new CancellationTokenSource(); caller.Cancel(); var setupCalled = false;
try { await StartupLearningWarmup.RunAsync(_ => { setupCalled = true; return Task.CompletedTask; },
_ => Task.CompletedTask, caller.Token, new ManualClock()); }
catch (OperationCanceledException) { }
checks["cancelled_caller_does_not_start_setup"] = !setupCalled;
}
// Production learning handlers absorb cancellation after cleaning up their own
// probes. The startup owner must still propagate the user's cancelled connect.
{
using var caller = new CancellationTokenSource();
var clock = new ManualClock(); var learnerFinishedNormally = false;
var run = StartupLearningWarmup.RunAsync(begin => {
begin(CancellationToken.None); return Task.CompletedTask;
}, async token => {
try { await Task.Delay(Timeout.Infinite, token); }
catch (OperationCanceledException) { learnerFinishedNormally = true; }
}, caller.Token, clock);
await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
caller.Cancel();
var cancelled = false;
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (OperationCanceledException) { cancelled = true; }
checks["caller_cancellation_propagates_when_learning_swallows_it"] = cancelled && learnerFinishedNormally;
}
var report = new { passed = checks.Values.All(v => v), checks, production_coordinator = true,
simulated_external_phases = true, network_modified = false, production_client_started = false };
Console.WriteLine(JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }));
return report.passed ? 0 : 91;
sealed class ManualClock : TimeProvider
{
private readonly List<ManualTimer> timers = [];
internal long ElapsedTicks { get; private set; }
internal TaskCompletionSource Armed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
var timer = new ManualTimer(this, callback, state); lock (timers) timers.Add(timer);
timer.Change(dueTime, period); return timer;
}
internal void Advance(TimeSpan elapsed)
{
ManualTimer[] snapshot; lock (timers) { ElapsedTicks += elapsed.Ticks; snapshot = timers.ToArray(); }
foreach (var timer in snapshot) timer.FireIfDue();
}
private sealed class ManualTimer(ManualClock clock, TimerCallback callback, object? state) : ITimer
{
private long? due; private bool disposed;
public bool Change(TimeSpan dueTime, TimeSpan period)
{
if (disposed) return false;
due = dueTime == Timeout.InfiniteTimeSpan ? null : clock.ElapsedTicks + dueTime.Ticks;
if (dueTime == TimeSpan.FromSeconds(15)) clock.Armed.TrySetResult();
return true;
}
internal void FireIfDue()
{
if (!disposed && due is { } value && value <= clock.ElapsedTicks)
{ due = null; callback(state); }
}
public void Dispose() { disposed = true; due = null; }
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
}
}