Skip to content

fix(runtime): migrate queued requests with activations during silo retirement - #11460

Merged
ReubenBond merged 54 commits into
dotnet:mainfrom
ReubenBond:rb-fix-runtime-safe-retirement-handoff
Oct 21, 2026
Merged

ReubenBond merged 54 commits into
dotnet:mainfrom
ReubenBond:rb-fix-runtime-safe-retirement-handoff

Conversation

@ReubenBond

@ReubenBond ReubenBond commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

Problem

During graceful silo shutdown, queued requests can reach a new activation while their callers still track them against the retiring silo. When that silo leaves the cluster, the callers fail with SiloUnavailableException, even though their requests may complete elsewhere.

Solution

Activations with queued requests migrate during retirement. The migration carries the requests, and after acceptance the source retargets their callers' pending callbacks to the destination on a best-effort basis.

Migration-local payload ownership

Requests enter a migration in one handoff after dehydration. The package serializes that fixed List<Message> directly. Later arrivals remain owned by the source activation. After leaving the catalog, the source completes the original handoff's disposition, then handles its remaining queue through ordinary forwarding or rejection. Deliver() handles the original migration requests.

MessageCodec encodes the package and its embedded messages. A nonserialized package reference identifies the existing ActivationMigration, whose completion lock coordinates a one-time payload handoff to serialization. The serializer releases the context and carried bodies in finally, including on failure. Completion releases an unclaimed payload; a later serializer rejects that completed migration. Once the serializer claims the payload, completion can proceed while its buffers remain valid until writing finishes. Work canceled before sending retains its requests for forwarding. The source retains routing headers for failure reporting.

The acceptance RPC uses its ordinary generated request. MessageCodec is the new production type; lifetime coordination stays in the existing migration types. Message, MessageFactory, CallbackData, and the invocation pipeline retain their existing behavior for this refinement.

Embedded messages use connection framing and preserve received bodies as serialized bytes. On the destination, they share the RPC receive buffer and retain their own body slices until invocation. The decoder validates required context objects and non-null request entries before admission. Malformed or truncated RPCs fail decoding; GC reclaims abandoned partial decode graphs once they become unreachable. This accepts GC reclamation instead of prompt pool recycling for those abandoned objects. The catalog receives successfully deserialized request lists directly.

Each embedded message encodes its current remaining TTL at serialization. Local expiry tracking resumes when the destination decodes its headers, and expired requests are dropped individually. Transport and retry time make expiry accounting best effort. The caller's response timeout continues independently; a delayed migration can deliver work after its caller has timed out. Retargeting preserves the caller's original deadline.

MigrationContext retains its managed backing storage and existing pooled-buffer wire field. Its field IDs and wire representation remain unchanged. The original acceptance RPC identity and request-free package wire shape are preserved. Transport retries reuse the serialized RPC body.

Activation and request disposition

FinishDeactivating initiates retirement migration for a migratable activation which completed activation, is deactivating with DeactivationReasonCode.ShuttingDown, and still has queued requests after running requests and lifecycle callbacks finish. Explicit Migrate and MigrateOnIdle use DeactivationReasonCode.Migrating and carry their queued requests through the same path.

ActivationMigration records queued, sent, or accepted stage. Its completion task publishes the final disposition. After the source activation leaves the catalog, the migration transiently rejects requests from failed or unknown outcomes and forwards its unsent requests. Accepted requests remain with the destination. The source activation separately forwards or rejects its remaining requests before signaling deactivation completion. A rejected request may still execute on the destination after a lost acknowledgement; applications can retry these failures with a call filter.

The source stays in the catalog until its final deactivation step, so incoming requests reach it and retirement awaits deactivations already underway. Activations abandoned while processing a stuck request leave the catalog early.

Ordinary admission and size bounds

The migration package flows through the single Catalog.GetOrCreateActivation method. Its ReceiveRequests helper transfers requests through ordinary IGrainContext.ReceiveMessage admission: FIFO queueing, per-request overload checks, cancellation, and failure handling. Requests already queued at the destination retain their place.

Creation commits the catalog to scheduling rehydration and calling Activate: a finally guarantees those required calls even if admission reports a failure. The activation owns every message submitted to it, including when submission throws, and handles activation failure through its ordinary request and lifecycle paths.

