using System.Text.Json; namespace UCVL.VPNPlus; internal static class LearningSyncCoordinatorSelfTest { internal static async Task RunAsync() { var checks = new Dictionary(); await AddChecksAsync(checks); var passed = checks.Values.All(value => value); File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "learning-sync-coordinator-self-test.json"), JsonSerializer.Serialize(new { kind = "optional_learning_api_resilience", network_modified = false, authenticated_vpn_tested = false, checks, passed }, new JsonSerializerOptions { WriteIndented = true })); return passed ? 0 : 87; } internal static async Task AddChecksAsync(Dictionary checks) { var test = new Fixture { UploadError = new ApiException(404, "secret-token-not-for-log") }; await test.Run(); checks["learning_upload_404_does_not_block_rule_fetch_or_apply"] = test.Uploads == 1 && test.Fetches == 1 && test.Applies == 1; checks["learning_upload_404_does_not_block_ack"] = test.Acks == 1 && test.Acknowledged.SequenceEqual(["revision-1"]); checks["learning_diagnostic_has_only_fixed_endpoint_and_outcome"] = test.Diagnostics.SequenceEqual(["learning.upload.unsupported.backoff"]); await test.Run(); checks["learning_one_callback_per_endpoint_per_run"] = test.Uploads == 1 && test.Fetches == 2 && test.Applies == 2 && test.Acks == 2; test.Now = 60_000; await test.Run(); checks["learning_unsupported_not_retried_or_logged_each_minute"] = test.Uploads == 1 && test.Diagnostics.Count == 1; test.Now = 120_000; await test.Run(); test.Now = 359_999; await test.Run(); checks["learning_unsupported_second_backoff_is_four_minutes"] = test.Uploads == 2 && test.Diagnostics.Count == 2; test.Now = 360_000; await test.Run(); test.Now = 839_999; await test.Run(); checks["learning_unsupported_third_backoff_is_eight_minutes"] = test.Uploads == 3; test.Now = 840_000; await test.Run(); test.Now = 1_739_999; await test.Run(); checks["learning_unsupported_backoff_caps_at_fifteen_minutes"] = test.Uploads == 4; test.Now = 1_740_000; await test.Run(); test.Now = 2_640_000; await test.Run(); checks["learning_unsupported_cap_remains_fifteen_minutes"] = test.Uploads == 6; test.UploadError = null; test.Now = 3_540_000; await test.Run(); checks["learning_endpoint_recovery_is_reported_once"] = test.Diagnostics.Last() == "learning.upload.recovered"; var logCount = test.Diagnostics.Count; test.Now++; await test.Run(); checks["learning_success_does_not_spam_recovery_logs"] = test.Diagnostics.Count == logCount; test.UploadError = new ApiException(405, "sensitive request details"); await test.Run(); var attempts = test.Uploads; test.Now += 119_999; await test.Run(); checks["learning_recovered_endpoint_restarts_405_at_two_minutes"] = test.Uploads == attempts; test.Now++; await test.Run(); checks["learning_405_uses_unsupported_policy"] = test.Uploads == attempts + 1 && test.Diagnostics.Last() == "learning.upload.unsupported.backoff"; test = new Fixture { FetchError = new ApiException(404, "not available") }; await test.Run(); test.Now = 60_000; await test.Run(); checks["learning_rules_backoff_does_not_gate_upload"] = test.Uploads == 2 && test.Fetches == 1 && test.Applies == 0 && test.Acks == 0; test = new Fixture { AckError = new ApiException(503, "unavailable") }; await test.Run(); checks["learning_failed_ack_keeps_applied_rules"] = test.Applies == 1 && test.LastApplied == "revision-1" && test.Acks == 1; test.FetchError = new ApiException(404, "not available"); await test.Run(); checks["learning_ack_gate_is_independent_of_rules_gate"] = test.Fetches == 2 && test.Acks == 1; test.AckError = null; test.Now = 60_000; await test.Run(); checks["learning_pending_ack_retries_even_when_rules_are_backing_off"] = test.Fetches == 2 && test.Acks == 2 && test.Acknowledged.SequenceEqual(["revision-1"]); test.Now++; await test.Run(); checks["learning_successful_pending_ack_is_not_repeated_without_new_apply"] = test.Acks == 2; test = new Fixture { UploadError = new ApiException(500, "transient") }; await test.Run(); test.Now = 59_999; await test.Run(); checks["learning_transient_first_retry_waits_one_minute"] = test.Uploads == 1; test.Now = 60_000; await test.Run(); test.Now = 179_999; await test.Run(); checks["learning_transient_second_retry_waits_two_minutes"] = test.Uploads == 2; test.Now = 180_000; await test.Run(); test.Now = 419_999; await test.Run(); checks["learning_transient_third_retry_waits_four_minutes"] = test.Uploads == 3; test.Now = 420_000; await test.Run(); test.Now = 719_999; await test.Run(); checks["learning_transient_backoff_caps_at_five_minutes"] = test.Uploads == 4; test.Now = 720_000; await test.Run(); checks["learning_transient_cap_eventually_retries"] = test.Uploads == 5; test = new Fixture { UploadError = new ApiException(404, "missing"), Now = 1_000_000 }; await test.Run(); test.Now = 1; await test.Run(); checks["learning_clock_regression_does_not_retry_early"] = test.Uploads == 1; test.Now = 1_119_999; await test.Run(); test.Now = 1_120_000; await test.Run(); checks["learning_retry_uses_monotonic_deadline_not_wall_clock"] = test.Uploads == 2; test.Coordinator.Reset(); await test.Run(); checks["learning_session_reset_clears_endpoint_backoff"] = test.Uploads == 3; foreach (var status in new[] { 401, 403 }) { test = new Fixture { UploadError = new ApiException(status, "authentication failed") }; var original = test.UploadError; Exception? thrown = null; try { await test.Run(); } catch (Exception error) { thrown = error; } checks[$"learning_upload_{status}_propagates_without_optional_fallback"] = ReferenceEquals(original, thrown) && test.Fetches == 0 && test.Applies == 0 && test.Acks == 0 && test.Diagnostics.Count == 0; test = new Fixture { FetchError = new ApiException(status, "authentication failed") }; original = test.FetchError; thrown = null; try { await test.Run(); } catch (Exception error) { thrown = error; } checks[$"learning_rules_{status}_propagates_without_ack"] = ReferenceEquals(original, thrown) && test.Acks == 0; test = new Fixture { AckError = new ApiException(status, "authentication failed") }; original = test.AckError; thrown = null; try { await test.Run(); } catch (Exception error) { thrown = error; } checks[$"learning_ack_{status}_propagates_without_removing_applied_rules"] = ReferenceEquals(original, thrown) && test.LastApplied == "revision-1"; } test = new Fixture { Current = false }; await test.Run(); checks["learning_wrong_session_does_not_send_requests"] = test.Uploads == 0 && test.Fetches == 0; test = new Fixture(); var fetchResult = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); test.FetchOverride = _ => fetchResult.Task; var inFlight = test.Run(); test.Current = false; fetchResult.SetResult(new RoutingManifest { Revision = "old-session" }); await inFlight; checks["learning_late_manifest_cannot_apply_to_new_session_or_core"] = test.Fetches == 1 && test.Applies == 0 && test.Acks == 0; test = new Fixture(); var uploadResult = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); test.UploadOverride = _ => uploadResult.Task; inFlight = test.Run(); await test.Run(); checks["learning_overlapping_run_does_not_duplicate_requests"] = test.Uploads == 1; test.Coordinator.Reset(); uploadResult.SetException(new ApiException(404, "old session")); await inFlight; checks["learning_reset_invalidates_old_error_without_new_session_penalty"] = test.Fetches == 0 && test.Diagnostics.Count == 0; test.UploadOverride = null; await test.Run(); checks["learning_new_session_can_sync_immediately_after_reset"] = test.Uploads == 2 && test.Applies == 1 && test.Acks == 1; test = new Fixture(); fetchResult = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); test.FetchOverride = _ => fetchResult.Task; inFlight = test.Run(); test.Current = false; fetchResult.SetException(new ApiException(401, "expired previous account")); await inFlight; checks["learning_stale_auth_failure_does_not_expire_successor_account"] = test.Applies == 0 && test.Diagnostics.Count == 0; test = new Fixture { ApplyAccepted = false }; await test.Run(); checks["learning_rejected_core_epoch_is_not_acknowledged"] = test.Applies == 1 && test.Acks == 0; test = new Fixture { AckError = new ApiException(404, "missing") }; await test.Run(); test.Coordinator.Reset(); test.FetchError = new ApiException(404, "missing"); test.AckError = null; await test.Run(); checks["learning_session_reset_discards_pending_ack"] = test.Acks == 1; test = new Fixture(); using var cancelled = new CancellationTokenSource(); cancelled.Cancel(); var sawCancellation = false; try { await test.Run(cancelled.Token); } catch (OperationCanceledException) { sawCancellation = true; } checks["learning_cancellation_prevents_requests"] = sawCancellation && test.Uploads == 0; using var deadline = new CancellationTokenSource(); test.UploadOverride = token => { deadline.Cancel(); return Task.CompletedTask; }; sawCancellation = false; try { await test.Run(deadline.Token); } catch (OperationCanceledException) { sawCancellation = true; } checks["learning_ignored_callback_cancellation_still_stops_following_requests"] = sawCancellation && test.Fetches == 0; test = new Fixture { UploadError = new TimeoutException("credential in exception") }; await test.Run(); checks["learning_timeout_is_transient_and_does_not_block_rule_fetch"] = test.Diagnostics.SequenceEqual(["learning.upload.transient.backoff"]) && test.Applies == 1; } private sealed class Fixture { internal long Now; internal bool Current = true; internal bool ApplyAccepted = true; internal Exception? UploadError, FetchError, AckError; internal Func? UploadOverride; internal Func>? FetchOverride; internal int Uploads, Fetches, Applies, Acks; internal string? LastApplied; internal List Acknowledged = []; internal List Diagnostics = []; internal LearningSyncCoordinator Coordinator { get; } internal Fixture() => Coordinator = new(() => Now); internal Task Run(CancellationToken token = default) => Coordinator.RunAsync(() => Current, cancellation => { Uploads++; return UploadOverride?.Invoke(cancellation) ?? (UploadError is { } error ? Task.FromException(error) : Task.CompletedTask); }, cancellation => { Fetches++; return FetchOverride?.Invoke(cancellation) ?? (FetchError is { } error ? Task.FromException(error) : Task.FromResult(new RoutingManifest { Revision = "revision-1" })); }, (manifest, cancellation) => { Applies++; if (ApplyAccepted) LastApplied = manifest.Revision; return Task.FromResult(ApplyAccepted); }, (revision, cancellation) => { Acks++; if (AckError is { } error) return Task.FromException(error); Acknowledged.Add(revision); return Task.CompletedTask; }, token, Diagnostics.Add); } }