From d268d5d9cf423850e88c75220776fdee5ceefae3 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Mon, 23 Nov 2026 01:47:13 +0800 Subject: [PATCH 1/3] Add durable update attempt snapshot binding Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/durable-update-attempts.md | 86 ++++ src/GeneralUpdate.Bowl/BowlContext.cs | 9 +- .../Bootstrap/GeneralUpdateBootstrap.cs | 28 ++ .../Configuration/ConfigurationMapper.cs | 8 + .../Configuration/ProcessContract.cs | 15 + .../Configuration/UpdateConfiguration.cs | 6 + .../Configuration/UpdateContext.cs | 12 + .../Configuration/UpdateRequestBuilder.cs | 18 +- .../FileSystem/StorageManager.cs | 71 ++- .../DurableUpdateAttemptStore.cs | 428 ++++++++++++++++++ .../Strategy/AbstractStrategy.cs | 6 + .../Strategy/ClientStrategy.cs | 31 +- tests/BowlTest/BowlContextTests.cs | 15 + .../Integration/BowlCrashPipelineTests.cs | 34 ++ .../UpdateRequestBuilderTests.cs | 15 + .../DurableUpdateAttemptStoreTests.cs | 308 +++++++++++++ tests/StartupHealthProbe/Program.cs | 40 ++ 17 files changed, 1105 insertions(+), 25 deletions(-) create mode 100644 docs/durable-update-attempts.md create mode 100644 src/GeneralUpdate.Core/StartupHealth/DurableUpdateAttemptStore.cs create mode 100644 tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs diff --git a/docs/durable-update-attempts.md b/docs/durable-update-attempts.md new file mode 100644 index 00000000..3e8bfd87 --- /dev/null +++ b/docs/durable-update-attempts.md @@ -0,0 +1,86 @@ +# Durable update attempts and exact backup binding + +This layer is opt-in. The caller supplies and durably retains a unique, +non-empty `DurableUpdateAttemptId` before starting an update: + +```csharp +var attemptId = Guid.NewGuid(); +// Persist attemptId and its update association before calling the updater. +var request = new UpdateRequest +{ + DurableUpdateAttemptId = attemptId, + // existing update settings... +}; +``` + +`UpdateRequestBuilder.SetDurableUpdateAttemptId` is also available. Never reuse +an ID, even when a crash occurs before an attempt record becomes readable. +Without an ID, the existing workflow, backup naming, and rollback behavior stay +unchanged. + +For an opted-in update, ClientStrategy requires backups to be enabled, creates +the durable attempt under +`{InstallPath}/.backups/.attempts`, and reserves an attempt-specific backup +path before copying. The path includes the attempt ID rather than relying on +the legacy one-second timestamp alone. The backup is copied to a fresh staging +directory and published with a non-overwriting directory move. Only after that +copy succeeds is the exact path bound into the journal and passed in +`ProcessContract`, together with the attempt ID, journal directory, and +`DisableLegacyRollback=true`. The executing Core bootstrap reopens the record +and rejects an absent, corrupt, unbound, mismatched, or missing snapshot rather +than using `GetLatestBackup`. + +The attempt journal uses atomic state-file publication and an OS-released +cross-process lock. `CleanBackup` takes the same lock while reading pins and +deleting candidates. Reserved and bound paths are excluded from retention; a +corrupt state file causes cleanup to fail rather than risk deleting an +unreadable pin. The attempt-specific staging/publish path avoids overwriting a +prior attempt snapshot through the opt-in Core path. + +## Reliability boundary + +The record binds an attempt to a **path**, not to an immutable snapshot +identity. This layer does not hash or verify a file manifest, prevent a +same-permission external writer from modifying that directory, or coordinate +with older binaries and external cleanup tools that do not use the journal +lock. Consequently it does not claim global snapshot immutability or a +filesystem-wide fence. The installing application should be quiescent during +backup; operators must protect the installation and journal from untrusted +writers. + +`ClaimRecovery` is a cooperative journal compare-and-swap: simultaneous +claimants using one expected fence cannot both win, and a later claim makes an +earlier claim stale for journal completion. It does not fence writes to the +installation tree and does not establish that a previous owner is dead. A +caller may advance a fence only after independently establishing that the +prior claimant is no longer authorized. No `RecoveryOwner` is designated here. +`Complete` only records a caller-supplied external outcome; it does not inspect +business readiness or restore files. + +For opted-in attempts, Core's legacy `AbstractStrategy.TryRollback` is +suppressed, and `BowlContext.Normalize` suppresses `AutoRestore` when the +attempt ID is propagated to that context. The process contract carries +`DisableLegacyRollback` for cooperating consumers. However, the current +GeneralUpdate producer does not construct Bowl.Host requests or pass this field +into an external Host; Bowl.Host's separate `AutoRollback` setting is not wired +or verified here. Keep Bowl/Host automatic rollback disabled for this mode. +The installed Bowl.Host PR #3 Recovery implementation is fail-closed and is +not a production recovery owner; its Controlled* prototypes and fixtures are +not enabled by this layer. No automatic restore is enabled. + +This is not a recovery or health closure. The updater does not recover after a +crash, select a recovery owner, make recovery idempotent, or report application +readiness. Process survival, Bowl `filesOnly`/`processAlive`, and successful +file application are not business health. The attempt remains pinned until an +authorized cooperating caller records an externally established terminal +outcome. + +The reporting changes from GeneralUpdate #541 concern report routing and +phase timing; they do not make a report a business-readiness signal. On the +#549 base, the MainOnly client path can report applied immediately before it +launches the upgrade process; #541 removes that particular early report. In +either version, execution-side package-application success still does not prove +that the updated application launched or passed its own readiness checks. A +future Bowl/Host integration must consume the attempt contract, keep +`AutoRollback=false` until a single real recovery owner is implemented and +fenced, and report health only after application-owned readiness confirmation. diff --git a/src/GeneralUpdate.Bowl/BowlContext.cs b/src/GeneralUpdate.Bowl/BowlContext.cs index 0eae0ede..7adee0ec 100644 --- a/src/GeneralUpdate.Bowl/BowlContext.cs +++ b/src/GeneralUpdate.Bowl/BowlContext.cs @@ -48,6 +48,12 @@ public readonly record struct BowlContext /// When true and is "Upgrade", restores backup on crash. public bool AutoRestore { get; init; } + /// + /// Durable attempt metadata received from a cooperating updater. When present, automatic + /// restore is suppressed; this does not designate a replacement recovery owner. + /// + public Guid? DurableUpdateAttemptId { get; init; } + /// Optional callback invoked when a crash is detected. public Func? OnCrash { get; init; } @@ -66,7 +72,8 @@ public BowlContext Normalize() ExtendedField = ExtendedField, TimeoutMs = TimeoutMs <= 0 ? 30_000 : TimeoutMs, DumpType = DumpType == default ? DumpType.Full : DumpType, - AutoRestore = AutoRestore, + AutoRestore = DurableUpdateAttemptId.HasValue ? false : AutoRestore, + DurableUpdateAttemptId = DurableUpdateAttemptId, OnCrash = OnCrash, }; } diff --git a/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs b/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs index 6dc8719a..839bd858 100644 --- a/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs +++ b/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs @@ -15,6 +15,7 @@ using GeneralUpdate.Core.Differential; using GeneralUpdate.Core.Pipeline; using GeneralUpdate.Core.Network; +using GeneralUpdate.Core.StartupHealth; using GeneralUpdate.Differential.Differ; namespace GeneralUpdate.Core; @@ -411,15 +412,42 @@ private void InitializeFromEnvironment() UpdatePath = processInfo.UpdatePath, LaunchClientAfterUpdate = processInfo.LaunchClientAfterUpdate, ReportType = processInfo.ReportType, + DurableUpdateAttemptId = processInfo.DurableUpdateAttemptId, + AttemptJournalDirectory = processInfo.AttemptJournalDirectory, + DisableLegacyRollback = processInfo.DisableLegacyRollback, Files = processInfo.Files ?? BlackDefaults.DefaultFiles, Formats = processInfo.Formats ?? BlackDefaults.DefaultFormats, Directories = processInfo.Directories ?? BlackDefaults.DefaultDirectories }; + if (processInfo.DurableUpdateAttemptId.HasValue) + { + if (processInfo.DurableUpdateAttemptId.Value == Guid.Empty) + throw new InvalidDataException("The update process contract contains an empty durable attempt ID."); + var expectedJournal = DurableUpdateAttemptStore.GetDirectory(processInfo.InstallPath); + if (string.IsNullOrWhiteSpace(processInfo.AttemptJournalDirectory) || + !string.Equals(Path.GetFullPath(processInfo.AttemptJournalDirectory), expectedJournal, + StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("The update process contract has a mismatched attempt journal directory."); + if (!processInfo.DisableLegacyRollback) + throw new InvalidDataException("A durable update attempt must disable the legacy Core rollback path."); + var attempt = new DurableUpdateAttemptStore(processInfo.InstallPath) + .GetAttempt(processInfo.DurableUpdateAttemptId.Value); + if (attempt.Status != DurableUpdateAttemptStatus.SnapshotBound || + string.IsNullOrWhiteSpace(attempt.SnapshotPath) || + !string.Equals(Path.GetFullPath(attempt.SnapshotPath), Path.GetFullPath(processInfo.BackupDirectory), + StringComparison.OrdinalIgnoreCase) || + !Directory.Exists(attempt.SnapshotPath)) + throw new InvalidDataException("The update process contract does not match the journal's bound snapshot."); + } + StorageManager.BlackMatcher = BlackMatcher.FromConfigInfo(_configInfo); } catch (Exception ex) { + if (processInfo.DurableUpdateAttemptId.HasValue) + throw new InvalidDataException("Failed to validate the durable update attempt process contract.", ex); + // Corrupted / incompatible IPC data (e.g. from a mismatched version // of the sender, or stale test data) — treat as "no IPC data". GeneralTracer.Warn($"Failed to map IPC process contract: {ex.Message}"); diff --git a/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs b/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs index 6929d5cf..25513093 100644 --- a/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs +++ b/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Text; +using GeneralUpdate.Core.StartupHealth; namespace GeneralUpdate.Core.Configuration { @@ -104,6 +105,7 @@ public static UpdateContext MapToUpdateContext(UpdateRequest source, UpdateConte target.ProductId = source.ProductId; target.CustomHeaders = source.CustomHeaders; target.MaxChainBeforeFallback = source.MaxChainBeforeFallback; + target.DurableUpdateAttemptId = source.DurableUpdateAttemptId; return target; } @@ -208,6 +210,12 @@ public static ProcessContract MapToProcessContract( launchClient: source.LaunchClientAfterUpdate ); processInfo.ReportType = reportType; + processInfo.DurableUpdateAttemptId = source.DurableUpdateAttemptId; + if (source.DurableUpdateAttemptId.HasValue) + { + processInfo.AttemptJournalDirectory = DurableUpdateAttemptStore.GetDirectory(source.InstallPath); + processInfo.DisableLegacyRollback = true; + } return processInfo; } } diff --git a/src/GeneralUpdate.Core/Configuration/ProcessContract.cs b/src/GeneralUpdate.Core/Configuration/ProcessContract.cs index dc37b14f..036e690b 100644 --- a/src/GeneralUpdate.Core/Configuration/ProcessContract.cs +++ b/src/GeneralUpdate.Core/Configuration/ProcessContract.cs @@ -403,5 +403,20 @@ public ProcessContract(string appName /// [JsonPropertyName("ReportType")] public int ReportType { get; set; } = 1; + + /// Caller-owned durable update-attempt ID; null keeps legacy behavior. + [JsonPropertyName("DurableUpdateAttemptId")] + public Guid? DurableUpdateAttemptId { get; set; } + + /// Stable local journal directory for the durable update attempt. + [JsonPropertyName("AttemptJournalDirectory")] + public string? AttemptJournalDirectory { get; set; } + + /// + /// Requests that cooperating consumers suppress their legacy automatic rollback. + /// This is a protocol declaration, not proof that an external consumer honors it. + /// + [JsonPropertyName("DisableLegacyRollback")] + public bool DisableLegacyRollback { get; set; } } } diff --git a/src/GeneralUpdate.Core/Configuration/UpdateConfiguration.cs b/src/GeneralUpdate.Core/Configuration/UpdateConfiguration.cs index 7d5e5dee..26791c9b 100644 --- a/src/GeneralUpdate.Core/Configuration/UpdateConfiguration.cs +++ b/src/GeneralUpdate.Core/Configuration/UpdateConfiguration.cs @@ -30,6 +30,12 @@ namespace GeneralUpdate.Core.Configuration /// public abstract class UpdateConfiguration { + /// + /// Optional caller-owned durable update-attempt identifier. Null preserves legacy behavior. + /// The caller must persist a non-empty ID and never reuse it. + /// + public Guid? DurableUpdateAttemptId { get; set; } + /// /// The executable file name of the updater application (e.g., "Update.exe"). /// When the client needs to launch the upgrade process, this name is used to locate and start the updater. diff --git a/src/GeneralUpdate.Core/Configuration/UpdateContext.cs b/src/GeneralUpdate.Core/Configuration/UpdateContext.cs index aa0d8889..f27f9af1 100644 --- a/src/GeneralUpdate.Core/Configuration/UpdateContext.cs +++ b/src/GeneralUpdate.Core/Configuration/UpdateContext.cs @@ -130,6 +130,18 @@ public class UpdateContext : UpdateConfiguration /// public string BackupDirectory { get; set; } + /// + /// Stable journal directory received by the update process for an opt-in durable attempt. + /// Empty when the legacy update path is in use. + /// + public string? AttemptJournalDirectory { get; set; } + + /// + /// When true, the in-process legacy rollback path must not compete with an external + /// recovery protocol. This does not enable or designate an external recovery owner. + /// + public bool DisableLegacyRollback { get; set; } + // ────────────────────────────── // Download/Update behavior options (injected from Option) // ────────────────────────────── diff --git a/src/GeneralUpdate.Core/Configuration/UpdateRequestBuilder.cs b/src/GeneralUpdate.Core/Configuration/UpdateRequestBuilder.cs index 17457520..5a329390 100644 --- a/src/GeneralUpdate.Core/Configuration/UpdateRequestBuilder.cs +++ b/src/GeneralUpdate.Core/Configuration/UpdateRequestBuilder.cs @@ -63,6 +63,7 @@ public class UpdateRequestBuilder private List _blackFiles; private List _blackFormats; private List _skipDirectorys; + private Guid? _durableUpdateAttemptId; /// /// Creates a instance by loading settings from the @@ -189,6 +190,8 @@ private static UpdateRequestBuilder LoadFromConfigFile() builder.SetFormats(config.Formats); if (config.Directories != null) builder.SetDirectories(config.Directories); + if (config.DurableUpdateAttemptId.HasValue) + builder.SetDurableUpdateAttemptId(config.DurableUpdateAttemptId.Value); builder.SetInstallPath(string.IsNullOrWhiteSpace(config.InstallPath) ? AppDomain.CurrentDomain.BaseDirectory : config.InstallPath); return builder; @@ -219,6 +222,18 @@ private static UpdateRequestBuilder LoadFromConfigFile() } } + /// + /// Enables durable update-attempt journaling for a caller-owned, pre-persisted ID. + /// The ID must be unique and must never be reused. + /// + public UpdateRequestBuilder SetDurableUpdateAttemptId(Guid attemptId) + { + if (attemptId == Guid.Empty) + throw new ArgumentException("A non-empty durable update-attempt ID is required.", nameof(attemptId)); + _durableUpdateAttemptId = attemptId; + return this; + } + /// /// Sets the API endpoint URL for update checking. /// @@ -533,7 +548,8 @@ public UpdateRequest Build() DriverDirectory = _driverDirectory, Files = _blackFiles ?? new List(), Formats = _blackFormats ?? new List(), - Directories = _skipDirectorys ?? new List() + Directories = _skipDirectorys ?? new List(), + DurableUpdateAttemptId = _durableUpdateAttemptId }; // 校验构建的配置 diff --git a/src/GeneralUpdate.Core/FileSystem/StorageManager.cs b/src/GeneralUpdate.Core/FileSystem/StorageManager.cs index 37ac6fbe..6c05ac62 100644 --- a/src/GeneralUpdate.Core/FileSystem/StorageManager.cs +++ b/src/GeneralUpdate.Core/FileSystem/StorageManager.cs @@ -7,6 +7,7 @@ using System.Threading; using GeneralUpdate.Core.HashAlgorithms; using GeneralUpdate.Core; +using GeneralUpdate.Core.StartupHealth; namespace GeneralUpdate.Core.FileSystem { @@ -54,6 +55,9 @@ public sealed class StorageManager /// public const string BackupRootDirectory = ".backups"; + /// Directory beneath containing durable attempt records. + public const string AttemptDirectoryName = ".attempts"; + /// /// Backup directory name prefixes used for enumeration (both new and legacy formats). /// Derived from and . @@ -309,7 +313,8 @@ public static void CleanupOldTempDirectories(TimeSpan? maxAge = null) if (Directory.Exists(backupRoot)) { allBackups.AddRange(new DirectoryInfo(backupRoot) - .GetDirectories("*", SearchOption.TopDirectoryOnly)); + .GetDirectories("*", SearchOption.TopDirectoryOnly) + .Where(d => !string.Equals(d.Name, AttemptDirectoryName, StringComparison.OrdinalIgnoreCase))); } // Scan installPath directly for backup dirs matching patterns from defaults @@ -506,20 +511,22 @@ public static bool HashEquals(string leftPath, string rightPath) /// The source application directory path. /// The target backup directory path. /// The list of subdirectory names to skip (uses containment matching). + /// When true, copy to a fresh staging directory and publish without replacing an existing destination. /// /// /// Backup flow: /// - /// If the backup directory already exists, delete it first. - /// Create a new backup directory. + /// When is false, delete an existing backup directory and create a new one. + /// When is true, create a fresh attempt staging directory instead. /// Recursively copy all files and subdirectories from the source directory, skipping directories that match . + /// When is true, move the completed staging directory to the destination without overwriting. /// /// /// - /// This method overwrites existing files in the target directory. + /// The default mode overwrites an existing destination. Use for paths that must be unique. /// /// - public static void Backup(string sourcePath, string backupPath, IReadOnlyList directoryNames) + public static void Backup(string sourcePath, string backupPath, IReadOnlyList directoryNames, bool createOnly = false) { // Merge default backup-exclusion prefixes with user-configured directories. // This ensures backup/legacy directories are ALWAYS skipped, preventing @@ -527,10 +534,27 @@ public static void Backup(string sourcePath, string backupPath, IReadOnlyList(directoryNames); effectiveDirectories.AddRange(BlackDefaults.DefaultDirectories); - if (Directory.Exists(backupPath)) + if (createOnly) { - DeleteDirectory(backupPath); + var stagingPath = Path.Combine( + Path.GetDirectoryName(backupPath)!, + AttemptDirectoryName, + ".staging-" + Guid.NewGuid().ToString("N")); + try + { + Directory.CreateDirectory(stagingPath); + CopyDirectory(sourcePath, stagingPath, effectiveDirectories); + Directory.Move(stagingPath, backupPath); + } + catch + { + if (Directory.Exists(stagingPath)) DeleteDirectory(stagingPath); + throw; + } + return; } + + if (Directory.Exists(backupPath)) DeleteDirectory(backupPath); Directory.CreateDirectory(backupPath); CopyDirectory(sourcePath, backupPath, effectiveDirectories); } @@ -726,18 +750,17 @@ private IEnumerable ReadFileNode(string path, string rootPath = null) /// public static void CleanBackup(string installPath, int keepVersions = 3) { - // Scan BackupRootDirectory subdirectory (new-format backup container) - var backupRoot = Path.Combine(installPath, BackupRootDirectory); - if (Directory.Exists(backupRoot)) - { - CleanDirectories(backupRoot, keepVersions); - } - - // Scan installPath directly for backup dirs matching patterns from defaults - foreach (var pattern in GetBackupSearchPatterns()) + DurableUpdateAttemptStore.WithBackupRetentionLock(installPath, pinned => { - CleanDirectories(installPath, keepVersions, pattern); - } + var pinnedPaths = new HashSet(pinned.Select(Path.GetFullPath), StringComparer.OrdinalIgnoreCase); + var backupRoot = Path.Combine(installPath, BackupRootDirectory); + if (Directory.Exists(backupRoot)) + CleanDirectories(backupRoot, keepVersions, "*", pinnedPaths, AttemptDirectoryName); + + foreach (var pattern in GetBackupSearchPatterns()) + CleanDirectories(installPath, keepVersions, pattern, pinnedPaths); + return true; + }); } /// @@ -756,10 +779,17 @@ private static IEnumerable GetBackupSearchPatterns() /// Cleans directories matching the specified pattern in the given root path, /// retaining only the most recent N directories. /// - private static void CleanDirectories(string rootPath, int keepVersions, string searchPattern = "*") + private static void CleanDirectories( + string rootPath, + int keepVersions, + string searchPattern = "*", + ISet? pinnedPaths = null, + string? excludedName = null) { var dirs = new DirectoryInfo(rootPath) .GetDirectories(searchPattern, SearchOption.TopDirectoryOnly) + .Where(d => excludedName == null || !string.Equals(d.Name, excludedName, StringComparison.OrdinalIgnoreCase)) + .Where(d => pinnedPaths == null || !pinnedPaths.Contains(Path.GetFullPath(d.FullName))) .OrderByDescending(d => d.CreationTime) .ThenByDescending(d => d.Name) .Skip(keepVersions); @@ -786,7 +816,8 @@ public static IReadOnlyList ListBackups(string installPath) var backupRoot = Path.Combine(installPath, BackupRootDirectory); if (Directory.Exists(backupRoot)) { - result.AddRange(ToBackupInfos(backupRoot, "*")); + result.AddRange(ToBackupInfos(backupRoot, "*") + .Where(info => !string.Equals(info.Version, AttemptDirectoryName, StringComparison.OrdinalIgnoreCase))); } // Scan installPath directly for backup dirs matching patterns from defaults diff --git a/src/GeneralUpdate.Core/StartupHealth/DurableUpdateAttemptStore.cs b/src/GeneralUpdate.Core/StartupHealth/DurableUpdateAttemptStore.cs new file mode 100644 index 00000000..56144528 --- /dev/null +++ b/src/GeneralUpdate.Core/StartupHealth/DurableUpdateAttemptStore.cs @@ -0,0 +1,428 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Threading; + +namespace GeneralUpdate.Core.StartupHealth; + +/// +/// Durable journal for update attempts and their exact backup snapshots. +/// This store records metadata and fences cooperating recovery claimants; it never restores files. +/// +public sealed class DurableUpdateAttemptStore +{ + private const int FormatVersion = 1; + private readonly string _installPath; + private readonly string _directory; + + public DurableUpdateAttemptStore(string installPath) + { + if (string.IsNullOrWhiteSpace(installPath)) + throw new ArgumentException("An installation path is required.", nameof(installPath)); + _installPath = Path.GetFullPath(installPath); + _directory = GetDirectory(_installPath); + } + + /// The stable journal directory used for an installation. + public static string GetDirectory(string installPath) + { + if (string.IsNullOrWhiteSpace(installPath)) + throw new ArgumentException("An installation path is required.", nameof(installPath)); + return Path.Combine(Path.GetFullPath(installPath), GeneralUpdate.Core.FileSystem.StorageManager.BackupRootDirectory, + GeneralUpdate.Core.FileSystem.StorageManager.AttemptDirectoryName); + } + + /// + /// Creates a new attempt. IDs are caller-selected and must never be reused, including + /// after an interrupted creation. + /// + public void Begin(Guid attemptId) + { + ValidateId(attemptId); + WithLock(() => + { + var path = StatePath(attemptId); + var creationPath = CreationPath(attemptId); + if (File.Exists(path) || File.Exists(creationPath)) + throw new InvalidOperationException($"Update attempt {attemptId} already exists."); + using (var creation = new FileStream(creationPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + creation.Flush(true); + WriteState(path, new AttemptState(attemptId)); + }); + } + + /// + /// Pins the intended backup path before copying starts, so concurrent retention cannot + /// delete it. The path is not a bound snapshot until succeeds. + /// + public void ReserveSnapshot(Guid attemptId, string snapshotPath) + { + ValidateId(attemptId); + var fullPath = ValidateSnapshotPath(snapshotPath); + WithLock(() => + { + var state = ReadState(attemptId); + RequireStatus(state, DurableUpdateAttemptStatus.Pending); + state.SnapshotPath = fullPath; + state.Status = DurableUpdateAttemptStatus.SnapshotReserved; + WriteState(StatePath(attemptId), state); + }); + } + + /// + /// Binds the exact reserved path after the real backup operation has completed. + /// Missing or mismatched paths fail explicitly; no latest-backup fallback is used. + /// + public void BindSnapshot(Guid attemptId, string snapshotPath) + { + ValidateId(attemptId); + var fullPath = ValidateSnapshotPath(snapshotPath); + WithLock(() => + { + var state = ReadState(attemptId); + RequireStatus(state, DurableUpdateAttemptStatus.SnapshotReserved); + if (!PathEquals(state.SnapshotPath!, fullPath)) + throw new InvalidOperationException("The completed backup does not match the reserved snapshot path."); + if (!Directory.Exists(fullPath)) + throw new DirectoryNotFoundException($"The reserved update snapshot was not created: {fullPath}"); + state.Status = DurableUpdateAttemptStatus.SnapshotBound; + WriteState(StatePath(attemptId), state); + }); + } + + /// Reopens the durable attempt after a process restart. + public DurableUpdateAttemptRecord GetAttempt(Guid attemptId) + { + ValidateId(attemptId); + return WithLock(() => ToRecord(ReadState(attemptId))); + } + + /// + /// Claims recovery at the expected fence. Use fence 0 for the first claim. A caller may + /// supersede a prior claimant only after independently establishing that claimant is no + /// longer authorized to act. Concurrent claimants using the same fence cannot both win. + /// + public DurableUpdateAttemptClaim ClaimRecovery(Guid attemptId, long expectedFence) + { + ValidateId(attemptId); + if (expectedFence < 0) throw new ArgumentOutOfRangeException(nameof(expectedFence)); + return WithLock(() => + { + var state = ReadState(attemptId); + if (state.Status != DurableUpdateAttemptStatus.SnapshotBound) + throw new InvalidOperationException("Recovery requires an active attempt with a bound snapshot."); + if (state.SnapshotPath == null || !Directory.Exists(state.SnapshotPath)) + throw new DirectoryNotFoundException($"The bound update snapshot is missing: {state.SnapshotPath}"); + if (state.Fence != expectedFence) + throw new InvalidOperationException($"Stale recovery fence {expectedFence}; current fence is {state.Fence}."); + state.Fence = checked(state.Fence + 1); + state.ClaimId = Guid.NewGuid(); + WriteState(StatePath(attemptId), state); + return new DurableUpdateAttemptClaim(attemptId, state.Fence, state.ClaimId.Value); + }); + } + + /// + /// Closes an attempt only with the current fenced claim. The caller must supply external + /// evidence of health or completed recovery; this method does not infer either outcome. + /// + public bool Complete(Guid attemptId, DurableUpdateAttemptClaim claim, DurableUpdateAttemptCompletion completion) + { + ValidateId(attemptId); + if (claim == null) throw new ArgumentNullException(nameof(claim)); + if (claim.AttemptId != attemptId) throw new ArgumentException("The claim belongs to another attempt.", nameof(claim)); + if (completion != DurableUpdateAttemptCompletion.HealthyConfirmed && + completion != DurableUpdateAttemptCompletion.RecoveryCompleted) + throw new ArgumentOutOfRangeException(nameof(completion)); + + return WithLock(() => + { + var state = ReadState(attemptId); + if (state.Status == DurableUpdateAttemptStatus.HealthyConfirmed || + state.Status == DurableUpdateAttemptStatus.RecoveryCompleted) + return false; + if (state.Status != DurableUpdateAttemptStatus.SnapshotBound || + state.Fence != claim.Fence || state.ClaimId != claim.ClaimId) + throw new InvalidOperationException("The recovery claim is stale or no longer owns this attempt."); + state.Status = completion == DurableUpdateAttemptCompletion.HealthyConfirmed + ? DurableUpdateAttemptStatus.HealthyConfirmed + : DurableUpdateAttemptStatus.RecoveryCompleted; + WriteState(StatePath(attemptId), state); + return true; + }); + } + + internal static TResult WithBackupRetentionLock( + string installPath, + Func, TResult> action) + { + if (action == null) throw new ArgumentNullException(nameof(action)); + var store = new DurableUpdateAttemptStore(installPath); + using (AcquireLock(store._installPath)) + { + if (!Directory.Exists(store._directory)) + return action(Array.Empty()); + + var pinned = new List(); + foreach (var path in Directory.GetFiles(store._directory, "*.state", SearchOption.TopDirectoryOnly)) + { + var name = Path.GetFileNameWithoutExtension(path); + if (!Guid.TryParseExact(name, "N", out var id)) + throw new InvalidDataException($"Invalid update attempt journal filename: {Path.GetFileName(path)}"); + var state = ReadStateFile(path, id); + if (state.Status == DurableUpdateAttemptStatus.SnapshotReserved || + state.Status == DurableUpdateAttemptStatus.SnapshotBound) + { + if (state.SnapshotPath == null) + throw new InvalidDataException($"Attempt {state.AttemptId} is missing its pinned snapshot path."); + pinned.Add(state.SnapshotPath); + } + } + return action(pinned); + } + } + + private string StatePath(Guid id) => Path.Combine(_directory, id.ToString("N") + ".state"); + private string CreationPath(Guid id) => Path.Combine(_directory, id.ToString("N") + ".created"); + + private string ValidateSnapshotPath(string path) + { + if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("A snapshot path is required.", nameof(path)); + var fullPath = Path.GetFullPath(path); + var backupRoot = Path.GetFullPath(Path.Combine(_installPath, GeneralUpdate.Core.FileSystem.StorageManager.BackupRootDirectory)); + if (!PathEquals(Path.GetDirectoryName(fullPath)!, backupRoot) || + !Path.GetFileName(fullPath).StartsWith("backup-", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("The snapshot must be a direct backup-{name} child of the installation backup directory.", nameof(path)); + return fullPath; + } + + private void WithLock(Action action) => WithLock(() => { action(); return true; }); + + private TResult WithLock(Func action) + { + Directory.CreateDirectory(_directory); + using (AcquireLock(_installPath)) + return action(); + } + + private static IDisposable AcquireLock(string installPath) + { + var lockIdentity = Path.GetFullPath(installPath).ToUpperInvariant(); + byte[] hash; + using (var sha = SHA256.Create()) + hash = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(lockIdentity)); + var mutexName = "GeneralUpdate_Attempt_" + BitConverter.ToString(hash).Replace("-", string.Empty); + var mutex = new Mutex(false, mutexName); + try + { + try + { + if (!mutex.WaitOne(TimeSpan.FromSeconds(5))) + throw new TimeoutException("Timed out waiting for the update-attempt journal lock."); + } + catch (AbandonedMutexException) + { + // The OS releases a named mutex when its owner process exits. + } + return new MutexLock(mutex); + } + catch + { + mutex.Dispose(); + throw; + } + } + + private sealed class MutexLock : IDisposable + { + private readonly Mutex _mutex; + private bool _disposed; + + public MutexLock(Mutex mutex) => _mutex = mutex; + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + try { _mutex.ReleaseMutex(); } + finally { _mutex.Dispose(); } + } + } + + private AttemptState ReadState(Guid id) => ReadStateFile(StatePath(id), id); + + private static AttemptState ReadStateFile(string path, Guid? expectedId = null) + { + if (!File.Exists(path)) throw new FileNotFoundException("Durable update attempt was not found.", path); + try + { + var fileBytes = File.ReadAllBytes(path); + if (fileBytes.Length < 36) throw new InvalidDataException("Truncated update attempt journal."); + var payloadLength = fileBytes.Length - 32; + var payload = new byte[payloadLength]; + var storedHash = new byte[32]; + Buffer.BlockCopy(fileBytes, 0, payload, 0, payloadLength); + Buffer.BlockCopy(fileBytes, payloadLength, storedHash, 0, storedHash.Length); + byte[] actualHash; + using (var sha = SHA256.Create()) actualHash = sha.ComputeHash(payload); + if (!storedHash.SequenceEqual(actualHash)) + throw new InvalidDataException("Update attempt journal checksum mismatch."); + + using var stream = new MemoryStream(payload, writable: false); + using var reader = new BinaryReader(stream); + if (reader.ReadInt32() != FormatVersion) throw new InvalidDataException("Unsupported update attempt journal format."); + var idBytes = reader.ReadBytes(16); + if (idBytes.Length != 16) throw new InvalidDataException("Truncated update attempt identifier."); + var id = new Guid(idBytes); + if (expectedId.HasValue && id != expectedId.Value) + throw new InvalidDataException("Update attempt identifier does not match its journal filename."); + var status = (DurableUpdateAttemptStatus)reader.ReadInt32(); + if (!Enum.IsDefined(typeof(DurableUpdateAttemptStatus), status)) + throw new InvalidDataException("Invalid update attempt status."); + var fence = reader.ReadInt64(); + if (fence < 0) throw new InvalidDataException("Invalid recovery fence."); + var hasClaim = reader.ReadBoolean(); + Guid? claimId = null; + if (hasClaim) + { + var claimBytes = reader.ReadBytes(16); + if (claimBytes.Length != 16) throw new InvalidDataException("Truncated recovery claim."); + claimId = new Guid(claimBytes); + } + var hasSnapshot = reader.ReadBoolean(); + var snapshotPath = hasSnapshot ? reader.ReadString() : null; + if (stream.Position != stream.Length) throw new InvalidDataException("Unexpected trailing update attempt data."); + if ((status == DurableUpdateAttemptStatus.Pending) != (snapshotPath == null)) + throw new InvalidDataException("Update attempt snapshot state is inconsistent."); + if ((fence == 0) != !claimId.HasValue) + throw new InvalidDataException("Update attempt recovery claim state is inconsistent."); + return new AttemptState(id) + { + Status = status, + Fence = fence, + ClaimId = claimId, + SnapshotPath = snapshotPath + }; + } + catch (EndOfStreamException ex) + { + throw new InvalidDataException("Truncated update attempt journal.", ex); + } + } + + private static void WriteState(string path, AttemptState state) + { + var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + byte[] payload; + using (var memory = new MemoryStream()) + { + using (var writer = new BinaryWriter(memory, System.Text.Encoding.UTF8, true)) + { + writer.Write(FormatVersion); + writer.Write(state.AttemptId.ToByteArray()); + writer.Write((int)state.Status); + writer.Write(state.Fence); + writer.Write(state.ClaimId.HasValue); + if (state.ClaimId.HasValue) writer.Write(state.ClaimId.Value.ToByteArray()); + writer.Write(state.SnapshotPath != null); + if (state.SnapshotPath != null) writer.Write(state.SnapshotPath); + writer.Flush(); + } + payload = memory.ToArray(); + } + + byte[] hash; + using (var sha = SHA256.Create()) hash = sha.ComputeHash(payload); + using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + stream.Write(payload, 0, payload.Length); + stream.Write(hash, 0, hash.Length); + stream.Flush(true); + } + if (File.Exists(path)) File.Replace(temporary, path, null); + else File.Move(temporary, path); + } + finally + { + if (File.Exists(temporary)) File.Delete(temporary); + } + } + + private static void RequireStatus(AttemptState state, DurableUpdateAttemptStatus status) + { + if (state.Status != status) + throw new InvalidOperationException($"Attempt {state.AttemptId} is {state.Status}, expected {status}."); + } + + private static DurableUpdateAttemptRecord ToRecord(AttemptState state) => + new(state.AttemptId, state.Status, state.SnapshotPath, state.Fence, state.ClaimId); + + private static bool PathEquals(string left, string right) => + string.Equals(Path.GetFullPath(left), Path.GetFullPath(right), StringComparison.OrdinalIgnoreCase); + + private static void ValidateId(Guid id) + { + if (id == Guid.Empty) throw new ArgumentException("A non-empty update attempt ID is required.", nameof(id)); + } + + private sealed class AttemptState + { + public AttemptState(Guid attemptId) => AttemptId = attemptId; + public Guid AttemptId { get; } + public DurableUpdateAttemptStatus Status { get; set; } = DurableUpdateAttemptStatus.Pending; + public string? SnapshotPath { get; set; } + public long Fence { get; set; } + public Guid? ClaimId { get; set; } + } +} + +public enum DurableUpdateAttemptStatus +{ + Pending = 0, + SnapshotReserved = 1, + SnapshotBound = 2, + HealthyConfirmed = 3, + RecoveryCompleted = 4 +} + +public enum DurableUpdateAttemptCompletion +{ + HealthyConfirmed = 1, + RecoveryCompleted = 2 +} + +public sealed class DurableUpdateAttemptRecord +{ + internal DurableUpdateAttemptRecord(Guid attemptId, DurableUpdateAttemptStatus status, string? snapshotPath, long fence, Guid? claimId) + { + AttemptId = attemptId; + Status = status; + SnapshotPath = snapshotPath; + Fence = fence; + ClaimId = claimId; + } + + public Guid AttemptId { get; } + public DurableUpdateAttemptStatus Status { get; } + public string? SnapshotPath { get; } + public long Fence { get; } + public Guid? ClaimId { get; } +} + +public sealed class DurableUpdateAttemptClaim +{ + internal DurableUpdateAttemptClaim(Guid attemptId, long fence, Guid claimId) + { + AttemptId = attemptId; + Fence = fence; + ClaimId = claimId; + } + + public Guid AttemptId { get; } + public long Fence { get; } + public Guid ClaimId { get; } +} diff --git a/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs b/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs index bf60a66f..496ebe4e 100644 --- a/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs @@ -509,6 +509,12 @@ private string ResolveUpdateDir() /// private void TryRollback() { + if (_configinfo.DisableLegacyRollback) + { + GeneralTracer.Warn("AbstractStrategy.TryRollback: skipped because this durable attempt suppresses legacy automatic rollback."); + return; + } + try { var backupDir = _configinfo.BackupDirectory; diff --git a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs index 7d3c87ea..8ebf82cf 100644 --- a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs @@ -13,6 +13,7 @@ using GeneralUpdate.Core.Ipc; using GeneralUpdate.Core.Pipeline; using GeneralUpdate.Core.Utilities; +using GeneralUpdate.Core.StartupHealth; namespace GeneralUpdate.Core.Strategy; @@ -543,6 +544,19 @@ private async Task ExecuteStandardWorkflowAsync() _configInfo.TempPath = StorageManager.GetTempDirectory("main_temp"); _configInfo.BackupDirectory = Path.Combine(_configInfo.InstallPath, StorageManager.BackupRootDirectory, StorageManager.GetBackupDirectoryName()); + var attemptStore = (DurableUpdateAttemptStore?)null; + if (_configInfo.DurableUpdateAttemptId.HasValue) + { + if (_configInfo.DurableUpdateAttemptId.Value == Guid.Empty) + throw new InvalidOperationException("DurableUpdateAttemptId must be non-empty."); + if (_configInfo.BackupEnabled == false) + throw new InvalidOperationException("A durable update attempt requires backups to be enabled."); + + _configInfo.BackupDirectory += "-" + _configInfo.DurableUpdateAttemptId.Value.ToString("N"); + _configInfo.DisableLegacyRollback = true; + _configInfo.AttemptJournalDirectory = DurableUpdateAttemptStore.GetDirectory(_configInfo.InstallPath); + attemptStore = new DurableUpdateAttemptStore(_configInfo.InstallPath); + } // Check failed version if (!string.IsNullOrEmpty(_configInfo.LastVersion) && CheckFail(_configInfo.LastVersion)) @@ -552,10 +566,22 @@ private async Task ExecuteStandardWorkflowAsync() return; } + // Create the durable attempt and reserve its exact snapshot before copying begins. + // The reservation also protects a partially-created path from concurrent retention. + if (attemptStore != null) + { + var attemptId = _configInfo.DurableUpdateAttemptId!.Value; + attemptStore.Begin(attemptId); + attemptStore.ReserveSnapshot(attemptId, _configInfo.BackupDirectory); + } + // Backup — conditionally skipped when BackupEnabled is false if (_configInfo.BackupEnabled != false) { Backup(); + if (attemptStore != null) + attemptStore.BindSnapshot(_configInfo.DurableUpdateAttemptId!.Value, _configInfo.BackupDirectory); + StorageManager.CleanBackup(_configInfo.InstallPath, keepVersions: 3); } else { @@ -894,9 +920,8 @@ private void Backup() GeneralTracer.Info( $"ClientStrategy: backing up {_configInfo!.InstallPath} -> {_configInfo.BackupDirectory}"); StorageManager.Backup(_configInfo.InstallPath, _configInfo.BackupDirectory, - _configInfo.Directories ?? BlackDefaults.DefaultDirectories); - // Retain only the most recent 3 backups to prevent disk accumulation - StorageManager.CleanBackup(_configInfo.InstallPath, keepVersions: 3); + _configInfo.Directories ?? BlackDefaults.DefaultDirectories, + createOnly: _configInfo.DurableUpdateAttemptId.HasValue); } /// diff --git a/tests/BowlTest/BowlContextTests.cs b/tests/BowlTest/BowlContextTests.cs index c21d4b72..99c8a918 100644 --- a/tests/BowlTest/BowlContextTests.cs +++ b/tests/BowlTest/BowlContextTests.cs @@ -227,6 +227,21 @@ public void Normalize_AutoRestore为false_保留false() Assert.False(result.AutoRestore); } + [Fact] + public void Normalize_持久化attempt存在时禁用AutoRestore() + { + var ctx = new BowlContext + { + AutoRestore = true, + DurableUpdateAttemptId = Guid.NewGuid() + }; + + var result = ctx.Normalize(); + + Assert.False(result.AutoRestore); + Assert.Equal(ctx.DurableUpdateAttemptId, result.DurableUpdateAttemptId); + } + [Fact] public void Normalize_OnCrash回调_正确传递() { diff --git a/tests/BowlTest/Integration/BowlCrashPipelineTests.cs b/tests/BowlTest/Integration/BowlCrashPipelineTests.cs index 4397e7dd..796373c0 100644 --- a/tests/BowlTest/Integration/BowlCrashPipelineTests.cs +++ b/tests/BowlTest/Integration/BowlCrashPipelineTests.cs @@ -213,6 +213,40 @@ public async Task SimulatedCrash_NormalMode_DoesNotRestore() Assert.True(File.Exists(dumpPath)); } + [Fact] + public async Task SimulatedCrash_DurableAttemptSuppressesLegacyAutoRestore() + { + var installPath = Path.Combine(_testBasePath, "DurableAttemptApp"); + var backupDir = Path.Combine(installPath, "backup"); + var failDir = Path.Combine(installPath, "fail", "5.0.0"); + var dumpPath = Path.Combine(failDir, "5.0.0_fail.dmp"); + Directory.CreateDirectory(backupDir); + File.WriteAllText(Path.Combine(installPath, "app.txt"), "current"); + File.WriteAllText(Path.Combine(backupDir, "app.txt"), "backup"); + + var context = new BowlContext + { + ProcessNameOrId = "DurableAttemptApp.exe", + DumpFileName = "5.0.0_fail.dmp", + FailFileName = "5.0.0_fail.json", + TargetPath = installPath, + FailDirectory = failDir, + BackupDirectory = backupDir, + WorkModel = "Upgrade", + ExtendedField = "5.0.0", + TimeoutMs = 5_000, + AutoRestore = true, + DurableUpdateAttemptId = Guid.NewGuid(), + }; + + var bowl = CreateBowl(new MockCrashStrategy(dumpPath, new[] { "Dump written." })); + var result = await bowl.LaunchAsync(context); + + Assert.True(result.DumpCaptured); + Assert.False(result.Restored); + Assert.Equal("current", File.ReadAllText(Path.Combine(installPath, "app.txt"))); + } + /// /// Verifies that when no dump is produced, the pipeline returns success /// and does NOT create a crash report. diff --git a/tests/CoreTest/Configuration/UpdateRequestBuilderTests.cs b/tests/CoreTest/Configuration/UpdateRequestBuilderTests.cs index 3e81c1cd..8acb6408 100644 --- a/tests/CoreTest/Configuration/UpdateRequestBuilderTests.cs +++ b/tests/CoreTest/Configuration/UpdateRequestBuilderTests.cs @@ -4,6 +4,21 @@ namespace CoreTest.Configuration; public class UpdateRequestBuilderTests { + [Fact] + public void SetDurableUpdateAttemptId_IsOptInAndPreservedByBuild() + { + var id = Guid.NewGuid(); + var request = new UpdateRequestBuilder() + .SetUpdateUrl("https://api.example.com") + .SetAppSecretKey("test-key") + .SetDurableUpdateAttemptId(id) + .Build(); + + Assert.Equal(id, request.DurableUpdateAttemptId); + Assert.Throws(() => new UpdateRequestBuilder().SetDurableUpdateAttemptId(Guid.Empty)); + Assert.Null(new UpdateRequest().DurableUpdateAttemptId); + } + #region SetXxx — Null/Empty Validation [Theory] diff --git a/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs b/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs new file mode 100644 index 00000000..9ae2028c --- /dev/null +++ b/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs @@ -0,0 +1,308 @@ +using System.Diagnostics; +using System.Text; +using System.Text.Json; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.Download.Abstractions; +using GeneralUpdate.Core.Download.Models; +using GeneralUpdate.Core.Event; +using GeneralUpdate.Core.FileSystem; +using GeneralUpdate.Core.JsonContext; +using GeneralUpdate.Core.StartupHealth; +using GeneralUpdate.Core.Strategy; +using Moq; + +namespace CoreTest.StartupHealth; + +[Collection("NonParallel_EventManager")] +public sealed class DurableUpdateAttemptStoreTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "durable-update-attempt-" + Guid.NewGuid().ToString("N")); + + [Fact] + public void Attempt_metadata_is_opt_in_and_round_trips_through_the_process_contract() + { + var legacyRequest = new UpdateRequest(); + Assert.Null(legacyRequest.DurableUpdateAttemptId); + var legacyContract = new ProcessContract(); + Assert.Null(legacyContract.DurableUpdateAttemptId); + Assert.Null(legacyContract.AttemptJournalDirectory); + Assert.False(legacyContract.DisableLegacyRollback); + + Directory.CreateDirectory(_root); + var attemptId = Guid.NewGuid(); + var source = new UpdateContext + { + MainAppName = "App.exe", + InstallPath = _root, + ClientVersion = "1.0.0", + LastVersion = "2.0.0", + AppSecretKey = "test-key", + BackupDirectory = Path.Combine(_root, ".backups", "backup-test-" + attemptId.ToString("N")), + TempPath = _root, + Encoding = Encoding.UTF8, + Format = Format.Zip, + DurableUpdateAttemptId = attemptId + }; + + var contract = ConfigurationMapper.MapToProcessContract( + source, new List { new() { Version = "2.0.0" } }, + new List(), new List(), new List()); + var json = JsonSerializer.Serialize(contract, ProcessContractJsonContext.Default.ProcessContract); + var reopened = JsonSerializer.Deserialize(json, ProcessContractJsonContext.Default.ProcessContract)!; + + Assert.Equal(attemptId, reopened.DurableUpdateAttemptId); + Assert.Equal(DurableUpdateAttemptStore.GetDirectory(_root), reopened.AttemptJournalDirectory); + Assert.True(reopened.DisableLegacyRollback); + Assert.Equal(attemptId, ConfigurationMapper.MapToUpdateContext(new UpdateRequest + { + DurableUpdateAttemptId = attemptId + }).DurableUpdateAttemptId); + } + + [Fact] + public void Legacy_backup_cleanup_does_not_create_attempt_journal_metadata() + { + var installPath = Path.Combine(_root, "install"); + Directory.CreateDirectory(Path.Combine(installPath, StorageManager.BackupRootDirectory)); + + StorageManager.CleanBackup(installPath); + + Assert.False(Directory.Exists(DurableUpdateAttemptStore.GetDirectory(installPath))); + } + + [Fact] + public void Real_backup_is_bound_to_its_reserved_path_and_retention_keeps_the_pin() + { + var installPath = Path.Combine(_root, "install"); + var sourcePath = Path.Combine(_root, "source"); + Directory.CreateDirectory(installPath); + Directory.CreateDirectory(sourcePath); + File.WriteAllText(Path.Combine(sourcePath, "state.txt"), "snapshot"); + var attemptId = Guid.NewGuid(); + var snapshotPath = Path.Combine(installPath, StorageManager.BackupRootDirectory, + "backup-old-" + attemptId.ToString("N")); + var store = new DurableUpdateAttemptStore(installPath); + store.Begin(attemptId); + store.ReserveSnapshot(attemptId, snapshotPath); + StorageManager.Backup(sourcePath, snapshotPath, Array.Empty(), createOnly: true); + store.BindSnapshot(attemptId, snapshotPath); + + for (var index = 0; index < 3; index++) + { + var other = Path.Combine(installPath, StorageManager.BackupRootDirectory, $"backup-new-{index}"); + Directory.CreateDirectory(other); + } + + StorageManager.CleanBackup(installPath, keepVersions: 1); + + Assert.Equal(DurableUpdateAttemptStatus.SnapshotBound, store.GetAttempt(attemptId).Status); + Assert.Equal(Path.GetFullPath(snapshotPath), Path.GetFullPath(store.GetAttempt(attemptId).SnapshotPath!)); + Assert.Equal("snapshot", File.ReadAllText(Path.Combine(snapshotPath, "state.txt"))); + Assert.DoesNotContain(DurableUpdateAttemptStore.GetDirectory(installPath), StorageManager.GetLatestBackup(installPath)); + } + + [Fact] + public void Attempt_specific_backup_never_deletes_an_existing_destination() + { + var sourcePath = Path.Combine(_root, "source"); + var snapshotPath = Path.Combine(_root, ".backups", "backup-unique-attempt"); + Directory.CreateDirectory(sourcePath); + Directory.CreateDirectory(snapshotPath); + File.WriteAllText(Path.Combine(sourcePath, "file.txt"), "new"); + File.WriteAllText(Path.Combine(snapshotPath, "file.txt"), "existing"); + + Assert.Throws(() => + StorageManager.Backup(sourcePath, snapshotPath, Array.Empty(), createOnly: true)); + + Assert.Equal("existing", File.ReadAllText(Path.Combine(snapshotPath, "file.txt"))); + } + + [Fact] + public async Task Client_strategy_creates_and_binds_the_backup_used_by_its_update_workflow() + { + var installPath = Path.Combine(_root, "install"); + Directory.CreateDirectory(installPath); + File.WriteAllText(Path.Combine(installPath, "app-state.txt"), "before-update"); + var attemptId = Guid.NewGuid(); + var asset = new DownloadAsset("client.zip", "https://example.test/client.zip", 10, null, "2.0.0", + AppType: (int)AppType.Client); + var source = new Mock(); + source.Setup(s => s.ListAsync(It.IsAny())) + .ReturnsAsync(new DownloadSourceResult { Assets = new[] { asset }, HasMainUpdate = true }); + var executor = new Mock(); + executor.Setup(e => e.ExecuteAsync(It.IsAny(), It.IsAny(), + It.IsAny>(), It.IsAny())) + .Returns((DownloadAsset download, string path, IProgress? _, CancellationToken _) => + Task.FromResult(new DownloadResult(download, path, 10, TimeSpan.Zero, 0, true, null))); + + var strategy = new ClientStrategy + { + DownloadSource = source.Object, + LaunchAfterPrepare = false + }; + strategy.SetOsStrategy(Mock.Of()); + strategy.SetDownloadExecutor(executor.Object); + strategy.Create(new UpdateContext + { + UpdateUrl = "https://example.test/update", + ClientVersion = "1.0.0", + AppSecretKey = "test-key", + MainAppName = "App.exe", + InstallPath = installPath, + Encoding = Encoding.UTF8, + DurableUpdateAttemptId = attemptId + }); + + try + { + await strategy.ExecuteAsync(); + Assert.True(strategy.HasPreparedClientUpdate); + var attempt = new DurableUpdateAttemptStore(installPath).GetAttempt(attemptId); + Assert.Equal(DurableUpdateAttemptStatus.SnapshotBound, attempt.Status); + Assert.NotNull(attempt.SnapshotPath); + Assert.Contains(attemptId.ToString("N"), Path.GetFileName(attempt.SnapshotPath)); + Assert.Equal("before-update", File.ReadAllText(Path.Combine(attempt.SnapshotPath, "app-state.txt"))); + } + finally + { + EventManager.Instance.Clear(); + } + } + + [Fact] + public void Competing_process_claims_are_fenced_and_stale_claim_cannot_complete() + { + var installPath = Path.Combine(_root, "install"); + var sourcePath = Path.Combine(_root, "source"); + Directory.CreateDirectory(installPath); + Directory.CreateDirectory(sourcePath); + File.WriteAllText(Path.Combine(sourcePath, "file.txt"), "data"); + var store = CreateBoundAttempt(installPath, sourcePath, out var attemptId); + + using var first = StartProbe("attempt-claim", installPath, attemptId.ToString(), "0"); + using var second = StartProbe("attempt-claim", installPath, attemptId.ToString(), "0"); + var firstOutput = Finish(first); + var secondOutput = Finish(second); + Assert.Contains("claimed", firstOutput + "|" + secondOutput); + Assert.Contains("stale", firstOutput + "|" + secondOutput); + + var firstClaim = store.ClaimRecovery(attemptId, 1); + var replacement = store.ClaimRecovery(attemptId, 2); + Assert.Throws(() => + store.Complete(attemptId, firstClaim, DurableUpdateAttemptCompletion.RecoveryCompleted)); + Assert.True(store.Complete(attemptId, replacement, DurableUpdateAttemptCompletion.RecoveryCompleted)); + Assert.False(store.Complete(attemptId, replacement, DurableUpdateAttemptCompletion.HealthyConfirmed)); + Assert.Equal(DurableUpdateAttemptStatus.RecoveryCompleted, store.GetAttempt(attemptId).Status); + } + + [Fact] + public void A_killed_writer_can_be_reopened_by_a_new_process_with_the_exact_snapshot_path() + { + var installPath = Path.Combine(_root, "install"); + var sourcePath = Path.Combine(_root, "source"); + Directory.CreateDirectory(installPath); + Directory.CreateDirectory(sourcePath); + File.WriteAllText(Path.Combine(sourcePath, "file.txt"), "durable"); + var attemptId = Guid.NewGuid(); + var readyPath = Path.Combine(_root, "ready"); + using var writer = StartProbe("attempt-bind-hold", installPath, attemptId.ToString(), sourcePath, readyPath); + try + { + Assert.True(SpinWait.SpinUntil(() => File.Exists(readyPath) || writer.HasExited, TimeSpan.FromSeconds(15))); + Assert.True(File.Exists(readyPath), "The writer exited before binding its snapshot."); + writer.Kill(); + Assert.True(writer.WaitForExit(15000)); + + var output = RunProbe("attempt-read", installPath, attemptId.ToString()); + var fields = output.Split('|'); + Assert.Equal(nameof(DurableUpdateAttemptStatus.SnapshotBound), fields[0]); + Assert.True(Directory.Exists(fields[1])); + Assert.Equal("durable", File.ReadAllText(Path.Combine(fields[1], "file.txt"))); + Assert.Equal("0", fields[2]); + } + finally + { + if (!writer.HasExited) { writer.Kill(); writer.WaitForExit(); } + } + } + + [Fact] + public void Missing_or_corrupt_snapshot_state_fails_closed_without_latest_backup_fallback() + { + var installPath = Path.Combine(_root, "install"); + var sourcePath = Path.Combine(_root, "source"); + Directory.CreateDirectory(installPath); + Directory.CreateDirectory(sourcePath); + File.WriteAllText(Path.Combine(sourcePath, "file.txt"), "data"); + + var store = CreateBoundAttempt(installPath, sourcePath, out var attemptId); + var exactPath = store.GetAttempt(attemptId).SnapshotPath!; + Directory.Delete(exactPath, true); + Assert.Throws(() => store.ClaimRecovery(attemptId, 0)); + Assert.Equal(DurableUpdateAttemptStatus.SnapshotBound, store.GetAttempt(attemptId).Status); + + var another = Guid.NewGuid(); + store.Begin(another); + var missing = Path.Combine(installPath, StorageManager.BackupRootDirectory, "backup-missing-" + another.ToString("N")); + store.ReserveSnapshot(another, missing); + Assert.Throws(() => store.BindSnapshot(another, missing)); + + var statePath = Path.Combine(DurableUpdateAttemptStore.GetDirectory(installPath), attemptId.ToString("N") + ".state"); + File.WriteAllBytes(statePath, new byte[] { 0 }); + Assert.Throws(() => StorageManager.CleanBackup(installPath, keepVersions: 0)); + } + + private DurableUpdateAttemptStore CreateBoundAttempt(string installPath, string sourcePath, out Guid attemptId) + { + attemptId = Guid.NewGuid(); + var snapshotPath = Path.Combine(installPath, StorageManager.BackupRootDirectory, + "backup-" + DateTime.UtcNow.ToString("yyyyMMddHHmmss") + "-" + attemptId.ToString("N")); + var store = new DurableUpdateAttemptStore(installPath); + store.Begin(attemptId); + store.ReserveSnapshot(attemptId, snapshotPath); + StorageManager.Backup(sourcePath, snapshotPath, Array.Empty(), createOnly: true); + store.BindSnapshot(attemptId, snapshotPath); + return store; + } + + private static Process StartProbe(params string[] args) + { + var start = CreateProbeStart(args); + start.RedirectStandardOutput = true; + start.RedirectStandardError = true; + return Process.Start(start) ?? throw new InvalidOperationException("Failed to start durable-attempt probe."); + } + + private static string RunProbe(params string[] args) + { + using var process = StartProbe(args); + return Finish(process); + } + + private static ProcessStartInfo CreateProbeStart(string[] args) + { + var start = new ProcessStartInfo("dotnet") { UseShellExecute = false }; + start.ArgumentList.Add("exec"); + start.ArgumentList.Add("--runtimeconfig"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "CoreTest.runtimeconfig.json")); + start.ArgumentList.Add("--depsfile"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "CoreTest.deps.json")); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "StartupHealthProbe.dll")); + foreach (var arg in args) start.ArgumentList.Add(arg); + return start; + } + + private static string Finish(Process process) + { + Assert.True(process.WaitForExit(15000), "The durable-attempt probe did not exit."); + var stderr = process.StandardError.ReadToEnd(); + Assert.Equal(0, process.ExitCode); + Assert.Empty(stderr); + return process.StandardOutput.ReadToEnd().Trim(); + } + + public void Dispose() + { + if (Directory.Exists(_root)) Directory.Delete(_root, true); + } +} diff --git a/tests/StartupHealthProbe/Program.cs b/tests/StartupHealthProbe/Program.cs index b76992c1..a2d0f7b4 100644 --- a/tests/StartupHealthProbe/Program.cs +++ b/tests/StartupHealthProbe/Program.cs @@ -1,6 +1,46 @@ using GeneralUpdate.Core.StartupHealth; +using GeneralUpdate.Core.FileSystem; using System.Diagnostics; +if (args.Length == 3 && args[0] == "attempt-read") +{ + var record = new DurableUpdateAttemptStore(args[1]).GetAttempt(Guid.Parse(args[2])); + Console.WriteLine($"{record.Status}|{record.SnapshotPath}|{record.Fence}"); + return; +} + +if (args.Length == 4 && args[0] == "attempt-claim") +{ + try + { + var claim = new DurableUpdateAttemptStore(args[1]).ClaimRecovery(Guid.Parse(args[2]), long.Parse(args[3])); + Console.WriteLine($"claimed|{claim.Fence}|{claim.ClaimId}"); + } + catch (InvalidOperationException) + { + Console.WriteLine("stale"); + } + return; +} + +if (args.Length == 5 && args[0] == "attempt-bind-hold") +{ + var installPath = args[1]; + var attemptId = Guid.Parse(args[2]); + var sourcePath = args[3]; + var readyPath = args[4]; + var snapshotPath = Path.Combine(installPath, StorageManager.BackupRootDirectory, + StorageManager.GetBackupDirectoryName() + "-" + attemptId.ToString("N")); + var store = new DurableUpdateAttemptStore(installPath); + store.Begin(attemptId); + store.ReserveSnapshot(attemptId, snapshotPath); + StorageManager.Backup(sourcePath, snapshotPath, Array.Empty(), createOnly: true); + store.BindSnapshot(attemptId, snapshotPath); + File.WriteAllText(readyPath, "bound"); + Thread.Sleep(Timeout.Infinite); + return; +} + if (args.Length == 3 && args[0] == "native-handoff") { var handoff = new StartupHealthHandoff(args[1]); From e92bd9f2fd9572c6fbc6b2423e364e103939b69c Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Mon, 23 Nov 2026 02:17:42 +0800 Subject: [PATCH 2/3] Fail closed durable update readiness reporting Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/durable-update-attempts.md | 76 +++-- .../Bootstrap/GeneralUpdateBootstrap.cs | 25 +- .../FileSystem/StorageManager.cs | 5 +- .../GeneralUpdate.Core.csproj | 4 + .../DurableUpdateAttemptStore.cs | 1 + .../Strategy/AbstractStrategy.cs | 26 +- .../Strategy/ClientStrategy.cs | 25 +- .../Strategy/LinuxStrategy.cs | 2 +- .../Strategy/MacStrategy.cs | 2 +- .../Strategy/OssStrategy.cs | 15 + .../Strategy/UpdateStrategy.cs | 20 ++ .../Strategy/WindowsStrategy.cs | 2 +- .../CoreTest/FileSystem/BackupRestoreTests.cs | 34 ++ .../DurableUpdateAttemptStoreTests.cs | 296 +++++++++++++++++- tests/StartupHealthProbe/Program.cs | 57 ++++ 15 files changed, 544 insertions(+), 46 deletions(-) diff --git a/docs/durable-update-attempts.md b/docs/durable-update-attempts.md index 3e8bfd87..9138b5c9 100644 --- a/docs/durable-update-attempts.md +++ b/docs/durable-update-attempts.md @@ -1,5 +1,12 @@ # Durable update attempts and exact backup binding +> **Not deployable yet.** This opt-in protocol is still a draft. It suppresses +> success reports and rejects configured Bowl/custom-strategy paths, but cannot +> prove that an arbitrary pre-existing updater executable understands the +> required-attempt environment marker. Do not enable it in production until a +> versioned producer/consumer handshake and real recovery owner are implemented +> and validated. + This layer is opt-in. The caller supplies and durably retains a unique, non-empty `DurableUpdateAttemptId` before starting an update: @@ -23,12 +30,16 @@ the durable attempt under `{InstallPath}/.backups/.attempts`, and reserves an attempt-specific backup path before copying. The path includes the attempt ID rather than relying on the legacy one-second timestamp alone. The backup is copied to a fresh staging -directory and published with a non-overwriting directory move. Only after that -copy succeeds is the exact path bound into the journal and passed in -`ProcessContract`, together with the attempt ID, journal directory, and -`DisableLegacyRollback=true`. The executing Core bootstrap reopens the record -and rejects an absent, corrupt, unbound, mismatched, or missing snapshot rather -than using `GetLatestBackup`. +directory and published with a non-overwriting directory move. Only after that copy succeeds is the exact path bound into the journal and +passed in `ProcessContract`, together with the attempt ID, journal directory, +and `DisableLegacyRollback=true`. The built-in launcher also supplies the +attempt ID in the `GENERALUPDATE_REQUIRED_DURABLE_ATTEMPT_ID` child-process +environment. A matching current Core bootstrap rejects missing, unreadable, +corrupt, or mismatched IPC rather than silently continuing in legacy mode, and +reopens the journal record to validate the exact bound snapshot. This detects a +lost contract only when the child is running a consumer that implements this +marker. An older or unrelated executable can ignore it; there is no version +handshake proving which consumer was launched. The attempt journal uses atomic state-file publication and an OS-released cross-process lock. `CleanBackup` takes the same lock while reading pins and @@ -58,29 +69,38 @@ prior claimant is no longer authorized. No `RecoveryOwner` is designated here. business readiness or restore files. For opted-in attempts, Core's legacy `AbstractStrategy.TryRollback` is -suppressed, and `BowlContext.Normalize` suppresses `AutoRestore` when the -attempt ID is propagated to that context. The process contract carries -`DisableLegacyRollback` for cooperating consumers. However, the current -GeneralUpdate producer does not construct Bowl.Host requests or pass this field -into an external Host; Bowl.Host's separate `AutoRollback` setting is not wired -or verified here. Keep Bowl/Host automatic rollback disabled for this mode. -The installed Bowl.Host PR #3 Recovery implementation is fail-closed and is -not a production recovery owner; its Controlled* prototypes and fixtures are -not enabled by this layer. No automatic restore is enabled. +suppressed, and success reports from ClientStrategy, AbstractStrategy, +UpdateStrategy, and OssStrategy are suppressed; failure reports remain enabled. +This intentionally reports no success until a future application-owned +readiness protocol exists. The built-in Client and Upgrade paths reject a +non-empty Bowl setting and a custom OS strategy before backup or file +application; an IPC contract containing a Bowl executable is also rejected. +The OSS workflow is not part of this protocol and rejects durable-attempt +requests. +`BowlContext.Normalize` only disables `AutoRestore` when an external caller +explicitly supplies an attempt ID; Core does not currently map its IPC contract +into an externally launched Bowl process. This PR therefore does not claim +that Bowl/Host rollback is disabled in an arbitrary deployed process tree. +External startup scripts, old binaries, and other writers can ignore the +marker or perform their own rollback and must not participate. Bowl/Host +automatic recovery must remain disabled. The Bowl.Host PR #3 Recovery +implementation is fail-closed and is not a production recovery owner; its +Controlled* prototypes and fixtures are not enabled by this layer. No automatic +restore is enabled. This is not a recovery or health closure. The updater does not recover after a crash, select a recovery owner, make recovery idempotent, or report application -readiness. Process survival, Bowl `filesOnly`/`processAlive`, and successful -file application are not business health. The attempt remains pinned until an -authorized cooperating caller records an externally established terminal -outcome. +readiness. Durable-mode `Success` reports are intentionally omitted rather than +relabeling file application as health. Process survival, Bowl +`filesOnly`/`processAlive`, and successful file application are not business +health. The attempt remains pinned until an authorized cooperating caller +records an externally established terminal outcome. -The reporting changes from GeneralUpdate #541 concern report routing and -phase timing; they do not make a report a business-readiness signal. On the -#549 base, the MainOnly client path can report applied immediately before it -launches the upgrade process; #541 removes that particular early report. In -either version, execution-side package-application success still does not prove -that the updated application launched or passed its own readiness checks. A -future Bowl/Host integration must consume the attempt contract, keep -`AutoRollback=false` until a single real recovery owner is implemented and -fenced, and report health only after application-owned readiness confirmation. +GeneralUpdate #541 changes report routing and phase timing, but does not create +a business-readiness signal. This layer suppresses both the #549 MainOnly +pre-launch applied report and execution-side package-application success for +durable attempts, including every package role. A future Bowl/Host integration +must establish a versioned required-attempt handshake, consume the attempt +contract, keep `AutoRollback=false` until a single real recovery owner is +implemented and fenced, and report health only after application-owned +readiness confirmation. diff --git a/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs b/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs index 839bd858..532f2dc5 100644 --- a/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs +++ b/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs @@ -127,6 +127,9 @@ public override async Task LaunchAsync() { var appType = GetOption(Option.AppType); _configInfo.AppType = appType; + if (_configInfo.DurableUpdateAttemptId.HasValue && + appType != AppType.Client && appType != AppType.Upgrade) + throw new InvalidOperationException("Durable update attempts are supported only by the built-in Client/Upgrade workflows."); // Silent mode: start background poll and return immediately if (appType == AppType.Client && GetOption(Option.Silent)) @@ -357,6 +360,16 @@ public GeneralUpdateBootstrap AddListenerUpdatePrecheck(Func for paths that must be unique. /// /// - public static void Backup(string sourcePath, string backupPath, IReadOnlyList directoryNames, bool createOnly = false) + public static void Backup(string sourcePath, string backupPath, IReadOnlyList directoryNames) + => Backup(sourcePath, backupPath, directoryNames, createOnly: false); + + public static void Backup(string sourcePath, string backupPath, IReadOnlyList directoryNames, bool createOnly) { // Merge default backup-exclusion prefixes with user-configured directories. // This ensures backup/legacy directories are ALWAYS skipped, preventing diff --git a/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj b/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj index e6161552..4758cfe4 100644 --- a/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj +++ b/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj @@ -43,6 +43,10 @@ + + + + True diff --git a/src/GeneralUpdate.Core/StartupHealth/DurableUpdateAttemptStore.cs b/src/GeneralUpdate.Core/StartupHealth/DurableUpdateAttemptStore.cs index 56144528..4eaa68a5 100644 --- a/src/GeneralUpdate.Core/StartupHealth/DurableUpdateAttemptStore.cs +++ b/src/GeneralUpdate.Core/StartupHealth/DurableUpdateAttemptStore.cs @@ -14,6 +14,7 @@ namespace GeneralUpdate.Core.StartupHealth; public sealed class DurableUpdateAttemptStore { private const int FormatVersion = 1; + public const string RequiredAttemptIdEnvironmentVariable = "GENERALUPDATE_REQUIRED_DURABLE_ATTEMPT_ID"; private readonly string _installPath; private readonly string _directory; diff --git a/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs b/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs index 496ebe4e..39c1598d 100644 --- a/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs @@ -9,6 +9,7 @@ using GeneralUpdate.Core.Pipeline; using GeneralUpdate.Core.Configuration; using GeneralUpdate.Core.Utilities; +using GeneralUpdate.Core.StartupHealth; using GeneralUpdate.Core.Hooks; using IUpdateReporter = GeneralUpdate.Core.Download.Reporting.IUpdateReporter; @@ -87,6 +88,8 @@ public abstract class AbstractStrategy : IStrategy /// public bool LaunchBowl { get; set; } + protected internal Guid? RequiredDurableUpdateAttemptId { get; set; } + /// /// Gets or sets whether to prefer using the update path. When true, /// will first attempt to resolve the application from , @@ -268,7 +271,8 @@ public virtual async Task ExecuteAsync() } finally { - await Reporter.ReportAsync(new UpdateReport(version.RecordId, status, version.AppType ?? 1)); + if (status != ReportType.Success || !_configinfo.DurableUpdateAttemptId.HasValue) + await Reporter.ReportAsync(new UpdateReport(version.RecordId, status, version.AppType ?? 1)); // Delete only this version's zip file — other AppType packages // in TempPath may still be needed by a downstream process. @@ -451,12 +455,30 @@ internal void StartProcess(string appName, bool preferUpdatePath = false) if (string.IsNullOrEmpty(appPath)) throw new FileNotFoundException($"Can't find the app {appName}!"); GeneralTracer.Info($"AbstractStrategy.StartProcess: launching {appPath}"); - using var process = Process.Start(appPath); + using var process = StartProcess(new ProcessStartInfo(appPath) { UseShellExecute = false }); if (process == null) throw new InvalidOperationException($"Failed to start process: {appPath}"); GeneralTracer.Info($"AbstractStrategy.StartProcess: process started (PID: {process.Id})."); } + protected Process? StartProcess(ProcessStartInfo startInfo) + { + if (startInfo == null) throw new ArgumentNullException(nameof(startInfo)); + var inheritedAttemptMarker = Environment.GetEnvironmentVariable( + DurableUpdateAttemptStore.RequiredAttemptIdEnvironmentVariable); + if (!RequiredDurableUpdateAttemptId.HasValue && string.IsNullOrEmpty(inheritedAttemptMarker)) + return Process.Start(startInfo.FileName); + + startInfo.UseShellExecute = false; + startInfo.EnvironmentVariables.Remove(DurableUpdateAttemptStore.RequiredAttemptIdEnvironmentVariable); + if (RequiredDurableUpdateAttemptId.HasValue) + { + startInfo.EnvironmentVariables[DurableUpdateAttemptStore.RequiredAttemptIdEnvironmentVariable] = + RequiredDurableUpdateAttemptId.Value.ToString("D"); + } + return Process.Start(startInfo); + } + /// /// Resolves the target application path for the update package. Determines whether to use the update path or install path /// based on the version's application type. diff --git a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs index 8ebf82cf..688ae2ae 100644 --- a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs @@ -14,6 +14,7 @@ using GeneralUpdate.Core.Pipeline; using GeneralUpdate.Core.Utilities; using GeneralUpdate.Core.StartupHealth; +using GeneralUpdate.Core.Ipc; namespace GeneralUpdate.Core.Strategy; @@ -75,6 +76,7 @@ public class ClientStrategy : IStrategy private int _mainRecordId; private int _upgradeRecordId; private int _reportType = 1; // 1=Upgrade(active poll), 2=Push(SignalR push) + internal EncryptedFileProcessContractProvider? ProcessContractProvider { get; set; } /// /// When false, skips in MainOnly / Both scenarios. @@ -264,6 +266,7 @@ public async Task ExecuteAsync() try { GeneralTracer.Debug("ClientStrategy.ExecuteAsync start."); + EnsureDurableAttemptSupported(); await CallSmallBowlHomeAsync(_configInfo.Bowl); await ExecuteWorkflowAsync(); } @@ -396,6 +399,7 @@ private async Task ExecuteWorkflowAsync() /// private async Task ExecuteStandardWorkflowAsync() { + EnsureDurableAttemptSupported(); GeneralTracer.Info( $"ClientStrategy: validating client={_configInfo!.ClientVersion}, upgrade={_configInfo.UpgradeClientVersion}"); @@ -788,7 +792,7 @@ private void SendProcessIpc(List clientVersions) _configInfo.ProcessContract = JsonSerializer.Serialize(processInfo, ProcessContractJsonContext.Default.ProcessContract); - new EncryptedFileProcessContractProvider().Send(processInfo); + (ProcessContractProvider ?? new EncryptedFileProcessContractProvider()).Send(processInfo); HasPreparedClientUpdate = true; GeneralTracer.Info("ClientStrategy: ProcessContract sent with MainApp versions only."); } @@ -810,6 +814,7 @@ private async Task LaunchUpgradeProcessAsync() abs.LaunchAppName = _configInfo!.UpdateAppName; abs.LaunchBowl = false; abs.UseUpdatePath = !string.IsNullOrWhiteSpace(_configInfo.UpdatePath); + abs.RequiredDurableUpdateAttemptId = _configInfo.DurableUpdateAttemptId; } GeneralTracer.Info( @@ -847,6 +852,7 @@ internal void LaunchUpgradeProcessSync() abs.LaunchAppName = _configInfo!.UpdateAppName; abs.LaunchBowl = false; abs.UseUpdatePath = !string.IsNullOrWhiteSpace(_configInfo.UpdatePath); + abs.RequiredDurableUpdateAttemptId = _configInfo.DurableUpdateAttemptId; abs.StartProcess(abs.LaunchAppName!, abs.UseUpdatePath); return; } @@ -906,6 +912,17 @@ private void InitBlackPolicy() )); } + private void EnsureDurableAttemptSupported() + { + if (!_configInfo!.DurableUpdateAttemptId.HasValue) return; + if (_configInfo.DurableUpdateAttemptId == Guid.Empty) + throw new InvalidOperationException("DurableUpdateAttemptId must be non-empty."); + if (!string.IsNullOrWhiteSpace(_configInfo.Bowl)) + throw new InvalidOperationException("Durable update attempts cannot run with a configured Bowl process."); + if (_customOsStrategy != null) + throw new InvalidOperationException("Durable update attempts require the built-in OS strategy; custom strategies are not verified."); + } + /// /// Backs up the current installation directory to the specified backup directory for rollback on update failure. /// @@ -1198,6 +1215,12 @@ await Reporter /// The update context. private async Task SafeReportUpdateAppliedAsync(Hooks.HookContext ctx, int recordId) { + if (_configInfo?.DurableUpdateAttemptId.HasValue == true) + { + GeneralTracer.Info("ClientStrategy: success report suppressed until application-owned readiness is confirmed."); + return; + } + try { await Reporter diff --git a/src/GeneralUpdate.Core/Strategy/LinuxStrategy.cs b/src/GeneralUpdate.Core/Strategy/LinuxStrategy.cs index b2b60da2..aa30c7cd 100644 --- a/src/GeneralUpdate.Core/Strategy/LinuxStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/LinuxStrategy.cs @@ -109,7 +109,7 @@ public override async Task StartAppAsync() throw new Exception($"Can't find the app {appName}!"); GeneralTracer.Info($"GeneralUpdate.Core.LinuxStrategy.StartApp: launching app={appPath}"); - using var process = Process.Start(appPath); + using var process = StartProcess(new ProcessStartInfo(appPath) { UseShellExecute = false }); if (process == null) throw new InvalidOperationException($"Failed to start application: {appPath}"); appLaunched = true; diff --git a/src/GeneralUpdate.Core/Strategy/MacStrategy.cs b/src/GeneralUpdate.Core/Strategy/MacStrategy.cs index b3829044..653ba98c 100644 --- a/src/GeneralUpdate.Core/Strategy/MacStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/MacStrategy.cs @@ -75,7 +75,7 @@ public override async Task StartAppAsync() if (!string.IsNullOrEmpty(mainApp) && File.Exists(mainApp)) { GeneralTracer.Info($"MacStrategy.StartApp: launching app={mainApp}"); - using var process = System.Diagnostics.Process.Start(mainApp); + using var process = StartProcess(new System.Diagnostics.ProcessStartInfo(mainApp) { UseShellExecute = false }); if (process == null) throw new InvalidOperationException($"Failed to start application: {mainApp}"); // Do NOT check process.HasExited here — a fast-starting app may diff --git a/src/GeneralUpdate.Core/Strategy/OssStrategy.cs b/src/GeneralUpdate.Core/Strategy/OssStrategy.cs index 04ef6306..a7c145c6 100644 --- a/src/GeneralUpdate.Core/Strategy/OssStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/OssStrategy.cs @@ -150,6 +150,15 @@ public async Task ExecuteAsync() { if (_configInfo == null) throw new InvalidOperationException("OssStrategy not configured. Call Create() first."); + if (_configInfo.DurableUpdateAttemptId.HasValue) + { + var error = new InvalidOperationException( + "Durable update attempts are not supported by the OSS workflow."); + var context = BuildUpdateContext(); + await SafeOnUpdateErrorAsync(context, error).ConfigureAwait(false); + await SafeReportUpdateFailedAsync(context, error).ConfigureAwait(false); + throw error; + } // Fill missing identity fields from generalupdate.manifest.json, // making the manifest the single source of configuration across @@ -647,6 +656,12 @@ private async Task SafeReportUpdateStartedAsync(Hooks.HookContext ctx) /// The update context. private async Task SafeReportUpdateAppliedAsync(Hooks.HookContext ctx) { + if (_configInfo?.DurableUpdateAttemptId.HasValue == true) + { + GeneralTracer.Info("OssStrategy: success report suppressed until application-owned readiness is confirmed."); + return; + } + try { await Reporter.ReportAsync(new Download.Reporting.UpdateReport(0, (int)Download.Reporting.UpdateStatus.Success, 1)).ConfigureAwait(false); diff --git a/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs b/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs index eb2124b2..98b9537e 100644 --- a/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs @@ -98,6 +98,7 @@ public async Task ExecuteAsync() var ctx = BuildUpdateContext(); try { + EnsureDurableAttemptSupported(); GeneralTracer.Debug("UpdateStrategy.ExecuteAsync start."); // Hooks: allow cancellation before applying updates @@ -251,6 +252,12 @@ private async Task SafeOnUpdateErrorAsync(Hooks.HookContext ctx, Exception error private async Task SafeReportUpdateAppliedAsync(Hooks.HookContext ctx) { + if (_configInfo?.DurableUpdateAttemptId.HasValue == true) + { + GeneralTracer.Info("UpdateStrategy: success report suppressed until application-owned readiness is confirmed."); + return; + } + try { var recordId = _configInfo?.UpdateVersions?.FirstOrDefault()?.RecordId ?? 0; @@ -264,6 +271,19 @@ await Reporter } } + private void EnsureDurableAttemptSupported() + { + if (!_configInfo!.DurableUpdateAttemptId.HasValue) return; + if (_configInfo.DurableUpdateAttemptId == Guid.Empty) + throw new InvalidOperationException("DurableUpdateAttemptId must be non-empty."); + if (!_configInfo.DisableLegacyRollback) + throw new InvalidOperationException("A durable update attempt must disable Core legacy rollback."); + if (!string.IsNullOrWhiteSpace(_configInfo.Bowl)) + throw new InvalidOperationException("Durable update attempts cannot run with a configured Bowl process."); + if (_customOsStrategy != null) + throw new InvalidOperationException("Durable update attempts require the built-in OS strategy; custom strategies are not verified."); + } + private async Task SafeReportUpdateFailedAsync(Hooks.HookContext ctx, Exception error) { try diff --git a/src/GeneralUpdate.Core/Strategy/WindowsStrategy.cs b/src/GeneralUpdate.Core/Strategy/WindowsStrategy.cs index 55ef18ed..aace995b 100644 --- a/src/GeneralUpdate.Core/Strategy/WindowsStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/WindowsStrategy.cs @@ -108,7 +108,7 @@ public override async Task StartAppAsync() throw new Exception($"Can't find the app {appName}!"); GeneralTracer.Info($"GeneralUpdate.Core.WindowsStrategy.StartApp: launching app={appPath}"); - using var appProcess = Process.Start(appPath); + using var appProcess = StartProcess(new ProcessStartInfo(appPath) { UseShellExecute = false }); if (appProcess == null) throw new InvalidOperationException($"Failed to start application: {appPath}"); // Do NOT check appProcess.HasExited here — a fast-starting app may diff --git a/tests/CoreTest/FileSystem/BackupRestoreTests.cs b/tests/CoreTest/FileSystem/BackupRestoreTests.cs index 1e8c4c81..db6421e4 100644 --- a/tests/CoreTest/FileSystem/BackupRestoreTests.cs +++ b/tests/CoreTest/FileSystem/BackupRestoreTests.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Linq; +using System.Reflection; using System.Threading; using GeneralUpdate.Core.FileSystem; using Xunit; @@ -9,6 +10,39 @@ namespace CoreTest.Backup; public class BackupRestoreTests { + [Fact] + public void Backup_preserves_the_original_three_parameter_binary_signature() + { + var oldSignature = typeof(StorageManager).GetMethod( + nameof(StorageManager.Backup), + BindingFlags.Public | BindingFlags.Static, + binder: null, + types: new[] { typeof(string), typeof(string), typeof(System.Collections.Generic.IReadOnlyList) }, + modifiers: null); + Assert.NotNull(oldSignature); + + var root = Path.Combine(Path.GetTempPath(), "CoreTest.Backup.Api." + Guid.NewGuid().ToString("N")); + var source = Path.Combine(root, "source"); + var destination = Path.Combine(root, "backup"); + Directory.CreateDirectory(source); + File.WriteAllText(Path.Combine(source, "state.txt"), "legacy"); + try + { + oldSignature!.Invoke(null, new object[] { source, destination, Array.Empty() }); + Assert.Equal("legacy", File.ReadAllText(Path.Combine(destination, "state.txt"))); + Assert.NotNull(typeof(StorageManager).GetMethod( + nameof(StorageManager.Backup), + BindingFlags.Public | BindingFlags.Static, + binder: null, + types: new[] { typeof(string), typeof(string), typeof(System.Collections.Generic.IReadOnlyList), typeof(bool) }, + modifiers: null)); + } + finally + { + if (Directory.Exists(root)) Directory.Delete(root, true); + } + } + [Fact] public void Backup_And_Restore_Roundtrip() { diff --git a/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs b/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs index 9ae2028c..b67456b9 100644 --- a/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs +++ b/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs @@ -1,12 +1,16 @@ using System.Diagnostics; +using System.IO.Compression; using System.Text; using System.Text.Json; using GeneralUpdate.Core.Configuration; using GeneralUpdate.Core.Download.Abstractions; using GeneralUpdate.Core.Download.Models; +using GeneralUpdate.Core.Download.Reporting; using GeneralUpdate.Core.Event; using GeneralUpdate.Core.FileSystem; using GeneralUpdate.Core.JsonContext; +using GeneralUpdate.Core.Ipc; +using GeneralUpdate.Core.Pipeline; using GeneralUpdate.Core.StartupHealth; using GeneralUpdate.Core.Strategy; using Moq; @@ -134,13 +138,19 @@ public async Task Client_strategy_creates_and_binds_the_backup_used_by_its_updat It.IsAny>(), It.IsAny())) .Returns((DownloadAsset download, string path, IProgress? _, CancellationToken _) => Task.FromResult(new DownloadResult(download, path, 10, TimeSpan.Zero, 0, true, null))); + var reports = new List(); + var reporter = new Mock(); + reporter.Setup(r => r.ReportAsync(It.IsAny(), It.IsAny())) + .Callback((report, _) => reports.Add(report)) + .Returns(Task.CompletedTask); var strategy = new ClientStrategy { DownloadSource = source.Object, - LaunchAfterPrepare = false + LaunchAfterPrepare = false, + Reporter = reporter.Object, + ProcessContractProvider = new EncryptedFileProcessContractProvider(Path.Combine(_root, "client-ipc")) }; - strategy.SetOsStrategy(Mock.Of()); strategy.SetDownloadExecutor(executor.Object); strategy.Create(new UpdateContext { @@ -162,6 +172,44 @@ public async Task Client_strategy_creates_and_binds_the_backup_used_by_its_updat Assert.NotNull(attempt.SnapshotPath); Assert.Contains(attemptId.ToString("N"), Path.GetFileName(attempt.SnapshotPath)); Assert.Equal("before-update", File.ReadAllText(Path.Combine(attempt.SnapshotPath, "app-state.txt"))); + Assert.DoesNotContain(reports, report => report.Status == (int)UpdateStatus.Success); + } + finally + { + EventManager.Instance.Clear(); + } + } + + [Fact] + public async Task Durable_client_update_rejects_bowl_before_backup_and_preserves_failure_reporting() + { + var installPath = Path.Combine(_root, "install-with-bowl"); + Directory.CreateDirectory(installPath); + var reports = new List(); + var reporter = new Mock(); + reporter.Setup(r => r.ReportAsync(It.IsAny(), It.IsAny())) + .Callback((report, _) => reports.Add(report)) + .Returns(Task.CompletedTask); + + var strategy = new ClientStrategy { Reporter = reporter.Object }; + strategy.Create(new UpdateContext + { + InstallPath = installPath, + UpdateUrl = "https://example.test/update", + AppSecretKey = "test-key", + DurableUpdateAttemptId = Guid.NewGuid(), + Bowl = "Bowl.exe" + }); + + try + { + await strategy.ExecuteAsync(); + Assert.False(Directory.Exists(DurableUpdateAttemptStore.GetDirectory(installPath))); + Assert.DoesNotContain(Directory.Exists(Path.Combine(installPath, StorageManager.BackupRootDirectory)) + ? Directory.GetDirectories(Path.Combine(installPath, StorageManager.BackupRootDirectory)) + : Array.Empty(), path => Path.GetFileName(path).StartsWith("backup-", StringComparison.Ordinal)); + Assert.Contains(reports, report => report.Status == (int)UpdateStatus.Failure); + Assert.DoesNotContain(reports, report => report.Status == (int)UpdateStatus.Success); } finally { @@ -169,6 +217,163 @@ public async Task Client_strategy_creates_and_binds_the_backup_used_by_its_updat } } + [Fact] + public async Task Durable_pipeline_suppresses_success_for_each_package_role_but_keeps_failure_reports() + { + var tempPath = Path.Combine(_root, "packages"); + Directory.CreateDirectory(tempPath); + var reports = new List(); + var reporter = new Mock(); + reporter.Setup(r => r.ReportAsync(It.IsAny(), It.IsAny())) + .Callback((report, _) => reports.Add(report)) + .Returns(Task.CompletedTask); + var strategy = new ReportOnlyStrategy { Reporter = reporter.Object }; + strategy.Create(new UpdateContext + { + InstallPath = _root, + TempPath = tempPath, + Format = Format.Zip, + Encoding = Encoding.UTF8, + DurableUpdateAttemptId = Guid.NewGuid(), + DisableLegacyRollback = true, + UpdateVersions = new List + { + new() { Name = "client-full", Version = "2.0.0", AppType = (int)AppType.Client, PackageType = (int)PackageType.Full }, + new() { Name = "upgrade-chain", Version = "2.0.0", AppType = (int)AppType.Upgrade, PackageType = (int)PackageType.Chain }, + new() { Name = "client-failure", Version = "2.0.0", AppType = (int)AppType.Client, PackageType = (int)PackageType.Full } + } + }); + + try + { + await strategy.ExecuteAsync(); + Assert.DoesNotContain(reports, report => report.Status == (int)UpdateStatus.Success); + Assert.Contains(reports, report => report.Status == (int)UpdateStatus.Failure); + } + finally + { + EventManager.Instance.Clear(); + } + } + + [Fact] + public async Task Durable_update_strategy_suppresses_its_post_apply_success_report() + { + var reports = new List(); + var reporter = new Mock(); + reporter.Setup(r => r.ReportAsync(It.IsAny(), It.IsAny())) + .Callback((report, _) => reports.Add(report)) + .Returns(Task.CompletedTask); + var strategy = new UpdateStrategy { Reporter = reporter.Object }; + strategy.Create(new UpdateContext + { + InstallPath = _root, + DurableUpdateAttemptId = Guid.NewGuid(), + DisableLegacyRollback = true, + UpdateVersions = new List(), + LaunchClientAfterUpdate = false + }); + + await strategy.ExecuteAsync(); + + Assert.DoesNotContain(reports, report => report.Status == (int)UpdateStatus.Success); + } + + [Fact] + public async Task Legacy_update_strategy_keeps_its_success_report() + { + var reports = new List(); + var reporter = new Mock(); + reporter.Setup(r => r.ReportAsync(It.IsAny(), It.IsAny())) + .Callback((report, _) => reports.Add(report)) + .Returns(Task.CompletedTask); + var strategy = new UpdateStrategy { Reporter = reporter.Object }; + strategy.Create(new UpdateContext + { + InstallPath = _root, + UpdateVersions = new List(), + LaunchClientAfterUpdate = false + }); + + await strategy.ExecuteAsync(); + + Assert.Contains(reports, report => report.Status == (int)UpdateStatus.Success); + } + + [Fact] + public async Task Durable_client_update_rejects_custom_strategy_before_backup() + { + var installPath = Path.Combine(_root, "install-with-custom"); + Directory.CreateDirectory(installPath); + var strategy = new ClientStrategy(); + strategy.SetOsStrategy(Mock.Of()); + strategy.Create(new UpdateContext + { + InstallPath = installPath, + UpdateUrl = "https://example.test/update", + AppSecretKey = "test-key", + DurableUpdateAttemptId = Guid.NewGuid() + }); + + try + { + await strategy.ExecuteAsync(); + Assert.False(Directory.Exists(DurableUpdateAttemptStore.GetDirectory(installPath))); + Assert.False(Directory.Exists(Path.Combine(installPath, StorageManager.BackupRootDirectory))); + } + finally + { + EventManager.Instance.Clear(); + } + } + + [Fact] + public void Child_process_requires_the_matching_attempt_contract_and_rejects_missing_or_corrupt_ipc() + { + var installPath = Path.Combine(_root, "install-ipc"); + var sourcePath = Path.Combine(_root, "source-ipc"); + var tempRoot = Path.Combine(_root, "ipc-temp"); + var ipcDirectory = Path.Combine(tempRoot, "GeneralUpdate", "ipc"); + Directory.CreateDirectory(installPath); + Directory.CreateDirectory(sourcePath); + Directory.CreateDirectory(ipcDirectory); + File.WriteAllText(Path.Combine(sourcePath, "file.txt"), "snapshot"); + using (var archive = ZipFile.Open(Path.Combine(_root, "package.zip"), ZipArchiveMode.Create)) + using (var writer = new StreamWriter(archive.CreateEntry("updated.txt").Open())) + writer.Write("applied-in-child"); + var store = CreateBoundAttempt(installPath, sourcePath, out var attemptId); + var contract = CreateAttemptContract(installPath, attemptId, store.GetAttempt(attemptId).SnapshotPath!); + var provider = new EncryptedFileProcessContractProvider(ipcDirectory); + var ipcPath = EncryptedFileProcessContractProvider.GetDefaultFilePath(ipcDirectory); + + provider.Send(contract); + var validStart = CreateProbeStart("attempt-apply"); + ConfigureProbeTemp(validStart, tempRoot); + using (var child = new ProcessStartStrategy().Launch(validStart, attemptId)) + { + var appliedOutput = Finish(child).Split('|'); + Assert.Equal(attemptId.ToString("D"), appliedOutput[0]); + Assert.DoesNotContain((int)UpdateStatus.Success, appliedOutput[1] + .Split(',', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse)); + Assert.Equal("applied-in-child", File.ReadAllText(Path.Combine(installPath, "updated.txt"))); + } + + File.Delete(ipcPath); + Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId)); + + File.WriteAllBytes(ipcPath, new byte[] { 1, 2, 3, 4 }); + Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId)); + + contract.DurableUpdateAttemptId = Guid.NewGuid(); + provider.Send(contract); + Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId)); + + contract.DurableUpdateAttemptId = attemptId; + contract.Bowl = "Bowl.exe"; + provider.Send(contract); + Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId)); + } + [Fact] public void Competing_process_claims_are_fenced_and_stale_claim_cannot_complete() { @@ -252,6 +457,52 @@ public void Missing_or_corrupt_snapshot_state_fails_closed_without_latest_backup Assert.Throws(() => StorageManager.CleanBackup(installPath, keepVersions: 0)); } + private ProcessContract CreateAttemptContract(string installPath, Guid attemptId, string snapshotPath, string bowl = "") + { + return ConfigurationMapper.MapToProcessContract(new UpdateContext + { + MainAppName = "App.exe", + InstallPath = installPath, + ClientVersion = "1.0.0", + LastVersion = "2.0.0", + AppSecretKey = "test-key", + BackupDirectory = snapshotPath, + TempPath = _root, + Encoding = Encoding.UTF8, + Format = Format.Zip, + PatchEnabled = false, + Bowl = bowl, + DurableUpdateAttemptId = attemptId + }, new List + { + new() + { + Name = "package", + Version = "2.0.0", + Hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData( + File.ReadAllBytes(Path.Combine(_root, "package.zip")))), + AppType = (int)AppType.Client, + PackageType = (int)PackageType.Full + } + }, + BlackDefaults.DefaultFormats, BlackDefaults.DefaultFiles, BlackDefaults.DefaultDirectories); + } + + private static string RunRequiredAttemptProbe(string tempRoot, Guid attemptId) + { + var start = CreateProbeStart("attempt-apply"); + ConfigureProbeTemp(start, tempRoot); + start.EnvironmentVariables[DurableUpdateAttemptStore.RequiredAttemptIdEnvironmentVariable] = attemptId.ToString("D"); + using var process = Process.Start(start) ?? throw new InvalidOperationException("Failed to start required-attempt probe."); + return Finish(process); + } + + private static void ConfigureProbeTemp(ProcessStartInfo start, string tempRoot) + { + start.EnvironmentVariables["TEMP"] = tempRoot; + start.EnvironmentVariables["TMP"] = tempRoot; + } + private DurableUpdateAttemptStore CreateBoundAttempt(string installPath, string sourcePath, out Guid attemptId) { attemptId = Guid.NewGuid(); @@ -273,13 +524,7 @@ private static Process StartProbe(params string[] args) return Process.Start(start) ?? throw new InvalidOperationException("Failed to start durable-attempt probe."); } - private static string RunProbe(params string[] args) - { - using var process = StartProbe(args); - return Finish(process); - } - - private static ProcessStartInfo CreateProbeStart(string[] args) + private static ProcessStartInfo CreateProbeStart(params string[] args) { var start = new ProcessStartInfo("dotnet") { UseShellExecute = false }; start.ArgumentList.Add("exec"); @@ -289,20 +534,51 @@ private static ProcessStartInfo CreateProbeStart(string[] args) start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "CoreTest.deps.json")); start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "StartupHealthProbe.dll")); foreach (var arg in args) start.ArgumentList.Add(arg); + start.RedirectStandardOutput = true; + start.RedirectStandardError = true; return start; } + private static string RunProbe(params string[] args) + { + using var process = StartProbe(args); + return Finish(process); + } + private static string Finish(Process process) { Assert.True(process.WaitForExit(15000), "The durable-attempt probe did not exit."); var stderr = process.StandardError.ReadToEnd(); Assert.Equal(0, process.ExitCode); Assert.Empty(stderr); - return process.StandardOutput.ReadToEnd().Trim(); + return process.StandardOutput.ReadToEnd() + .Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries) + .LastOrDefault()?.Trim() ?? string.Empty; } public void Dispose() { if (Directory.Exists(_root)) Directory.Delete(_root, true); } + + private sealed class ReportOnlyStrategy : AbstractStrategy + { + protected override PipelineBuilder BuildPipeline(PipelineContext context) + { + if (context.Get("ZipFilePath").Contains("client-failure", StringComparison.Ordinal)) + throw new InvalidOperationException("Synthetic package failure."); + return new PipelineBuilder(context); + } + } + + private sealed class ProcessStartStrategy : AbstractStrategy + { + protected override PipelineBuilder BuildPipeline(PipelineContext context) => new(context); + + public Process Launch(ProcessStartInfo startInfo, Guid attemptId) + { + RequiredDurableUpdateAttemptId = attemptId; + return StartProcess(startInfo) ?? throw new InvalidOperationException("Failed to launch process probe."); + } + } } diff --git a/tests/StartupHealthProbe/Program.cs b/tests/StartupHealthProbe/Program.cs index a2d0f7b4..a8741e92 100644 --- a/tests/StartupHealthProbe/Program.cs +++ b/tests/StartupHealthProbe/Program.cs @@ -1,6 +1,50 @@ using GeneralUpdate.Core.StartupHealth; using GeneralUpdate.Core.FileSystem; +using GeneralUpdate.Core; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.Download.Reporting; +using GeneralUpdate.Core.Strategy; using System.Diagnostics; +using System.Reflection; + +if (args.Length == 1 && args[0] == "attempt-contract") +{ + try + { + var bootstrap = new GeneralUpdateBootstrap(); + var context = (UpdateContext)typeof(GeneralUpdateBootstrap) + .GetField("_configInfo", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(bootstrap)!; + Console.WriteLine(context.DurableUpdateAttemptId?.ToString("D") ?? "legacy"); + } + catch (InvalidDataException) + { + Console.WriteLine("rejected"); + } + return; +} + +if (args.Length == 1 && args[0] == "attempt-apply") +{ + try + { + var bootstrap = new GeneralUpdateBootstrap(); + var context = (UpdateContext)typeof(GeneralUpdateBootstrap) + .GetField("_configInfo", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(bootstrap)!; + context.LaunchClientAfterUpdate = false; + var statuses = new List(); + var strategy = new UpdateStrategy { Reporter = new ProbeReporter(statuses) }; + strategy.Create(context); + await strategy.ExecuteAsync(); + Console.WriteLine($"{context.DurableUpdateAttemptId:D}|{string.Join(",", statuses)}"); + } + catch (InvalidDataException) + { + Console.WriteLine("rejected"); + } + return; +} if (args.Length == 3 && args[0] == "attempt-read") { @@ -162,3 +206,16 @@ : store.ReportFailure(id, StartupHealthStatus.Failed); Console.WriteLine(changed ? "changed" : "unchanged"); } + +sealed class ProbeReporter : IUpdateReporter +{ + private readonly List _statuses; + + public ProbeReporter(List statuses) => _statuses = statuses; + + public Task ReportAsync(UpdateReport report, CancellationToken token = default) + { + _statuses.Add(report.Status); + return Task.CompletedTask; + } +} From afc584562b01117c2ed64bbd92a5c42990a798f2 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Mon, 23 Nov 2026 08:20:55 +0800 Subject: [PATCH 3/3] Clarify durable IPC identity and replay trust boundaries Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/durable-update-attempts.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/durable-update-attempts.md b/docs/durable-update-attempts.md index 9138b5c9..091f0422 100644 --- a/docs/durable-update-attempts.md +++ b/docs/durable-update-attempts.md @@ -41,6 +41,22 @@ lost contract only when the child is running a consumer that implements this marker. An older or unrelated executable can ignore it; there is no version handshake proving which consumer was launched. +The existing IPC file is not an authenticated identity channel. Its fixed +AES-CBC key and IV are derived from public implementation constants, and the +contract has no authentication tag or durable consumption nonce. Deleting the +file after reading does not prevent a writer from replaying a contract for an +active attempt. The required-attempt environment marker checks consistency in +the current consumer, not sender authorization. + +`ReportType` and package `RecordId` values travel in the contract, but the +journal does not bind them to an authorized tenant or record identity. There +is no protected tenant/record/attempt context produced for Bowl. A future +diagnostic-case association must establish the authorization source, supported +consumer version, protected channel, persistent replay rejection, and complete +tenant/record/attempt/installation/snapshot binding before treating these +fields as trusted evidence. Adding a snapshot content digest alone cannot +establish that trust. + The attempt journal uses atomic state-file publication and an OS-released cross-process lock. `CleanBackup` takes the same lock while reading pins and deleting candidates. Reserved and bound paths are excluded from retention; a