For a new activation, requests are admitted before rehydration and activation are scheduled, so they precede directory registration. ActivationData reads and checks the previous registration during rehydration and adds cache updates to its queued messages. Responses carry those updates. One-way callers' routes converge on their next send through normal forwarding and cache repair. Previous-address decoding and participant failures follow the existing best-effort rehydration policy: errors are logged and the scheduled activation still runs.

An existing activation receives requests through ordinary admission before the unused migration context is disposed. Its callers' routes converge through normal forwarding and cache repair. A deactivating destination forwards through its ordinary lifecycle path. If the catalog cannot obtain an activation, the manager routes requests through the message center.

Admission consumes the package's request list. Validation, cancellation, or activation-creation failure disposes the unadmitted remainder; admitted requests stay owned by their activation. A package containing messages which are not requests for its grain fails acceptance. Migration counts as one forward; requests which have exhausted MaxForwardCount remain at the source and are rejected.

Local request bodies are serialized once into owned buffers before sizing; received requests already have serialized bodies. Migration and ordinary forwarding reuse those bytes. Size bounds include context, current headers and cache updates, body lengths, and list/message framing. Runtime-owned headers allow routing-address growth. Opaque request-context values use MaxMessageHeaderSize as a conservative bound so sizing leaves their values untouched. Groups whose bound exceeds MaxMessageBodySize are forwarded individually. Preparation and serialization failures reject the affected requests and release their payloads at the owning boundary.

Cache headers retain the first update per grain. Null cache-update entries fail decoding before dispatch.

Retargeting, compatibility, and shutdown

Version 1 of IActivationMigrationManagerSystemTarget advertises request-carrying support and adds RetargetMigratedRequests. After acceptance, the source sends routes to caller silos. CallbackData updates the target and monotonically increasing forward count, and re-signals cancellation which preceded retargeting while that callback remains registered. Retargeting to an already-dead silo fails the call. Grain call cancellation and retargeting remain best-effort; canceled callbacks removed before retargeting retain baseline cancellation behavior.

DeactivationTimeout cancels a still-queued migration and completes an accepted migration without waiting for remaining retarget acknowledgements. The manager bounds the complete acceptance invocation, including asynchronous outgoing filters, by SystemResponseTimeout on the messaging clock and observes late invocation failures. Host shutdown budgets must allow for acceptance and subsequent retargeting. A caller which was not retargeted can fail if the source departs before its response arrives.

The source carries requests only when the destination manifest advertises version 1 or later. Older destinations receive request-free AcceptMigratingGrains packages and requests are forwarded. Stateless workers, [Immovable] grains, oversized request groups, late arrivals, and activations already deactivating for another reason retain ordinary forwarding behavior. Such calls retain their original tracked target and can fail when that silo leaves. Outside-client grain location caching is tracked in #11508.

General transport correctness

Serialization can consume PooledBuffer arguments and request-context entries. MessageWriteRequest retains written bytes until transport completion, restores request context on failure, and retries retained bodies while preserving routing and expiration. Unreadable retry context follows the per-message failure path. CallbackData retains invocation metadata independently, and diagnostics identify serialized bodies without decoding or releasing transport-owned buffers.

Application request instrumentation lives in SharedCallbackData, shared by callbacks in each runtime configuration. This preserves the invocation reference needed for retry-safe cancellation and deadlines while keeping each callback at 88 bytes on x64, recovering the measured eight-byte-per-call allocation increase.

Normal message-discard paths release their owned serialized buffers. Stateless-worker dispatch handles creation failures before handoff and leaves ownership with the receiving context after handoff; a terminated parent rejects and releases a message when the silo cannot create a replacement.

Coverage

Migration regressions cover ordinary FIFO and overload admission, existing/deactivating/failed destinations, explicit migration reasons, retirement and catalog lifetime, cancellation, lost acknowledgements, capability gating, expiration, forward limits, cache updates, callback retargeting, and the fixed original handoff versus later arrivals.

