Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 122 additions & 0 deletions docs/durable-update-attempts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# 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:

```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 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 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
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 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. 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.

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.
9 changes: 8 additions & 1 deletion src/GeneralUpdate.Bowl/BowlContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ public readonly record struct BowlContext
/// <summary>When <c>true</c> and <see cref="WorkModel"/> is "Upgrade", restores backup on crash.</summary>
public bool AutoRestore { get; init; }

/// <summary>
/// Durable attempt metadata received from a cooperating updater. When present, automatic
/// restore is suppressed; this does not designate a replacement recovery owner.
/// </summary>
public Guid? DurableUpdateAttemptId { get; init; }

/// <summary>Optional callback invoked when a crash is detected.</summary>
public Func<CrashInfo, CancellationToken, Task>? OnCrash { get; init; }

Expand All @@ -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,
};
}
Expand Down
51 changes: 51 additions & 0 deletions src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -126,6 +127,9 @@ public override async Task<GeneralUpdateBootstrap> 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))
Expand Down Expand Up @@ -356,6 +360,16 @@ public GeneralUpdateBootstrap AddListenerUpdatePrecheck(Func<UpdateInfoEventArgs

private void InitializeFromEnvironment()
{
var requiredAttemptValue = Environment.GetEnvironmentVariable(
DurableUpdateAttemptStore.RequiredAttemptIdEnvironmentVariable);
Guid? requiredAttemptId = null;
if (!string.IsNullOrEmpty(requiredAttemptValue))
{
if (!Guid.TryParse(requiredAttemptValue, out var parsedAttemptId) || parsedAttemptId == Guid.Empty)
throw new InvalidDataException("The required durable update-attempt identity is invalid.");
requiredAttemptId = parsedAttemptId;
}

// Read ProcessContract via AES-encrypted file IPC.
// The Upgrade process is only ever launched by the Client — no IPC means
// there is nothing to do. The Client's manifest.json flows through IPC,
Expand All @@ -367,6 +381,8 @@ private void InitializeFromEnvironment()
}
catch (Exception ex)
{
if (requiredAttemptId.HasValue)
throw new InvalidDataException("The required durable update process contract could not be read.", ex);
// Corrupted / unreadable IPC file (e.g. leftover from a crashed
// previous run, or parallel test execution) — treat as "no IPC data".
GeneralTracer.Warn($"Failed to read IPC process contract: {ex.Message}");
Expand All @@ -375,6 +391,8 @@ private void InitializeFromEnvironment()

if (processInfo == null)
{
if (requiredAttemptId.HasValue)
throw new InvalidDataException("The required durable update process contract is missing or unreadable.");
// Normal when running standalone (no update in progress). A locked IPC file
// also surfaces here as null — the Warn inside IpcEncryption distinguishes it.
GeneralTracer.Debug("InitializeFromEnvironment: no IPC process contract found, nothing to do.");
Expand All @@ -383,6 +401,10 @@ private void InitializeFromEnvironment()

try
{
if (processInfo.DurableUpdateAttemptId.HasValue && !requiredAttemptId.HasValue)
throw new InvalidDataException("A durable update contract requires an out-of-band attempt identity.");
if (requiredAttemptId.HasValue && processInfo.DurableUpdateAttemptId != requiredAttemptId)
throw new InvalidDataException("The update process contract does not match the required durable attempt identity.");
var encoding = !string.IsNullOrEmpty(processInfo.CompressEncoding)
? Encoding.GetEncoding(processInfo.CompressEncoding)
: Encoding.UTF8;
Expand Down Expand Up @@ -411,15 +433,44 @@ 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.");
if (!string.IsNullOrWhiteSpace(processInfo.Bowl))
throw new InvalidDataException("Durable update attempts cannot run with a configured Bowl process.");
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 (requiredAttemptId.HasValue || 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}");
Expand Down
8 changes: 8 additions & 0 deletions src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Text;
using GeneralUpdate.Core.StartupHealth;

namespace GeneralUpdate.Core.Configuration
{
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
}
Expand Down
15 changes: 15 additions & 0 deletions src/GeneralUpdate.Core/Configuration/ProcessContract.cs
Original file line number Diff line number Diff line change
Expand Up @@ -403,5 +403,20 @@ public ProcessContract(string appName
/// </summary>
[JsonPropertyName("ReportType")]
public int ReportType { get; set; } = 1;

/// <summary>Caller-owned durable update-attempt ID; null keeps legacy behavior.</summary>
[JsonPropertyName("DurableUpdateAttemptId")]
public Guid? DurableUpdateAttemptId { get; set; }

/// <summary>Stable local journal directory for the durable update attempt.</summary>
[JsonPropertyName("AttemptJournalDirectory")]
public string? AttemptJournalDirectory { get; set; }

/// <summary>
/// Requests that cooperating consumers suppress their legacy automatic rollback.
/// This is a protocol declaration, not proof that an external consumer honors it.
/// </summary>
[JsonPropertyName("DisableLegacyRollback")]
public bool DisableLegacyRollback { get; set; }
}
}
6 changes: 6 additions & 0 deletions src/GeneralUpdate.Core/Configuration/UpdateConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ namespace GeneralUpdate.Core.Configuration
/// <seealso cref="ProcessContract" />
public abstract class UpdateConfiguration
{
/// <summary>
/// Optional caller-owned durable update-attempt identifier. Null preserves legacy behavior.
/// The caller must persist a non-empty ID and never reuse it.
/// </summary>
public Guid? DurableUpdateAttemptId { get; set; }

/// <summary>
/// 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.
Expand Down
12 changes: 12 additions & 0 deletions src/GeneralUpdate.Core/Configuration/UpdateContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,18 @@ public class UpdateContext : UpdateConfiguration
/// </summary>
public string BackupDirectory { get; set; }

/// <summary>
/// Stable journal directory received by the update process for an opt-in durable attempt.
/// Empty when the legacy update path is in use.
/// </summary>
public string? AttemptJournalDirectory { get; set; }

/// <summary>
/// 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.
/// </summary>
public bool DisableLegacyRollback { get; set; }

// ──────────────────────────────
// Download/Update behavior options (injected from Option)
// ──────────────────────────────
Expand Down
Loading
Loading