Skip to content

fix(hr): gate UpdateFile requests on workspace initialization (spec 050) - #23789

Merged
dr1rrb merged 7 commits into
masterfrom
dev/dr/hr-updatefile-workspace-gate
Jul 21, 2026
Merged

dr1rrb merged 7 commits into
masterfrom
dev/dr/hr-updatefile-workspace-gate

Conversation

@dr1rrb

@dr1rrb dr1rrb commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

GitHub Issue: closes #23787

PR Type:

🐞 Bugfix

What changed? 🚀

The dev-server processed hot-reload UpdateFile requests the moment they arrived, with no dependency on the Roslyn workspace initialization. Since the workspace captures its baseline by reading the solution from disk asynchronously, an update request racing that read was written to disk first — the baseline silently absorbed the edit and it was never emitted as a delta (the running app permanently diverges from the delta engine's baseline until rebuild). A second window existed where the edit landed after the baseline read but before the FileSystemObserver was created, so it was never observed at all. Both windows produce "request acknowledged, change never applied" — most easily hit by design-time tooling issuing updates at application startup.

This PR contains the design spec (specs/050-hotreload-updatefile-workspace-gate/spec.md, marked implemented with implementation notes) and its implementation:

  • IFileUpdater (new, Uno.HotReload/IO): contract extracted from FileUpdater so behavior composes by decoration; the bare FileUpdater keeps its exact semantics for consumers without a Roslyn workspace.
  • WorkspaceGatedFileUpdater (new): decorator holding the whole state machine, driven by HotReloadWorkspaceState (NotConfigured / NoWorkspace / Initializing / Ready / Failed / Disposed):
    • requests received while the workspace is expected but not ready are queued and flushed FIFO once the baseline is captured and the file-system observer is active;
    • strict pass-through when hot reload is IDE-driven (Visual Studio — no workspace, HR active at app start): no gate, no delay;
    • fail-fast with an explicit error when the workspace failed to initialize or the connection is disposed (recovery is a new connection), and after a hard 30 s queue timeout (configurable via the update-file-queue-timeout server configuration) — an expired request is never applied late;
    • rejections populate per-edit Results (FileUpdateResult.NotAvailable) so clients don't mistake them for an empty "no changes" success;
    • diagnostic events (queued/flushed/expired/rejected) relayed as update-* telemetry.
  • ServerHotReloadProcessor: stays a thin message router — it only composes the decorator and reports lifecycle transitions (Initializing before the workspace load, Ready after the FileSystemObserver is constructed, Failed on init failure, Disposed on dispose, NoWorkspace in IDE-driven mode). ProcessUpdateFile is unchanged; repeated ConfigureServer messages only swap the decorated editor, the gate (state + queued requests) survives.

Both message shapes (UpdateFileRequest and the legacy UpdateSingleFileRequest) funnel through the same updater call, so the gate covers them uniformly.

Testing

  • 13 new unit tests (Uno.HotReload.Tests/IO/Given_WorkspaceGatedFileUpdater.cs) covering the state machine in isolation: queue-then-flush ordering, pre-configuration queueing, VS pass-through, workspace failure, sticky terminal states, TTL expiry (incl. no late application), expired entries not blocking live ones, dispose with a non-empty queue, NoWorkspace → Initializing reconfiguration without replay, inner swap while queued, cancellation, gate events. All 87 tests of the project pass.
  • Full DevServer suite (Uno.UI.RemoteControl.DevServer.Tests): 481 passed / 0 failed (2 pre-existing skips).
  • End-to-end integration tests of the race against an in-process dev-server (spec test plan) are follow-up work.

PR Checklist ✅

Copilot AI review requested due to automatic review settings July 16, 2026 14:09
@github-actions

github-actions Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @dr1rrb's task in 2m 53s —— View job


Review complete

  • Gather context and understand request
  • Read spec file
  • Review for correctness, consistency, and completeness
  • Post inline comments for specific findings
  • Post summary

Summary

This is a clean, well-grounded spec. The problem statement is precise (two named failure windows with distinct mechanisms), the state machine is well-scoped, and the decorator pattern correctly separates gating policy from the processor. The fact table (F1–F9) is a strong anchoring device — it makes the design legible without access to the source.

3 findings posted as inline comments:

Severity Finding
Moderate State diagram omits the NoWorkspace → Initializing edge (F6 / R6) — the prose explains it but the diagram is the first thing readers process
Moderate R5 TTL enforcement model is unspecified: timer-based (proactive) vs. lazy (checked at flush) have meaningfully different user-observable behavior and implementation complexity
Moderate Test plan is missing a case for the NoWorkspace → Initializing mode-change transition; test 6 only covers re-entrant same-mode calls

No blocking issues — the spec is correct as a whole and the design decisions are sound. The three findings are clarifications that will prevent implementation divergence; they're all additive (nothing to remove).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a new design spec (spec 050) to document and propose a fix for hot-reload UpdateFile requests racing Roslyn workspace initialization on the dev-server, causing baseline corruption or missed change detection.

Changes:

  • Introduces spec 050 describing the two race windows and their impact on deltas/baseline correctness.
  • Defines a per-connection workspace lifecycle state machine and per-state request handling (queue/flush/pass-through/fail-fast).
  • Proposes implementing gating as a WorkspaceGatedFileUpdater decorator with a server-side queue TTL and a concrete test plan.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@dr1rrb dr1rrb changed the title docs(hr): add spec 050 - gate UpdateFile requests on workspace initialization fix(hr): gate UpdateFile requests on workspace initialization (spec 050) Jul 16, 2026
Copilot AI review requested due to automatic review settings July 16, 2026 19:14
@dr1rrb
dr1rrb marked this pull request as ready for review July 16, 2026 19:14
@github-actions

github-actions Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @dr1rrb's task in 7m 51s —— View job


Review complete

  • Gather context and understand request
  • Read changed files
  • Review WorkspaceGatedFileUpdater.cs (main implementation)
  • Review ServerHotReloadProcessor changes
  • Review test file
  • Review interface and enum files
  • Post inline comments
  • Post summary

Summary

Verdict: fix-first — the state machine, cancellation design, FIFO ordering, and sticky-terminal logic are all correct. Four findings posted as inline comments; the first three share the same root cause and should be addressed together before merge.

4 findings (1 pattern × 3 occurrences, 1 thread-safety):

Severity Finding Location
High External callbacks (onEvent, reporter) invoked after TryTake() but before entry.Complete(), without try/catch. If the callback throws: (a) the entry's TaskCompletionSource is never resolved → caller awaits forever; (b) in DrainAsync, the exception escapes the fire-and-forget task and leaves _draining = true permanently — every subsequent queued request is stuck. DrainAsync line 206; WatchTimeoutAsync line 239; ReportWorkspaceState line 130
Medium _inner field is not volatile. It is written from InitializeProcessor (message-handler thread) and read from DrainAsync (background thread). Without volatile, the JIT is free to use a stale cached value on ARM-based Skia targets (iOS, Android, M-series Mac). WorkspaceGatedFileUpdater.cs line 44

Cross-cutting notes (no blocking issues):

  • The IUpdateFileRequest.Edits passed to Reject() is assumed to be non-default; a default ImmutableArray<FileEdit> would throw in the .Select() call. In practice this is upheld by all current call sites, but request.Edits.IsDefault is worth guarding in the same way FileUpdater guards IsDefaultOrEmpty at the top of its method.
  • The errorMessage variable in SafeNotifyMetadataInitializationFailed (ex?.Message ?? ex?.ToString()) — since Exception.Message is guaranteed non-null, the ?? ex?.ToString() branch is dead code. Minor but worth cleaning up.

Test coverage is solid: the 13 unit tests cover the major state-machine paths, FIFO ordering, TTL expiry, cancellation, and the NoWorkspace → Initializing reconfiguration case (which addresses a gap flagged in the prior spec review). All test assertions use .Should() / AwesomeAssertions directly — no deactivated or [Ignore]d tests.

@github-actions

github-actions Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @dr1rrb's task in 5m 34s —— View job


Review complete

  • Gather context and understand request
  • Read all changed files
  • Review for correctness, async/cancellation discipline, SOLID principles, code style
  • Post inline comments for specific findings
  • Post summary

Summary

The design and state machine are clean: the WorkspaceGatedFileUpdater decorator pattern correctly isolates gating policy from the processor, the FIFO flush ordering is well-reasoned, the TTL expiry races are handled with a lock-free TryTake() claim, and the 13 unit tests give good coverage of the main paths.

3 findings posted as inline comments, all in WorkspaceGatedFileUpdater.cs:

Severity Location Finding
Moderate Line 210 (DrainAsync) _inner field is not volatile and read without a lock on the background drain task while Inner setter can be called concurrently from the message-processing thread — no memory-ordering guarantee
Moderate Line 138 (_ = DrainAsync()) Fire-and-forget drain: if onEvent or reporter delegate throws, _draining is never reset and all future Ready-mode requests queue indefinitely — a try/finally { _draining = false; } closes the gap
Moderate Line 171 (_ = WatchTimeoutAsync(entry)) Fire-and-forget watch: if the method throws after TryTake() succeeds but before entry.Complete(), the TaskCompletionSource is orphaned and the caller of UpdateAsync awaits forever — a top-level catch ensuring the entry is always completed is the fix

No architectural or SOLID concerns. The separation of IFileUpdater / FileUpdater / WorkspaceGatedFileUpdater / ServerHotReloadProcessor is correct and the processor correctly stays a thin router. The three findings are all about exception-safety of the background fire-and-forget tasks, a class of issue the operability guidelines specifically flag.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.

@unodevops

Copy link
Copy Markdown
Contributor

Copilot AI review requested due to automatic review settings July 20, 2026 18:46
@github-actions

github-actions Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @dr1rrb's task in 5m 15s —— View job


Review complete

  • Gather context and understand request
  • Read changed files (post-fixup state)
  • Review WorkspaceGatedFileUpdater.cs for addressed findings
  • Review test coverage for new regression tests
  • Review spec changes
  • Post inline comments
  • Post summary

Summary

Verdict: ship — all prior blocking and moderate findings have been fully addressed. Two minor issues posted as inline comments; neither blocks merge.

Prior findings — all addressed:

Prior finding Status
_inner not volatile (ARM visibility) ✅ Fixed — field declared volatile
DrainAsync fire-and-forget: _draining permanently stuck on callback throw ✅ Fixed — outer try/finally always resets _draining; outer catch logs the fault
DrainAsync: entry awaiter orphaned if callback throws before entry.Complete() ✅ Fixed — entry.Complete() now precedes all reporter/onEvent callbacks, each wrapped in try/catch
WatchTimeoutAsync: orphaned awaiter on unexpected throw ✅ Fixed — outer try/catch/finally guarantees entry completion; CompactQueue() called in finally
ReportWorkspaceState: partial reject loop on throwing callback ✅ Fixed — per-entry Complete before callbacks; callbacks individually caught
Claimed entries accumulating in queue (stuck Initializing) ✅ Fixed — CompactQueue() removes IsTaken entries after timeout/cancellation
Spec: NoWorkspace → Initializing edge missing from diagram ✅ Fixed
Spec: R5 TTL enforcement model unspecified ✅ Fixed — explicitly timer-based (proactive)
Spec: test plan missing NoWorkspace → Initializing mode-change case ✅ Fixed — test plan item 9 added; matched by When_NoWorkspaceThenInitializing_Then_GatingResumes

Two new regression tests added alongside the fixes: When_OnEventThrowsDuringFlush_Then_RequestCompletesAndGateNotWedged (drain exception safety) and When_EntryExpires_Then_ItIsRemovedFromTheQueue (queue compaction). Total: 15 unit tests.

2 minor inline findings posted:

Severity Location Finding
Minor ServerHotReloadProcessor.cs:312 ex?.Message ?? ex?.ToString() — the ?? ex?.ToString() branch is dead code
Minor WorkspaceGatedFileUpdater.cs:344 Reject calls .Select() on request.Edits without guarding a default ImmutableArray, unlike FileUpdater.UpdateAsync

One theoretical edge case noted (not posted inline): if DrainAsync were ever to escape via its outer catch (which requires a truly unexpected exception — all per-entry exceptions and all diagnostics callbacks are already individually caught, so this path is essentially unreachable), items stranded in the queue in Ready state would not trigger a new drain from UpdateAsync because the goto default path doesn't set _draining = true. This would only manifest in a scenario that genuinely can't occur in the current code.

The state machine, FIFO ordering, volatile visibility, and exception-safety fixes are all correct. The decorator pattern cleanly separates the gating policy from the processor, which remains a thin router.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.

@unodevops

Copy link
Copy Markdown
Contributor

dr1rrb added 6 commits July 20, 2026 15:06
…ts baseline

An update request racing the async workspace initialization was written to
disk before the baseline solution was read, folding the edit into the
baseline (never emitted as a delta) or landing before the FileSystemObserver
existed (never observed). Requests are now gated on the workspace lifecycle
by a WorkspaceGatedFileUpdater decorator: queued while initializing, flushed
FIFO once the baseline is captured and the observer is active, pass-through
when hot reload is IDE-driven (no workspace), failed with an explicit error
on init failure/dispose or after a hard 30s queue timeout (configurable via
the update-file-queue-timeout server configuration).

Implements specs/050-hotreload-updatefile-workspace-gate; fixes #23787.
Harden WorkspaceGatedFileUpdater against a throwing diagnostics callback:
complete each queued entry before invoking reporter/onEvent, guard those
callbacks, and give DrainAsync an outer try/finally that always resets the
draining flag (catching + logging any unexpected escape). WatchTimeoutAsync
now guarantees the entry is resolved on any fault, _inner is volatile, and
timed-out/cancelled entries are compacted out of the queue so a workspace
stuck in Initializing cannot grow it unbounded. Adds two regression tests.

Spec 050: add the standard header, drop the broken 049 link, use stable
symbol references instead of file:line, draw the NoWorkspace -> Initializing
edge, reword R2 (flush point is not today's Notify(Ready)), state TTL is
timer-based, and add the mode-change test-plan item.
DrainAsync: reset _draining atomically with the empty-queue check under the
same lock (removing the finally) so a request arriving in Ready state can no
longer observe an empty queue with draining still latched and get stuck
unflushed; the catch path also resets it under the lock on an unexpected
escape. Re-check the lifecycle immediately before applying so an entry already
dequeued when the workspace goes terminal (Failed/Disposed) is rejected rather
than written to disk.

Reject: guard against a default ImmutableArray (Select would throw NRE),
matching FileUpdater's IsDefaultOrEmpty entry guard.

ServerHotReloadProcessor: drop the dead `?? ex?.ToString()` (Message is never
null on a non-null exception).
UpdateAsync: arm the TTL watcher (WatchTimeoutAsync) outside the _gate lock.
If the token is already cancelled or the timeout is zero, the watcher runs
synchronously through its finally -> CompactQueue, which re-enters _gate;
starting it under the held lock ran that re-entrant queue mutation mid-enqueue.

ServerHotReloadProcessor: in IDE-driven mode, report NoWorkspace before awaiting
Notify(Ready) so an UpdateFile racing that window passes through immediately
instead of being queued (strict IDE-driven pass-through).
Copilot AI review requested due to automatic review settings July 20, 2026 22:07
@dr1rrb
dr1rrb force-pushed the dev/dr/hr-updatefile-workspace-gate branch from 82d84b5 to b9e4e6e Compare July 20, 2026 22:07
@github-actions

github-actions Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @dr1rrb's task in 6m 1s —— View job


Review complete

  • Gather context and understand request
  • Read changed files (post-fixup state after latest push)
  • Review WorkspaceGatedFileUpdater.cs — latest fixes
  • Review ServerHotReloadProcessor.cs — NoWorkspace-before-Notify fix
  • Review test coverage
  • Post inline comments for specific findings
  • Post summary

Summary

Verdict: ship — all prior blocking and moderate findings from rounds 1–3 are correctly addressed. Three minor findings posted as inline comments; none blocks merge.

Prior findings — all confirmed addressed in this push:

Prior finding Status
_draining gate-wedge: reset now atomic with empty-queue check under lock; no more finally race window ✅ Fixed
Drain-in-flight terminal race: _state re-read under lock immediately after TryTake(), terminal entries rejected instead of written ✅ Fixed
WatchTimeoutAsync started while holding _gate (potential deadlock on pre-cancelled token) ✅ Fixed — watcher armed outside lock with explicit comment
NoWorkspace gate state reported after Notify(Ready) in IDE-driven mode ✅ Fixed — ReportWorkspaceState(NoWorkspace) now precedes await Notify(Ready)
ex?.Message ?? ex?.ToString() dead code in SafeNotifyMetadataInitializationFailed ✅ Fixed — simplified to ex?.Message

Correctness of fixes verified by inspection:

  • _draining = false and return are both inside the lock scope → lock released atomically; no window where UpdateAsync can see _draining = true + empty queue after drain has finished ✅
  • _inner is volatile → ARM visibility guaranteed ✅
  • entry.Complete(response) precedes all reporter/onEvent callbacks at every call site ✅
  • All per-callback invocations individually guarded with try/catch ✅
  • Reject() guards ImmutableArray.IsDefaultOrEmpty before .Select() ✅
  • CompactQueue() called in WatchTimeoutAsync finally when entry is claimed — removes dead entries from queue ✅
  • WatchTimeoutAsync outer try/catch/finally guarantees entry resolution on all code paths ✅
  • Sticky terminal-state logic allows NoWorkspace → Initializing without replay ✅

3 minor inline findings posted:

Severity Location Finding
Minor WorkspaceGatedFileUpdater.cs:136 Bare catch {} throughout the file triggers CA1031; catch (Exception) {} is semantically identical in .NET Core and satisfies the analyzer
Minor WorkspaceGatedFileUpdater.cs:176 reporter/onEvent callbacks invoked inside the _gate lock in UpdateAsync — inconsistent with DrainAsync/ReportWorkspaceState which invoke them after the lock scope
Minor WorkspaceGatedFileUpdater.cs:251 kind = "flushed" set for both successful flushes and inner-updater exceptions; a "failed" kind in the catch path would make telemetry distinguishable

Test coverage: 15 unit tests cover all major state-machine paths, FIFO ordering, TTL expiry, cancellation, drain exception safety, queue compaction, and the NoWorkspace → Initializing reconfiguration case. All sound.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

UpdateAsync re-checks the workspace lifecycle immediately before the
pass-through call to the inner updater: a terminal transition (Failed/Disposed)
reported from the init task or Dispose can race the pass-through decision made
under the lock, so re-check and reject without applying (mirrors the same
re-check already on the drain path).
Copilot AI review requested due to automatic review settings July 20, 2026 22:18
@github-actions

github-actions Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @dr1rrb's task in 3m 29s —— View job


Review complete

  • Gather context and understand request
  • Read changed files (latest push)
  • Review WorkspaceGatedFileUpdater.cs — latest fixes
  • Review ServerHotReloadProcessor.cs — latest fixes
  • Review test coverage
  • Post inline comments
  • Post summary

Summary

Verdict: ship — the latest commit (922d3e1, "reject pass-through updates that race a terminal transition") correctly addresses the last Copilot correctness finding. All prior blocking and moderate issues from rounds 1–4 remain fully resolved.

Latest fix verified by inspection:

The new double-checked lock in UpdateAsync (lines 196–202) re-reads _state under _gate immediately before calling _inner.UpdateAsync, rejecting with the terminal error if Failed/Disposed raced the pass-through decision. The narrow residual window — where a terminal transition could land between that second lock release and the actual _inner.UpdateAsync invocation — is inherent to any async-safe decorator and is correctly documented in the inline comment.

Two minor findings posted as inline comments (same as prior round — still open):

Severity Location Finding
Minor WorkspaceGatedFileUpdater.cs:176 reporter and onEvent callbacks invoked inside _gate lock — inconsistent with DrainAsync/ReportWorkspaceState; slow delegates hold the lock
Minor WorkspaceGatedFileUpdater.cs:263 kind = "flushed" is set for both successful flushes and inner-updater exceptions — a "failed" kind in the catch path makes telemetry distinguishable

Neither blocks merge. The state machine, FIFO ordering, volatile visibility, exception-safety fixes, queue compaction, lock-external TTL arming, and the NoWorkspace-before-Notify ordering are all correct.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (1)

src/Uno.HotReload/IO/WorkspaceGatedFileUpdater.cs:56

  • queueTimeout is accepted without validation. If a negative value is passed, Task.Delay(QueueTimeout, ...) will throw at runtime and callers will get an opaque rejection message derived from ArgumentOutOfRangeException.Message rather than a clear argument error. Since this is a public type, validate queueTimeout at construction time (e.g., reject < TimeSpan.Zero).
	/// <summary>
	/// Max delay a request is kept queued while waiting for the workspace to become ready.
	/// On expiry the request is failed and is never applied afterwards.
	/// </summary>
	public TimeSpan QueueTimeout { get; } = queueTimeout ?? DefaultQueueTimeout;

@dr1rrb
dr1rrb merged commit dd48d86 into master Jul 21, 2026
72 checks passed
@dr1rrb
dr1rrb deleted the dev/dr/hr-updatefile-workspace-gate branch July 21, 2026 13:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Hot reload: UpdateFile requests received before the workspace is initialized corrupt the delta baseline

4 participants