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
38 changes: 38 additions & 0 deletions .github/workflows/ordered-report-aot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
name: Ordered report Native AOT

on:
pull_request:
workflow_dispatch:

jobs:
publish-and-run:
strategy:
matrix:
include:
- os: windows-latest
rid: win-x64
executable: ReportWorker.exe
- os: ubuntu-latest
rid: linux-x64
executable: ReportWorker
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v6
- uses: actions/setup-dotnet@v5
with:
dotnet-version: '10.0.x'
- name: Test outbox
run: >-
dotnet test tests/CoreTest/CoreTest.csproj -c Release
--filter "FullyQualifiedName~OrderedUpdateReporterTests|FullyQualifiedName~RealFallback_CoveredChainCannotOverwriteFailureOrReportDurableSuccess|FullyQualifiedName~Child_apply_failure_survives_restart_and_replays_exact_ordered_event_over_http|FullyQualifiedName~Child_process_requires_the_matching_attempt_contract"
- name: Publish Native AOT
run: dotnet publish tests/ReportWorker/ReportWorker.csproj -c Release -f net10.0 -r ${{ matrix.rid }} -p:PublishAot=true -p:TargetFrameworks=net10.0 -o aot-out
- name: Run native outbox
shell: pwsh
run: |
$exe = Join-Path $PWD "aot-out" "${{ matrix.executable }}"
$queue = Join-Path $env:RUNNER_TEMP "ordered-aot"
& $exe $queue success
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& $exe $queue success
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
48 changes: 48 additions & 0 deletions .github/workflows/report-integration-regression.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
name: Report integration regression

on:
push:
branches: [justerzhu-persistent-regression-integration]
workflow_dispatch:

permissions:
contents: read