Ownership regressions hold serialization before and after its payload claim, complete the migration concurrently, and verify release and disposition for successful and failed writes. Other cases cover pre-message failure, discard, preparation failure, retained-byte retries, and shared receive pages. Malformed-input regressions cover truncated requests, packages, complete invocation framing, reference-table overflow, and structural nulls; they check rejection before admission and ordinary outer-message disposal. Compatibility checks decode the original acceptance-invocation/package shape and migration-context format in both directions.

Lifecycle regressions retain the required Activate call after admission failure, activation-owned previous-address handling, existing destinations ignoring unused rehydration metadata, next-send cache repair, and cleanup of dropped or unadmitted messages. Sizing coverage includes pooled payload/context preservation, oversized groups, routing-address growth, and cache updates from prior migrations. A controlled-time callback regression establishes that retargeting preserves the caller's original timeout.

Copilot AI balanced review requested due to automatic review settings October 10, 2026 00:19

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.

🟡 Changes recommended

Retirement draining can miss removed connections and drop already-admitted asynchronous reroutes after outbound admission closes.

3 open findings
What changed in this PR

Preserves forwarded grain invocations during silo retirement by retaining callbacks, propagating route hints, and draining admitted work.

Changes:

  • Adds callback route tracking and receiver-owned forwarding.
  • Introduces retirement admission/drain coordination across messaging and transport.
  • Adds extensive regression, compatibility, and documentation coverage.
File Description
test/​ReleasedPeer/​V104/​ReleasedPeer.V104.csproj Adds Orleans 10.4 peer host.
test/​ReleasedPeer/​V103/​ReleasedPeer.V103.csproj Adds Orleans 10.3 peer host.
test/​ReleasedPeer/​Shared/​RuntimeProbe.cs Observes released-runtime messages.
test/​ReleasedPeer/​Shared/​Program.cs Implements peer process protocol.
test/​ReleasedPeer/​Shared/​ProbeGrain.cs Adds retirement probe grain.
test/​ReleasedPeer/​README.md Documents compatibility qualification.
test/​ReleasedPeer/​NuGet.Config Isolates released package restoration.
test/​ReleasedPeer/​Directory.Build.props Configures peer helper projects.
test/​ReleasedPeer/​Contracts/​ReleasedPeer.Contracts.csproj Builds shared legacy contracts.
test/​ReleasedPeer/​Contracts/​IRetirementProbeGrain.cs Defines probe contracts.
test/​Orleans.Runtime.Tests/​CallbackDataTests.cs Tests callback and route semantics.
test/​Orleans.Runtime.Internal.Tests/​ActivationsLifeCycleTests/​SafeSiloRetirementTests.cs Tests activation retirement behavior.
test/​Orleans.ReleasedPeer.Tests/​ReleasedPeerRetirementTests.cs Tests mixed-version retirement.
test/​Orleans.ReleasedPeer.Tests/​ReleasedPeerProcess.cs Manages released peer processes.
test/​Orleans.ReleasedPeer.Tests/​Orleans.ReleasedPeer.Tests.csproj Configures compatibility tests.
test/​Orleans.Core.Tests/​Networking/​MessageTransportLifecycleTests.cs Tests transport and drain boundaries.
src/​Orleans.Runtime/​Silo/​Silo.cs Replaces shutdown delay with draining.
src/​Orleans.Runtime/​Networking/​SiloConnection.cs Records retirement write failures.
src/​Orleans.Runtime/​Networking/​GatewayInboundConnection.cs Updates gateway routing and draining.
src/​Orleans.Runtime/​Messaging/​MessageCenter.cs Coordinates retirement admissions.
src/​Orleans.Runtime/​Messaging/​Gateway.cs Drains gateway connections and queues.
src/​Orleans.Runtime/​GrainDirectory/​LruGrainDirectoryCache.cs Preserves replacement registrations.
src/​Orleans.Runtime/​Core/​InsideRuntimeClient.cs Applies forwarding route updates.
src/​Orleans.Runtime/​Catalog/​StatelessWorkerGrainContext.cs Drains stateless-worker requests.
src/​Orleans.Runtime/​Catalog/​RetirementDrainResult.cs Defines drain outcomes.
src/​Orleans.Runtime/​Catalog/​Catalog.cs Tracks activation retirement producers.
src/​Orleans.Runtime/​Catalog/​ActivationData.cs Disposes queued retirement requests.
src/​Orleans.Core/​Runtime/​OutsideRuntimeClient.cs Caches advisory grain locations.
src/​Orleans.Core/​Runtime/​CallbackData.cs Preserves callbacks and routes.
src/​Orleans.Core/​Networking/​MessageWriteRequest.cs Handles accepted-write uncertainty.
src/​Orleans.Core/​Networking/​MessageReadRequest.cs Gates incoming dispatch.
src/​Orleans.Core/​Networking/​ConnectionManager.cs Adds connection drain operations.
src/​Orleans.Core/​Networking/​Connection.cs Tracks connection-level admissions.
src/​Orleans.Core/​Networking/​ClientOutboundConnection.cs Preserves logical grain targets.
src/​Orleans.Core/​Messaging/​StatusResponse.cs Adds forwarding destinations.
src/​Orleans.Core/​Messaging/​MessageFactory.cs Creates forwarding statuses.
src/​Orleans.Core/​Messaging/​Message.cs Classifies relocatable/drain work.
src/​Orleans.Core/​Messaging/​ClientMessageCenter.cs Keeps gateway selection sticky.
Orleans.slnx Registers compatibility projects.
docs/​site/​src/​content/​docs/​implementation/​messaging-delivery-guarantees.md Documents delivery semantics.
docs/​site/​src/​content/​docs/​host/​configuration-guide/​shutting-down-orleans.md Documents retirement draining.
docs/​site/​src/​content/​docs/​grains/​cancellation-tokens.md Documents forwarded cancellation.
docs/​site/​src/​content/​docs/​deployment/​upgrades.md Documents upgrade compatibility.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/Orleans.Runtime/Silo/Silo.cs Resolved
Copilot AI balanced review requested due to automatic review settings October 10, 2026 01:53

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.

