You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(runtime): migrate queued requests with activations during silo retirement - #11460
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.
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.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.MessageCodecencodes the package and its embedded messages. A nonserialized package reference identifies the existingActivationMigration, whose completion lock coordinates a one-time payload handoff to serialization. The serializer releases the context and carried bodies infinally, 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.
MessageCodecis 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.
MigrationContextretains 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
FinishDeactivatinginitiates retirement migration for a migratable activation which completed activation, is deactivating withDeactivationReasonCode.ShuttingDown, and still has queued requests after running requests and lifecycle callbacks finish. ExplicitMigrateandMigrateOnIdleuseDeactivationReasonCode.Migratingand carry their queued requests through the same path.ActivationMigrationrecords 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.GetOrCreateActivationmethod. ItsReceiveRequestshelper transfers requests through ordinaryIGrainContext.ReceiveMessageadmission: 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: afinallyguarantees 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.
ActivationDatareads 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
MaxForwardCountremain 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
MaxMessageHeaderSizeas a conservative bound so sizing leaves their values untouched. Groups whose bound exceedsMaxMessageBodySizeare 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
IActivationMigrationManagerSystemTargetadvertises request-carrying support and addsRetargetMigratedRequests. After acceptance, the source sends routes to caller silos.CallbackDataupdates 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.DeactivationTimeoutcancels 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, bySystemResponseTimeouton 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
AcceptMigratingGrainspackages 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
PooledBufferarguments and request-context entries.MessageWriteRequestretains 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.CallbackDataretains 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
Activatecall 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.