Repository navigation
Wait for MongoDB replica set primary before reconfiguring to fix rs0 FailedToStart flake - #21594
Conversation
…efore reconfiguring replSetInitiate returns while the initial member is still stepping up. The forced replSetReconfig that adds the remaining members was sent straight away and raced that election, failing with InterruptedDueToReplStateChange (11602), which the initialization loop does not treat as retryable, so the replica set resource went to FailedToStart. Co-authored-by: Copilot <[email protected]>
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 21594Or
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 21594" |
Tests selector4 / 100 PR test projects · 2 PR jobs, from 2 changed files. Selected PR test projects (4 / 100)
Selected PR jobs (2)
How these were chosen — grouped by what changed🔧 📦 affected project 🧪 Job reasons
Selection computed for commit |
There was a problem hiding this comment.
🔵 Needs a closer look
The MongoDB election-timing fix still needs real-system validation, as Hosting.MongoDB CI jobs are pending and DCP-backed functional scenarios were not run locally.
No open issues 🎉
What changed in this PR
Addresses #21593 by making Aspire’s MongoDB replica set initialization wait for the initial member to become writable primary before reconfiguring membership, avoiding a race with its election.
Changes:
- Extracts initialization into
InitiateReplicaSetAsyncand pollshello.isWritablePrimarybefore reconfiguration. - Bounds the wait to 30 seconds while honoring caller cancellation.
- Adds regression tests for command ordering and cancellation during primary election.
| File | Description |
|---|---|
tests/Aspire.Hosting.MongoDB.Tests/ReplicaSet/MongoDBReplicaSetInitiationTests.cs |
Adds simulated-member tests for readiness ordering and cancellation. |
src/Aspire.Hosting.MongoDB/ReplicaSet/MongoDBReplicaSetBuilderExtensions.cs |
Waits for writable-primary readiness before adding the remaining replica set members. |
Review effort: Balanced
|
Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt. |
|
[automated] Validating this PR's test-flakiness fix with paired pre-fix and post-fix runs on fresh CI runners, capped at 250 runners per arm. Historical evidence and duplicate reports will be checked; observed failures and limitations will be recorded. |
|
[automated] The original MongoDB failure reproduced in 6/50 pre-fix invocations and was not observed in 100/100 post-fix invocations. This supports the fix, but does not prove that the remaining failure rate is zero.
Full technical evidence, every batch, historical runs, duplicate reports, and limitationsFrozen revisions and experiment isolation
Workload and exact execution
./build.sh -restore -ci -build -projects "$TEST_PROJECT_PATH" \
/p:InstallBrowsersForPlaywright=false /p:RunQuarantinedTests=true
./dotnet.sh test --project "$TEST_PROJECT_PATH" --no-restore --no-build -- \
--timeout 10m --results-directory "$GITHUB_WORKSPACE/testresults" \
--filter-not-trait "quarantined=true" --filter-not-trait "outerloop=true"The workflow sets Paired batches and budget
Ref: Ref: Runners were counted from actual Sizing ladder: 10, 25, 50, 100, 250 cumulative runners per arm. The starting pair was 50/100 from the independently verified historical project-job rate; any later batch added only the incremental runners needed. Baseline escalation stops at an original-signature reproduction; fixed validation finishes the next size level. All completed outcomes, including other failures, are retained. Failed/excluded runners
Original signature and mechanism
Independently verified historical denominatorOriginal issue #21593 was read in full, including labels and comments (none). Its title, marker, and labels did not establish flakiness. Primary CI evidence below does: two distinct failures and 20 comparable passes in the same window, with the same MongoDB product source blob independently checked between one failure and the original PR-parent pass. Window: 2026-10-29 13:00Z through 2026-10-31 13:23Z,
Historical same-baseline-source passing job: 41175594640 / 124467031086, source revision Duplicate and related issue reportsSearched open and closed issues for
These bodies describe 11 distinct run IDs altogether: three signature-confirmed jobs on distinct revisions, and eight older related reports not promoted to confirmed 11602 failures. Primary API metadata verifies that every older linked run exists and completed with failure; that alone does not establish its underlying signature. None are counted twice by issue count or by mixing first attempts with retries. The third November occurrence is outside the historical sizing window. Exclusions, limitations, and publication
|
|
✅ No documentation update needed. docs_optional → internal_refactor. No signals triggered (signal_count 0). Changed files: |
…ing healthy (#21638) ## Description Fixes an intermittent `Hosting.MongoDB (ubuntu-latest)` failure in `SingleMemberReplicaSetFunctionalTests`. The first write after the single-member replica set reports healthy fails: ``` MongoDB.Driver.MongoNotPrimaryException : Server returned not primary error. at MongoDB.Driver.MongoDatabase.CreateCollectionAsync(...) at ...SingleMemberReplicaSetFunctionalTests.VerifyTransactionsAndChangeStreamsAsync(...) in SingleMemberReplicaSetFunctionalTests.cs:251 ``` ### Root cause (product) `WithReplicaSet()` readiness used `replSetGetStatus.myState == 1`, both in `InitializeAndWaitForPrimaryAsync` and in the health check. A newly elected member reports PRIMARY before it leaves drain mode, and it rejects writes with `NotWritablePrimary` until [`hello.isWritablePrimary`](https://www.mongodb.com/docs/manual/reference/command/hello/#mongodb-data-hello.isWritablePrimary) is true. When the health check landed in that window, the resource reported Healthy and the consumer's first write failed. Apps using `WaitFor` hit the same race. I reproduced the window locally with `mongo:9.0` (`--replSet`, `replSetInitiate`, then polling `replSetGetStatus`, `hello` and an insert). It appeared in **6 of 6** runs: `myState` became 1 about 300ms before `isWritablePrimary` turned true. Every insert in that window failed with `NotWritablePrimary`, and the first successful insert matched the first `isWritablePrimary: true` exactly. ### Fix - Initialization and the health check now use `hello` and require `isWritablePrimary`, the matching `setName` and exactly one host. The readiness signal is now the server's own write-acceptance flag rather than its election state. - No sleeps or retries were added, and no test assertions were changed. ### Regression coverage In `SingleMemberReplicaSetTests`, a fake `DrainingMember` reports PRIMARY but is not writable for the first N `hello` probes: - `InitializationWaitsUntilTheElectedPrimaryAcceptsWrites`: initialization keeps probing until the member is writable. - `HealthIsUnhealthyWhileTheElectedPrimaryIsDraining`: the health check is Unhealthy while the member drains and Healthy afterwards. - `ReadinessRequiresTheSingleMemberWritablePrimary` / `ReadinessRejectsHelloFromAStandaloneServer`: covers the `hello` predicate cases. Negative control: with the `isWritablePrimary` check removed, 3 of these tests fail. With the fix, all 22 pass in `SingleMemberReplicaSetTests`. ### Evidence ci.yml attempt 1, 2026-10-25 → 2026-11-01: across 214 runs with Hosting.MongoDB jobs, 4 `Hosting.MongoDB (ubuntu-latest)` jobs failed with this signature (1 on main, 3 on unrelated PR branches). Details are in #21637. This is a separate code path from the multi-member family (#20478, #21593, #21594). Fixes #21637 ## Checklist - Is this feature complete? - [x] Yes. Ready to ship. - [ ] No. Follow-up changes expected. - Are you including unit tests for the changes and scenario tests if relevant? - [x] Yes - [ ] No - Did you add public API? - [ ] Yes - [x] No - Does the change make any security assumptions or guarantees? - [ ] Yes - [x] No **🤖 Posted by AspireAgent (AI Agent)** Co-authored-by: davidfowl <[email protected]> Co-authored-by: Copilot <[email protected]>
Description
Fixes an intermittent
Hosting.MongoDB (ubuntu-latest)failure in which the multi-member replica set resourcers0goes toFailedToStartwith this error:The failure affects these
MongoDbReplicaSetFunctionalTeststests:VerifyMongoDBMultiNodeReplicaSetAllNodesEndUpHealthyVerifyMongoDBMultiNodeReplicaWithDataShouldWorkAcrossUsagesVerifyMongoExpressConnectsToAReplicaSetMemberVerifyReplicaSetInitializesWhenAMemberNeverBecomesHealthyRoot cause (product)
The multi-member initialization runs
replSetInitiatewith the first member, then immediately sends a forcedreplSetReconfigthat adds the remaining members.replSetInitiatereturns once the configuration is installed, but the member is still running its own election at that point (the old code comment said otherwise). The reconfig therefore races the step-up:ConfigurationInProgress. The init loop already retries this error.InterruptedDueToReplStateChange(11602). The init loop doesn't retry this error, sors0fails to start.The single-member path (
MongoDBSingleMemberReplicaSet) already waits for primary after initiating; the multi-member path didn't.Fix
InitiateReplicaSetAsync. It runsreplSetInitiate, then pollshelloevery 100ms untilisWritablePrimaryis true (30s budget), and only then sends the forcedreplSetReconfig.DistributedApplicationException. Caller cancellation is honored.Evidence
Denominator: ci.yml, 2026-10-29 13:00Z to 2026-10-31 13:23Z (388 runs),
Hosting.MongoDB (ubuntu-latest):I sampled 6 failing jobs across unrelated branches, including main jobs 123855998476 and 123877826145. All 6 have the 11602 signature above.
Regression tests (new
MongoDBReplicaSetInitiationTests): a fake member reports not-primary for the first Nhelloprobes and throws 11602 if it receives a reconfig before stepping up.MongoNodeIsRecoveringException(11602).hellountil writable primary, then reconfig with all members.Real
mongodrepro (mongo:9.0 --replSet rs0, fresh container per iteration):ConfigurationInProgress), and in 5 of 11 in an earlier run.isWritablePrimary, then reconfig): 15 of 15 succeeded.I couldn't run the full DCP-backed functional tests locally because the members weren't reachable from the test host in this sandbox, so this PR's
Hosting.MongoDBCI job provides the functional validation.CI on 898c98b: green, with
Hosting.MongoDBpassing on ubuntu-latest and windows-latest on the first attempt. The run had one unrelated failure,Cli.EndToEnd-JavaScriptPublishTests (ubuntu)(JavaScriptHostingApisRunFromTypeScriptAppHost, job 124557722651). In that job,aspire runstalled at "Preparing Aspire server..." before the runtime probe. CI's automatic retry (attempt 2, job 124562754576) passed. No manual reruns.Fixes #21593
Checklist
🤖 Posted by AspireAgent (AI Agent)