🟡 Changes recommended

Incoming drain snapshots can miss newly registered silo and gateway connections, allowing already-admitted frames to be dropped.

2 open findings
3 resolved since last review

🧠 Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 10, 2026 05:01

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.

🔵 Needs a closer look

It changes concurrency-sensitive callback, activation, gateway, shutdown, and transport ownership semantics across multiple runtime layers.

0 open findings

2 resolved since last review

🧠 Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 10, 2026 06:32

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.

🟡 Changes recommended

Pre-transport refusals can incorrectly poison retirement and a connection-termination race can silently drop admitted messages.

1 open finding
Previously missed (1)

In code that hasn't changed since last review

Medium severity Avoid recording retirement failure for rejected writes

src/​Orleans.Core/​Networking/​MessageWriteRequest.cs:145

This path is the definite pre-transport refusal (EnqueueWrite returned false), but it records a retirement write failure before rerouting. In production BeginRetirement() is already set, so even if the retry reaches a replacement connection successfully, DrainRetirementAsync will still throw ConnectionClosedException. The accepted-write failure path should record the failure, while this non-accepted path should only transfer its admissions and retry.

🧠 Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 10, 2026 14:08

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.

🔵 Needs a closer look

Pre-transport write refusals incorrectly mark a successfully rerouted retirement drain as failed.

0 open findings

1 resolved since last review
Previously missed (1)

In code that hasn't changed since last review

Medium severity Enqueue refusal falsely marks retirement reroute as failed

src/​Orleans.Core/​Networking/​MessageWriteRequest.cs:145

RerouteMessage is also called from Connection.SendWorker when EnqueueWrite returns false, which is a definite refusal before transport acceptance. This unconditional callback therefore sets MessageCenter._retirementSendFailed during retirement even when the admitted message is successfully rerouted and sent, causing an otherwise successful graceful drain to report failure. Record the failure only for the SetException path, where the transport had already accepted the write.

🧠 Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 13, 2026 22:04

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.

🟡 Changes recommended

A pre-transport write refusal can incorrectly mark an otherwise successful retirement retry as failed.

1 open finding

🧠 Review effort: Balanced

Comment thread src/Orleans.Runtime/Catalog/Catalog.cs Resolved
Copilot AI balanced review requested due to automatic review settings October 14, 2026 00:19

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.

🟡 Changes recommended

Concurrent location updates can leave an older forwarding destination cached.

1 open finding
1 resolved since last review

🧠 Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 14, 2026 00:44
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants