fix(outbox): reclaim expired Processing messages in Entity Framework Core and Cosmos DB - #903
Merged
Merged
Conversation
…ocessing lease expires
…rtially claimed batches
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #903 +/- ##
==========================================
+ Coverage 96.07% 96.13% +0.06%
==========================================
Files 274 274
Lines 11514 11527 +13
Branches 1072 1070 -2
==========================================
+ Hits 11062 11082 +20
+ Misses 232 229 -3
+ Partials 220 216 -4 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
… and ETag-guarded Cosmos DB reclaim
…ocessing lease timeout
…op the provider hedge
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Closes #813
Summary
The Entity Framework Core and Cosmos DB outbox repositories now reclaim messages that stay in
Processinglonger than the processing lease, like the SQL Server, PostgreSQL, MySQL, SQLite and MongoDB providers already do. Without this, a graceful shutdown mid-batch, a cancellation between send and completion, a failure after the claim, or a crashed host left messages inProcessingforever.Changes
EntityFrameworkOutboxRepositorytakesIOptions<OutboxOptions>(registered byAddOutbox) and validatesProcessingLeaseTimeout > TimeSpan.Zero. TheGetPendingAsyncclaim filter is widened to(Pending AND NextRetryAt due) OR (Processing AND UpdatedAt <= now - ProcessingLeaseTimeout). The cutoff is computed outside the expression tree. Because the claim filter is also the predicate of the bulkExecuteUpdate(seedecisions/2026-09-28-entityframework-outbox-claim-concurrency.md), a competing poller re-checks it against the committed row and fails, since the reclaim writes a freshUpdatedAt. The tracking executors reject the same race through theStatus/UpdatedAtconcurrency tokens. No executor changes were needed, and the claim-concurrency guards from fix(entityframework): prevent double claims in bulk FetchAndMarkAsync under READ COMMITTED #883 are unchanged.CosmosDbOutboxOptions.ProcessingLeaseTimeout(default 5 minutes). This mirrorsMongoDbOutboxOptions.ProcessingLeaseTimeout.CosmosDbOutboxOptionsValidatorrejects values<= TimeSpan.Zeroat host startup (ValidateOnStart), next to thePartitionKeyPathcheck; the repository constructor keeps its guard for direct construction.OR (c.status = 1 AND c.updatedAt <= @leaseExpiredBefore). TheIfMatchEtagclaim keeps a reclaim exclusive. The query keeps its single-propertyORDER BY c._ts, which needs no composite index under the default indexing policy.CosmosDbOutboxTestspass against the emulator with the new query.ClaimMessagesAsyncnow returns the documents already claimed when a later patch fails with aCosmosException(for example429). With nothing claimed yet, and on cancellation, the exception still propagates. Any document stranded that way is reclaimed once the lease expires.ProcessIndividuallyAsyncremarks: remaining messages are reclaimed after the lease expires.OutboxOptions.ProcessingLeaseTimeoutremarks: now name the providers that honor it.ProcessingLeaseTimeoutrow (validated at startup).OutboxOptions.ProcessingLeaseTimeout.OutboxEventTypeResolver.DeadLetterUnresolvableAsyncremarks: no longer suggest that some providers do not reclaim expired leases.2026-09-24-outbox-unresolvable-event-types.md: the line-58 consequence no longer describes the gap.state: proposed, for the maintainer to accept in review):decisions/2026-09-28-entityframework-and-cosmosdb-outbox-lease-reclaim.md. It records the use ofUpdatedAtas the lease timestamp (no schema change), where each provider reads the lease from, and the partial-claim behavior.Bug hunt
GetPendingAsyncnever returns a message stuck inProcessingpast the leaseOutboxTestsBase.Should_GetPendingAsync_Reclaim_Expired_Processing(all providers)GetPendingAsyncnever returns a message stuck inProcessingpast the leaseProcessingmessage is reclaimed before its lease expiresOutboxTestsBase.Should_GetPendingAsync_Keep_Processing_Within_Leasefirst.Count == 0)EntityFrameworkOutboxClaimRaceTestsBase.GetPendingAsync_WhenReclaimsOverlap_ReturnsDisjointBatches(SQLite, PostgreSQL, SQL Server RCSI, MySQL/tracking executor)429)CosmosDbOutboxRepositoryClaimTests.GetPendingAsync_WhenLaterPatchIsThrottled_ReturnsMessagesClaimedSoFarCosmosDbOutboxRepositoryClaimTests.GetPendingAsync_WhenFirstPatchIsThrottled_ThrowsCosmosExceptionProcessingdocument carriesIfMatchEtagand is skipped on412CosmosDbOutboxRepositoryClaimTests.GetPendingAsync_WhenReclaimPatchThrowsPreconditionFailed_SkipsExpiredProcessingCandidateOutboxOptions.ProcessingLeaseTimeout(hardcoded lease would pass the shared tests)UpdatedAt = now)EntityFrameworkOutboxRepositoryInvariantTests.GetPendingAsync_Uses_configured_ProcessingLeaseTimeoutProcessingLeaseTimeoutat host startup (only the scoped repository constructor threw, on first poll)CosmosDbOutboxOptionsValidatorTests.Validate_When_ProcessingLeaseTimeout_is_not_positive_failsAcceptance criterion "after a graceful shutdown mid-batch, the remaining messages are dispatched once the lease expires":
Should_GetPendingAsync_Reclaim_Expired_Processingcovers it. The test claims 3 messages, completes 1, advances past the lease, and checks that exactly the other 2 are returned once and are not returned again.Impact
CosmosDbOutboxOptionsgains a publicProcessingLeaseTimeoutproperty (additive).OutboxOptions.ProcessingLeaseTimeoutnow also applies to the Entity Framework Core provider. There are no interface changes, so externalIOutboxRepositoryimplementers are not affected. They SHOULD reclaim expired leases the same way.Processingin existing EF/Cosmos DB installations are reclaimed on the first poll after the upgrade. They may be delivered again, which matches at-least-once semantics.GetPendingCountAsyncstill counts onlyPending.Test evidence
dotnet build Pulse.slnx -c Release: 0 errors, 0 warnings.NetEvolve.Pulse.Tests.Unit, net8.0/net9.0/net10.0): 7203 passed, 0 failed (after mergingorigin/main).*EntityFramework*outbox classes (InMemory, SQLite, and Docker-backed SQL Server, PostgreSQL, MySQL; outbox and claim-race tests): 271 tests. The first run had 7 failures at 0 ms that came from fixture startup on a heavily loaded machine. Those 7 tests passed on a targeted rerun (5/5 and 48/48, including all new reclaim, lease and race tests).CosmosDbOutboxTestson the emulator: 52/52 passed, including the new reclaim tests.SQLiteAdoNetOutboxTests: 51/51 passed.Should_GetPendingAsync_Reclaim_Expired_Processing,GetPendingAsync_WhenReclaimsOverlap_ReturnsDisjointBatches), Cosmos DB emulator (Should_GetPendingAsync_Reclaim_Expired_Processing), the Cosmos DB partial-claim unit test, and the Cosmos DB lease validator test.1e29379): all checks green, including Run Tests (unit + integration with Docker-backed providers), Code Formatting, Commitlint, CodeQL, NativeAOT, codecov/patch and codecov/project.