jobs:
report-regression:
name: Report regression (${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [windows-latest, ubuntu-latest]
env:
REPORT_INTEGRATION_MERGE_SHA: 057da130aab3251342d344e2b60a12dcc8be71ef
REPORT_ROUTING_SHA: 623a87ce5112af0dab4d23c457797d23cd419143
FAILURE_STAGE_SHA: 66a9403259235dd19c4602ed17a8c51c4615fba0
PERSISTENT_REPORT_SHA: ad77b50c5125a436ab4d4c8a894f6df7235d95b0
steps:
- name: Checkout fixed integration history
uses: actions/checkout@v6
with:
ref: ${{ github.sha }}
fetch-depth: 0

- name: Verify dependency commits
shell: bash
run: |
test "$(git rev-parse "${REPORT_INTEGRATION_MERGE_SHA}^1")" = "${FAILURE_STAGE_SHA}"
test "$(git rev-parse "${REPORT_INTEGRATION_MERGE_SHA}^2")" = "${PERSISTENT_REPORT_SHA}"
git merge-base --is-ancestor "${REPORT_ROUTING_SHA}" "${REPORT_INTEGRATION_MERGE_SHA}"
git merge-base --is-ancestor "${REPORT_INTEGRATION_MERGE_SHA}" HEAD

- name: Setup .NET
uses: actions/setup-dotnet@v5
with:
dotnet-version: '10.0.x'

- name: Run cross-PR report regressions
run: >-
dotnet test tests/CoreTest/CoreTest.csproj
--configuration Release
--filter "FullyQualifiedName~PersistentUpdateReporterTests|FullyQualifiedName~FailureReportingTests|FullyQualifiedName~ReportRoutingTests"
74 changes: 74 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,80 @@ Special thanks to the authors of the following open source projects for contribu
| 🩺 `generalupdate-troubleshoot` | `/generalupdate-troubleshoot` | 50+ known issues diagnosis |


## Durable update reports (opt-in)

The default `HttpUpdateReporter` remains best-effort. Hosts that need durable reporting
can create and register a `PersistentUpdateReporter`, and must replay it on every
application start (and periodically when connectivity returns):

```csharp
var sender = new HttpUpdateReporter(httpClient, reportUrl);
var reporter = new PersistentUpdateReporter(queueDirectory, sender);
await reporter.ReplayAsync(cancellationToken); // handle and log failures; retry later
bootstrap.UpdateReporter(reporter);
```

Use the same writable, local, private queue directory and endpoint across restarts and
processes, and a separate directory for each endpoint/account. Configure authentication
and register the reporter again in each reporting process, including the upgrade process;
neither the URL nor credentials are stored in the queue. Queue
files contain record IDs and statuses and should be protected and retained by the host.
The host must arrange periodic retries and monitor disk usage, permissions and errors.
`ReportAsync` writes before sending and throws if persistence or delivery fails;
the built-in strategies catch and log reporter exceptions so the update continues.

All statuses are queued to preserve their order, including success after failure.
Delivery stops at the first unconfirmed report: HTTP success alone is insufficient;
the response must also have `code: 200` and `body: true`. This is **at-least-once**,
not exactly-once: a crash or lost response after server acceptance can resend a report,
and the current server may count a repeated failure again. Safe deduplication requires
a server-supported event ID/idempotency contract. Ordering applies only to reporters
sharing this queue, not old clients or independent queues. A report is durable once its
queue file has been flushed and published; failure before that point cannot be recovered.
Storage and filesystem durability depend on the host's filesystem and hardware.
The queue's local file order is not a server sequence or a causal order, and its file
numbering can restart after the queue drains.

### Ordered idempotent reports (separate opt-in)

`OrderedUpdateReporter` uses the GeneralSpace ordered-event protocol, but is **disabled
by default** and separate from the legacy file queue. Enable it only after an operator
confirms the deployed service supports both `eventId` and `sequence`; an ordinary
success response is not evidence because older servers ignore unknown fields.

```csharp
var reporter = new OrderedUpdateReporter(
queueDirectory, httpClient, reportUrl,
namespaceIdentity: "stable-tenant-and-server-database-id",
protocolConfirmed: true);
await reporter.ReplayAsync(cancellationToken);
bootstrap.UpdateReporter(reporter);
```

The host must replay on startup and periodically, monitor errors and storage, and
register the same reporter in each reporting process. It must ensure that **all**
writers for a server database's `(type, recordId)` use this one database on the same
machine and the same exact endpoint and namespace identity; no legacy, independent,
multi-machine or restored-old-copy writers may write those records. The namespace must
identify the tenant and actual server database, not an ephemeral token or hostname.
URLs and credentials are not stored, but a hash binding the exact URL and namespace is
stored to reject accidental reconfiguration. The host must prevent redirects, retargeting,
and authentication changes that could send to a different tenant or database.

The private directory must be on a local filesystem supporting SQLite locking and
durable flushes, with access restricted to trusted processes. Protect the database,
rollback journal, lock file, and backups: report payloads may contain sensitive
diagnostics. SQLite transactionally commits the record counter, GUID, and complete
payload before sending. A lost response or crash replays the same event; a business
conflict or other failure stops replay without deleting it. Keep the database and
counters even when the queue is empty. Deleting, rolling back or cloning the database,
or using network filesystems, invalidates the ordering guarantee. Hardware and filesystem
durability still apply. The SQLite native dependency must be available for the target RID.
Enqueue transactions do not hold the delivery lock during HTTP requests. If delivery
is busy, times out or is cancelled after the transaction commits, `ReportAsync` can
throw while the event remains queued; retry delivery with `ReplayAsync`, not by
submitting a new report. Persistence failures before commit cannot be replayed.

## 🙏 Thanks

<div align="center">
Expand Down
16 changes: 10 additions & 6 deletions docs/core-execution-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,16 +247,16 @@ flowchart TB
UO2 -- Yes --> UO3["OnAfterUpdate 钩子\nReport UpdateApplied"]
UO2 -- No --> UO_FAIL["Report UpdateFailed"]

CS19 -- "MainOnly" --> MO1["SendProcessIpc()\n写加密 IPC 文件\nHasPreparedClientUpdate = true"]
MO1 --> MO2["OnAfterUpdate 钩子\nReport UpdateApplied"]
CS19 -- "MainOnly" --> MO1["SendProcessIpcAsync()\n写加密 IPC 文件\nHasPreparedClientUpdate = true"]
MO1 --> MO2["OnAfterUpdate 钩子\n等待升级进程应用"]
MO2 --> MO3["OnBeforeStartApp 钩子"]
MO3 --> MO4["LaunchUpgradeProcessAsync()\n拉起 Upgrade 进程"]

CS19 -- "Both" --> BOTH1["ApplyUpgradePackagesAsync()\n先原地升级自身"]
BOTH1 --> BOTH2{"AllPackagesSucceeded?"}
BOTH2 -- No --> BOTH_FAIL["中止!\n不发送 IPC\n不拉起 Upgrade\n防止循环更新"]
BOTH2 -- Yes --> BOTH3["OnAfterUpdate 钩子"]
BOTH3 --> BOTH4["SendProcessIpc()"]
BOTH3 --> BOTH4["SendProcessIpcAsync()"]
BOTH4 --> BOTH5["LaunchUpgradeProcessAsync()"]
end
```
Expand Down Expand Up @@ -387,7 +387,7 @@ if (downloadReport.FailedCount > 0)
┌─────────────────────────────────────────────────────────────────┐
│ MainOnly │
│ │
│ SendProcessIpc() │
│ SendProcessIpcAsync() │
│ ↓ │
│ 写 AES 加密 IPC 文件到 %TEMP%/GeneralUpdate/ipc/process_info.enc│
│ ↓ │
Expand All @@ -401,7 +401,7 @@ if (downloadReport.FailedCount > 0)
│ │
│ ApplyUpgradePackagesAsync() ─── 先升级自身 │
│ ↓ 失败则中止 │
│ SendProcessIpc() ─── 再写 IPC │
│ SendProcessIpcAsync() ─── 再写 IPC │
│ ↓ │
│ LaunchUpgradeProcessAsync() ─── 最后拉起 Upgrade 进程 │
└─────────────────────────────────────────────────────────────────┘
Expand Down Expand Up @@ -1116,6 +1116,10 @@ public static void EncryptToFile(byte[] plainBytes, string filePath, byte[] key,
| `LaunchClientAfterUpdate` | `_configInfo.LaunchClientAfterUpdate` | 更新后是否自动启动主程序 | UpdateStrategy |
| `ReportType` | 1 或 2 | 1=主动轮询 2=推送通知 | 上报区分 |

`ReportType` 选择服务器记录表,与包的 `AppType` 无关。下载阶段上报 Updating;主程序暂存后不报告成功,升级进程完成应用后才报告结果。同一批次中共享记录 ID 的包按记录汇总,任何失败优先;角色策略可能重复上报结果,启动抛错时也可能在成功后上报失败。成功仅表示文件应用完成,不代表重启后的健康检查通过。推送上报还需要调用方提供服务器分配的对应推送记录 ID,不能复用轮询记录 ID。

下载及内置管道的失败报告可带 `category`、`phase`、`errorCode` 和 `message`。下载、校验、解压、补丁应用及回滚在明确的执行边界分类;自定义中间件或编排器没有提供阶段时不猜测。上报只包含固定的诊断代码和消息,不包含异常文本、URL、凭据或堆栈;本地事件保留可获得的原始异常和下载资源。回滚失败时先报告原始包失败,再对同一记录报告回滚失败;服务端是否保留两次历史取决于其实现。Chain 回退 Full 时报告所属 Chain 记录,现有 IPC 不携带独立 Full 记录 ID。取消、启动、兼容性及其他无可靠阶段来源的失败不附加阶段诊断;自检不在此流程中。

---

## 10. UpdateStrategy:Upgrade 进程的执行流程
Expand Down Expand Up @@ -1366,7 +1370,7 @@ private void TryRollback()
| 场景判定 | `Strategy/ClientStrategy.cs` | Scenario switch @L452-458 |
| 一次性下载 | `Strategy/ClientStrategy.cs` | `DownloadAndApplyAsync()` @L589-597 |
| 原地升级 Upgrade 包 | `Strategy/ClientStrategy.cs` | `ApplyUpgradePackagesAsync()` @L723-737 |
| IPC 写文件 | `Strategy/ClientStrategy.cs` | `SendProcessIpc()` @L751-765 |
| IPC 写文件 | `Strategy/ClientStrategy.cs` | `SendProcessIpcAsync()` |
| 拉起 Upgrade 进程 | `Strategy/ClientStrategy.cs` | `LaunchUpgradeProcessAsync()` @L777-789 |
| 下载计划构建 | `Download/DownloadPlanBuilder.cs` | `Build()` @L111 |
| Chain vs Full 阈值决策 | `Download/DownloadPlanBuilder.cs` | @L174-196 |
Expand Down
13 changes: 13 additions & 0 deletions docs/durable-update-attempts.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,18 @@ 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.
Such an updater may independently report `Success`; suppression is only
enforced by the participating new Core code, not by the environment marker.

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.
The default file is `%TEMP%/GeneralUpdate/ipc/process_info.enc` on Windows.
It serializes the configured application secret and authentication credentials;
the fixed-key encryption does not protect them from a local reader.

`ReportType` and package `RecordId` values travel in the contract, but the
journal does not bind them to an authorized tenant or record identity. There
Expand Down Expand Up @@ -120,3 +125,11 @@ 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.

The ordered-report outbox is not automatically installed in either process.
Its `ReplayAsync` must be explicitly invoked by a cooperating host at startup
and after connectivity returns. A committed event is not proof of delivery;
if replay fails after enqueue, replay the queue rather than enqueueing the same
report again. Connecting that lifecycle, verifying the updater before handoff,
and establishing a single authorized writer and recovery owner are separate
unfinished work. No automatic recovery or global filesystem fence is enabled.
10 changes: 10 additions & 0 deletions src/GeneralUpdate.Core/Configuration/AbstractBootstrap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,21 @@ protected T GetOption<T>(Option<T>? option)
/// </remarks>
public TBootstrap UpdateReporter<T>() where T : Download.Reporting.IUpdateReporter, new()
{
_instances.Remove(typeof(Download.Reporting.IUpdateReporter));
_extensions[typeof(Download.Reporting.IUpdateReporter)] = typeof(T);
_extensionFactories[typeof(Download.Reporting.IUpdateReporter)] = () => new T();
return (TBootstrap)this;
}

/// <summary>Registers a configured reporter instance for the update workflow.</summary>
public TBootstrap UpdateReporter(Download.Reporting.IUpdateReporter reporter)
{
if (reporter == null) throw new ArgumentNullException(nameof(reporter));
_instances[typeof(Download.Reporting.IUpdateReporter)] = reporter;
_extensions[typeof(Download.Reporting.IUpdateReporter)] = reporter.GetType();
return (TBootstrap)this;
}

/// <summary>
/// Registers a custom OS-level strategy implementation (e.g.,
/// <see cref="Strategy.WindowsStrategy"/>, <see cref="Strategy.LinuxStrategy"/>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,11 @@ public async Task<DownloadResult> ExecuteAsync(
{
GeneralTracer.Error($"HttpDownloadExecutor: download failed '{asset.Url}' -> '{destPath}' after {sw.Elapsed}. {ex.Message}", ex);
sw.Stop();
return new DownloadResult(asset, destPath, existingBytes, sw.Elapsed, retries, false, ex.Message);
return new DownloadResult(asset, destPath, existingBytes, sw.Elapsed, retries, false, ex.Message)
{
Error = ex,
FailureCategory = Reporting.FailureCategory.Download
};
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,11 @@ public async Task<DownloadResult> ExecuteAsync(
{
GeneralTracer.Error($"OssDownloadExecutor: download failed '{asset.Url}' -> '{destPath}' after {sw.Elapsed}. {ex.Message}", ex);
sw.Stop();
return new DownloadResult(asset, destPath, 0, sw.Elapsed, 0, false, ex.Message);
return new DownloadResult(asset, destPath, 0, sw.Elapsed, 0, false, ex.Message)
{
Error = ex,
FailureCategory = Reporting.FailureCategory.Download
};
}
}
}
10 changes: 9 additions & 1 deletion src/GeneralUpdate.Core/Download/Models/DownloadProgress.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using GeneralUpdate.Core.Download.Reporting;

namespace GeneralUpdate.Core.Download.Models;

Expand All @@ -23,4 +24,11 @@ public record DownloadResult(
int RetryCount,
bool Success,
string? ErrorMessage
);
)
{
/// <summary>The original local exception, when available. Never sent to the server.</summary>
public Exception? Error { get; init; }

/// <summary>The known failure category; null when the origin is unknown.</summary>
public FailureCategory? FailureCategory { get; init; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,10 @@ public async Task<DownloadReport> ExecuteAsync(
GeneralTracer.Warn($"DefaultDownloadOrchestrator: semaphore wait timed out (1 min) for '{asset.Name}'. Concurrency={effectiveConcurrency}, ActiveSlots={effectiveConcurrency - sem.CurrentCount}. Skipping asset.");
lock (results)
{
results.Add(new DownloadResult(asset, null, 0, TimeSpan.Zero, 0, false, "Semaphore wait timed out"));
results.Add(new DownloadResult(asset, null, 0, TimeSpan.Zero, 0, false, "Semaphore wait timed out")
{
FailureCategory = Reporting.FailureCategory.Timeout
});
}
return;
}
Expand Down Expand Up @@ -254,7 +257,11 @@ public async Task<DownloadReport> ExecuteAsync(
{
return new DownloadResult(asset, destPath,
downloadResult.DownloadedBytes, downloadResult.Duration,
downloadResult.RetryCount, false, $"SHA256 verification failed: {ex.Message}");
downloadResult.RetryCount, false, $"SHA256 verification failed: {ex.Message}")
{
Error = ex,
FailureCategory = Reporting.FailureCategory.Verify
};
}

return downloadResult;
Expand Down
Loading
Loading