Skip to content

Wait for MongoDB replica set primary before reconfiguring to fix rs0 FailedToStart flake - #21594

Merged
David Fowler (davidfowl) merged 1 commit into
mainfrom
aspireagent/fix-mongodb-replicaset-initiate-race
Nov 3, 2026
Merged

David Fowler (davidfowl) merged 1 commit into
mainfrom
aspireagent/fix-mongodb-replicaset-initiate-race

Conversation

@davidfowl

@davidfowl David Fowler (davidfowl) commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Fixes an intermittent Hosting.MongoDB (ubuntu-latest) failure in which the multi-member replica set resource rs0 goes to FailedToStart with this error:

MongoDB.Driver.MongoNodeIsRecoveringException: Server returned node is recovering error (code = 11602, codeName = "InterruptedDueToReplStateChange").
   at ... MongoDBReplicaSetBuilderExtensions.cs:line 314
Resource rs0/rs0 changed state: Starting -> FailedToStart
DistributedApplicationException : Stopped waiting for resource 'rs0' to become healthy because it failed to start.

The failure affects these MongoDbReplicaSetFunctionalTests tests:

  • VerifyMongoDBMultiNodeReplicaSetAllNodesEndUpHealthy
  • VerifyMongoDBMultiNodeReplicaWithDataShouldWorkAcrossUsages
  • VerifyMongoExpressConnectsToAReplicaSetMember
  • VerifyReplicaSetInitializesWhenAMemberNeverBecomesHealthy

Root cause (product)

The multi-member initialization runs replSetInitiate with the first member, then immediately sends a forced replSetReconfig that adds the remaining members. replSetInitiate returns 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:

  • It can be rejected with ConfigurationInProgress. The init loop already retries this error.
  • It can be interrupted with InterruptedDueToReplStateChange (11602). The init loop doesn't retry this error, so rs0 fails to start.

The single-member path (MongoDBSingleMemberReplicaSet) already waits for primary after initiating; the multi-member path didn't.

Fix

  • Extracted the sequence into InitiateReplicaSetAsync. It runs replSetInitiate, then polls hello every 100ms until isWritablePrimary is true (30s budget), and only then sends the forced replSetReconfig.
  • The wait ends on a concrete readiness signal, the member reporting itself writable primary, rather than a fixed delay.
  • No new retries were added and no assertions were changed.
  • If the member never becomes primary, initialization throws a 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):

First attempts Retries
main (push) 2 failed / 22 0 / 1
PRs 39 failed / 131 (9 cancelled) 11 failed / 123

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 N hello probes and throws 11602 if it receives a reconfig before stepping up.

  • With the wait removed (old behavior), both tests fail. The ordering test fails with exactly the CI MongoNodeIsRecoveringException (11602).
  • With the fix, both tests pass (2/2). They assert the command order: initiate, hello until writable primary, then reconfig with all members.

Real mongod repro (mongo:9.0 --replSet rs0, fresh container per iteration):

  • Old sequence (initiate, then immediate forced reconfig): failed in 2 of 15 iterations (ConfigurationInProgress), and in 5 of 11 in an earlier run.
  • New sequence (initiate, wait for 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.MongoDB CI job provides the functional validation.

CI on 898c98b: green, with Hosting.MongoDB passing 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 run stalled at "Preparing Aspire server..." before the runtime probe. CI's automatic retry (attempt 2, job 124562754576) passed. No manual reruns.

Fixes #21593

Checklist

  • Is this feature complete?
    • Yes. Ready to ship.
    • No. Follow-up changes expected.
  • Are you including unit tests for the changes and scenario tests if relevant?
    • Yes
    • No
  • Did you add public API?
    • Yes
    • No
  • Does the change make any security assumptions or guarantees?
    • Yes
    • No

🤖 Posted by AspireAgent (AI Agent)

…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]>
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.sh | bash -s -- 21594

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/microsoft/aspire/main/eng/scripts/get-aspire-cli-pr.ps1) } 21594"

@aspire-repo-bot
aspire-repo-bot Bot requested a balanced review from Copilot October 31, 2026 13:50
@github-actions github-actions Bot added the needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners label Oct 31, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Tests selector

4 / 100 PR test projects · 2 PR jobs, from 2 changed files.

Selected PR test projects (4 / 100)

Aspire.Cli.EndToEnd.Tests, Aspire.Hosting.MongoDB.Tests, Aspire.Hosting.Radius.Tests, Aspire.Playground.Tests

Selected PR jobs (2)

polyglot, typescript-api-compat


How these were chosen — grouped by what changed

🔧 src/Aspire.Hosting.MongoDB/ReplicaSet/MongoDBReplicaSetBuilderExtensions.cs (changed source)
→ 1 directly: Aspire.Hosting.MongoDB.Tests
→ 2 via the project graph: Aspire.Hosting.Radius.Tests, Aspire.Playground.Tests (2 hops)

📦 affected project Aspire.Hosting.MongoDB
→ 1 test: Aspire.Cli.EndToEnd.Tests

🧪 tests/Aspire.Hosting.MongoDB.Tests/ReplicaSet/MongoDBReplicaSetInitiationTests.cs (changed test)
→ 1 directly: Aspire.Hosting.MongoDB.Tests

Job reasons

Job Triggered by
polyglot affected project Aspire.Hosting.MongoDB
typescript-api-compat affected project Aspire.Hosting.MongoDB

Selection computed for commit 898c98b.

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

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 InitiateReplicaSetAsync and polls hello.isWritablePrimary before 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

@github-actions

Copy link
Copy Markdown
Contributor

Retrying the failed CI jobs for this pull request from the CI run attempt. The rerun is being tracked in the rerun attempt.

@radical

Copy link
Copy Markdown
Member

[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.

@radical

Copy link
Copy Markdown
Member

[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.

Arm Provisioned Valid project invocations Passed Original 11602 failures Other test failures Infrastructure Invalid Original-failure rate
Pre-fix 50 50 42 6 2 0 0 12.0%
Post-fix 100 100 100 0 0 0 0 0.0%
  • Scope: user-authorized exception for the existing product-and-test fix in PR Wait for MongoDB replica set primary before reconfiguring to fix rs0 FailedToStart flake #21594; this is targeted flakiness validation, not comprehensive review. No approval or merge.
  • Historical evidence: independently reconstructed 2 matching failures / 22 completed first-attempt main Ubuntu MongoDB jobs (20 passes, 206 tests each); five cancelled runs never created that job. A third matching occurrence confirms related issue [CI Failure] Flaky: MongoDbReplicaSetFunctionalTests.VerifyMongoDBReplicaSetResource fails to become healthy #21680.
  • Experiment: the entire MongoDB test project on fresh ubuntu-latest Docker runners, one invocation each; 50 pre-fix / 100 post-fix runners provisioned against a 250-per-arm cap. Quarantined and outerloop tests excluded.
  • Sizing and limits: p=2/22 gives 32 trials for a nominal 95% detection chance; rounded to 50 baseline / 100 fixed. Finite sampling, other OSes, excluded tests, and later PR revisions remain outside this conclusion.
  • Publication gate: only the specifically authorized start comment was posted. This exact draft and underlying evidence require a separate independent audit through the coordinator before any final posting; PR approval remains forbidden.
Full technical evidence, every batch, historical runs, duplicate reports, and limitations

Frozen revisions and experiment isolation

  • Pre-fix source: 6a8f53125b8788df3c409088381057a3c0dacfff — exact parent of the PR's first and only commit, not a moving main tip.
  • Fixed source: 898c98bb761cc7960ccf0819d154f476942ab85a — the independently checked live PR head.
  • Complete source diff: src/Aspire.Hosting.MongoDB/ReplicaSet/MongoDBReplicaSetBuilderExtensions.cs plus new tests/Aspire.Hosting.MongoDB.Tests/ReplicaSet/MongoDBReplicaSetInitiationTests.cs only.
  • Private Git object database and indexes constructed workflow-only commits; the session checkout, index, branch, and Git configuration were preserved. The author's branch and source/tests were not changed.
  • Original, fixed, and live reproduce-flaky-tests.yml execution logic were identical. Across arms only RUNNERS_PER_OS differs in configuration. No action pin, fixture, readiness delay, stress setup, test assertion, or product code was added to the baseline.
  • Existing ci.yml pushes only to main/release branches: it was not disabled. Upstream-only workflow guards required temporary ankj/ refs in microsoft/aspire, not a fork.
  • Active GitHub account radical had repo and workflow scope. Existing invalid saved credentials were not changed or used. Workflow-only commits include the mandatory Copilot App coauthor.

Workload and exact execution

  • Workflow: .github/workflows/reproduce-flaky-tests.yml, workflow_dispatch with no inputs; configuration comes from workflow env.
  • Project: tests/Aspire.Hosting.MongoDB.Tests/Aspire.Hosting.MongoDB.Tests.csproj (TEST_PROJECT=Hosting.MongoDB). Full-project execution preserves class/project contention, rather than isolating a fake unit test or a single method.
  • OS: ubuntu-latest; Docker availability, build completion, admitted SHA, selected filter, one iteration, and nonzero test output were checked for every runner.
  • ITERATIONS_PER_RUNNER="1"; each matrix job is a fresh runner. Baseline project invocations execute 206 tests; the fixed project has two additional authored regression tests and executes 208. Independent sample unit is a project invocation, not an individual test case.
  • Existing functional tests start real DCP-backed MongoDB containers, including three-member rs0, TLS/key-file configuration, member data/topology reuse, and Mongo Express. Default project concurrency and cold container startup were retained.
  • Image versions verified at the source SHA in src/Aspire.Hosting.MongoDB/MongoDBContainerImageTags.cs: library/mongo:9.0 and library/mongo-express:1.0, mirrored through netaspireci.azurecr.io. SDK pinned by global.json: 11.0.100-rc.2.26504.105.
./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 SkipDefaultTestFilters=true; the explicit filters above restore the regular CI exclusions. No tests in the affected replica-set functional class carried a quarantine/outerloop attribute at the frozen baseline.

Paired batches and budget

Stage Arm Run Exact experiment SHA Actual runners Passed Original Other Infrastructure Invalid
1 pre 41691376825 9dd81be0c9b801f7e799a14ec475e7bc4a01496b 50 42 6 2 0 0
1 post 41691413400 5eca6d0b1603ac6b3e268f404ecba20500d4495a 100 100 0 0 0 0

Ref: ankj/pr21594-pre-validation-20261103; source SHA 6a8f53125b8788df3c409088381057a3c0dacfff; dispatch 2026-11-03T18:11:17.079702+00:00.

Ref: ankj/pr21594-post-validation-20261103; source SHA 898c98bb761cc7960ccf0819d154f476942ab85a; dispatch 2026-11-03T18:11:31.020609+00:00.

Runners were counted from actual ubuntu-latest #N jobs, not the workflow's comma-based printed matrix total. Setup/results jobs are excluded from the runner budget. Infrastructure and invalid runners remain in the provisioned totals; they were not silently replenished.

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

  • pre job 126110903095: original_failure; test totals [206], failed [1], skipped [0].
    • Aspire.Hosting.MongoDB.Tests.MongoDbReplicaSetFunctionalTests.VerifyMongoDBMultiNodeReplicaSetAllNodesEndUpHealthy (9s 550ms)
ubuntu-latest #11	Run test iterations (Linux/macOS)	2026-11-03T18:21:15.9738989Z   Xunit.MicrosoftTestingPlatform.XunitException: Aspire.Hosting.DistributedApplicationException : Stopped waiting for resource 'rs0' to become healthy because it failed to start.
ubuntu-latest #11	Run test iterations (Linux/macOS)	2026-11-03T18:21:16.1687680Z     |                                                                         MongoDB.Driver.MongoNodeIsRecoveringException: Server returned node is recovering error (code = 11602, codeName = "InterruptedDueToReplStateChange").
ubuntu-latest #11	Run test iterations (Linux/macOS)	2026-11-03T18:21:16.1693615Z     |                                                                                         Aspire.Hosting.DistributedApplicationException: Resource 'mongo1-mongoexpress' stopped waiting for dependency resource 'rs0' because it failed to start.
ubuntu-latest #11	Run test iterations (Linux/macOS)	2026-11-03T18:21:16.2451766Z Test run summary: Failed!
  • pre job 126110903324: original_failure; test totals [206], failed [1], skipped [0].
    • Aspire.Hosting.MongoDB.Tests.MongoDbReplicaSetFunctionalTests.VerifyMongoExpressConnectsToAReplicaSetMember(addCompanionBeforeMember: True) (9s 228ms)
2026-11-03T18:18:18.7715814Z   Xunit.MicrosoftTestingPlatform.XunitException: Aspire.Hosting.DistributedApplicationException : Stopped waiting for resource 'rs0' to become healthy because it failed to start.
2026-11-03T18:18:19.0140178Z     |                                                                         MongoDB.Driver.MongoNodeIsRecoveringException: Server returned node is recovering error (code = 11602, codeName = "InterruptedDueToReplStateChange").
2026-11-03T18:18:19.0161396Z     |                                                                                         Aspire.Hosting.DistributedApplicationException: Resource 'mongo1-mongoexpress' stopped waiting for dependency resource 'rs0' because it failed to start.
2026-11-03T18:22:58.0975740Z Test run summary: Failed!
  • pre job 126110903484: original_failure; test totals [206], failed [1], skipped [0].
    • Aspire.Hosting.MongoDB.Tests.MongoDbReplicaSetFunctionalTests.VerifyMongoDBMultiNodeReplicaWithDataShouldWorkAcrossUsages(topologyChange: None) (16s 793ms)
2026-11-03T18:21:21.4450651Z   Xunit.MicrosoftTestingPlatform.XunitException: Aspire.Hosting.DistributedApplicationException : Stopped waiting for resource 'rs0' to become healthy because it failed to start.
2026-11-03T18:21:21.8479181Z     |                                                                         MongoDB.Driver.MongoNodeIsRecoveringException: Server returned node is recovering error (code = 11602, codeName = "InterruptedDueToReplStateChange").
2026-11-03T18:23:41.5917954Z Test run summary: Failed!
  • pre job 126110903542: other_failure; test totals [206], failed [1], skipped [0].
    • Aspire.Hosting.MongoDB.Tests.SingleMemberReplicaSetFunctionalTests.TransactionsAndChangeStreamsWorkWithoutADeveloperCertificate (10s 276ms)
2026-11-03T18:20:13.5308244Z   Xunit.MicrosoftTestingPlatform.XunitException: MongoDB.Driver.MongoNotPrimaryException : Server returned not primary error.
2026-11-03T18:20:13.6943511Z     | System.ObjectDisposedException: Cannot access a disposed object.
2026-11-03T18:24:21.6904586Z Test run summary: Failed!
  • pre job 126110903638: original_failure; test totals [206], failed [1], skipped [0].
    • Aspire.Hosting.MongoDB.Tests.MongoDbReplicaSetFunctionalTests.VerifyMongoDBMultiNodeReplicaWithDataShouldWorkAcrossUsages(topologyChange: None) (16s 116ms)
2026-11-03T18:21:34.8019039Z   Xunit.MicrosoftTestingPlatform.XunitException: Aspire.Hosting.DistributedApplicationException : Stopped waiting for resource 'rs0' to become healthy because it failed to start.
2026-11-03T18:21:35.2213038Z     |                                                                         MongoDB.Driver.MongoNodeIsRecoveringException: Server returned node is recovering error (code = 11602, codeName = "InterruptedDueToReplStateChange").
2026-11-03T18:24:11.2935340Z Test run summary: Failed!
  • pre job 126110903646: original_failure; test totals [206], failed [1], skipped [0].
    • Aspire.Hosting.MongoDB.Tests.MongoDbReplicaSetFunctionalTests.VerifyReplicaSetInitializesWhenAMemberNeverBecomesHealthy (30s 018ms)
2026-11-03T18:19:07.9505907Z   Xunit.MicrosoftTestingPlatform.XunitException: Aspire.Hosting.DistributedApplicationException : Stopped waiting for resource 'rs0' to become healthy because it failed to start.
2026-11-03T18:19:08.2094084Z     |                                                                         MongoDB.Driver.MongoNodeIsRecoveringException: Server returned node is recovering error (code = 11602, codeName = "InterruptedDueToReplStateChange").
2026-11-03T18:19:08.2170608Z     | [2026-11-03T18:19:04] Aspire.Hosting.TestUtilities.Resources.mongo1 Information: 596: 2026-11-03T18:19:04.3818175Z {"t":{"$date":"2026-11-03T18:19:04.381+00:00"},"s":"E",  "c":"REPL",     "id":21422,   "ctx":"conn4","msg":"replSetReconfig failed to store config document","attr":{"error":{"code":11602,"codeName":"InterruptedDueToReplStateChange","errmsg":"operation was interrupted"}}}
2026-11-03T18:24:27.9114440Z Test run summary: Failed!
  • pre job 126110903715: original_failure; test totals [206], failed [1], skipped [0].
    • Aspire.Hosting.MongoDB.Tests.MongoDbReplicaSetFunctionalTests.VerifyMongoDBMultiNodeReplicaWithDataShouldWorkAcrossUsages(topologyChange: MemberAdded) (16s 066ms)
2026-11-03T18:20:54.8993448Z   Xunit.MicrosoftTestingPlatform.XunitException: Aspire.Hosting.DistributedApplicationException : Stopped waiting for resource 'rs0' to become healthy because it failed to start.
2026-11-03T18:20:55.4570272Z     |                                                                         MongoDB.Driver.MongoNodeIsRecoveringException: Server returned node is recovering error (code = 11602, codeName = "InterruptedDueToReplStateChange").
2026-11-03T18:24:11.5652280Z Test run summary: Failed!
  • pre job 126110903921: other_failure; test totals [206], failed [2], skipped [0].
    • Aspire.Hosting.MongoDB.Tests.SingleMemberReplicaSetFunctionalTests.MongoExpressConnectsWithTls (33s 766ms)
    • Aspire.Hosting.MongoDB.Tests.SingleMemberReplicaSetFunctionalTests.TransactionsAndChangeStreamsWorkWithoutADeveloperCertificate (10s 523ms)
2026-11-03T18:19:06.3844583Z   Xunit.MicrosoftTestingPlatform.XunitException: MongoDB.Driver.MongoNotPrimaryException : Server returned not primary error.
2026-11-03T18:19:50.0972594Z   Xunit.MicrosoftTestingPlatform.XunitException: MongoDB.Driver.MongoNotPrimaryException : Server returned not primary error.
2026-11-03T18:19:50.2893623Z     | System.ObjectDisposedException: Cannot access a disposed object.
2026-11-03T18:24:07.6603944Z Test run summary: Failed!

Original signature and mechanism

MongoDB.Driver.MongoNodeIsRecoveringException: Server returned node is recovering error (code = 11602, codeName = "InterruptedDueToReplStateChange").
MongoDBReplicaSetBuilderExtensions.cs:line 314
Resource rs0/rs0 changed state: Starting -> FailedToStart
Stopped waiting for resource 'rs0' to become healthy because it failed to start.
  • Primary historical logs locate 11602 at the forced reconfiguration immediately after initial single-member initiation. The baseline source catches ConfigurationInProgress, but not the observed MongoNodeIsRecoveringException.
  • The fixed source polls hello.isWritablePrimary every 100ms, with a 30-second timeout and caller cancellation, before forced reconfiguration. MongoDB's primary command documentation confirms the field indicates a writable primary in a replica set.
  • This is a mechanism supported by the source ordering and actual CI signature, not direct instrumentation of the internal election timing.
  • The experiment naturally reproduced 11602 across the healthy-all-nodes test, Mongo Express before-member case, data/topology cases (None and MemberAdded), and the pre-existing never-healthy-member scenario. Two other pre-fix jobs failed with MongoNotPrimaryException in single-member tests: TransactionsAndChangeStreamsWorkWithoutADeveloperCertificate and MongoExpressConnectsWithTls; these are explicitly separate from the six original-signature failures.
  • Authored proxy tests force a not-yet-primary ordering and test cancellation; they are controlled injected regression coverage, not independent natural reproductions. They were never copied into the baseline.
  • Author-reported raw mongod results (2/15 ConfigurationInProgress, earlier interrupted 5/11, fixed 15/15) were not independently reproduced here. That different, already-retried error is not counted as the original 11602 signature or used for sample sizing.

Independently verified historical denominator

Original 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, ci.yml, main push runs, first attempts only. Reconstructed 27 distinct runs/revisions: 22 completed MongoDB Ubuntu jobs, plus five cancelled runs with no MongoDB job. Each completed job executed 206 tests; both failed jobs contain the original 11602 signature. This verifies the reported 2/22 main first-attempt rate, not the separate PR/retry rates or the author's six-job sample.

Historical run/job Revision Outcome Executed tests Original signature
41175594640 / 124467031086 6a8f53125b8788df3c409088381057a3c0dacfff success 206 no
41174429302 / 124460052412 8487570ff52a6a01bb4e6fe5e806f247b96d2c08 success 206 no
41171266086 / 124454723554 d77dac9fb91ffa04522728306f613ec69d90da9b success 206 no
41168649739 / 124441988146 8f70754f6c571fb9263a7231c32495e26bb99564 success 206 no
41138625758 / 124358915932 13b2068df7157a9637e77ca7627542b425156910 success 206 no
41136039061 / 124339481897 57971d4f6af50580984b1c59f06142ecc44a3a9f success 206 no
41125387843 / 124303434291 cedfcd0f14e6086a808106144134b3d6fb998afd success 206 no
41113340061 / 124262052592 591673906330a6664b5d29a3ad568cc4be5f3897 success 206 no
41101946907 / 124223485142 129d4a7142abd962e7b29f8702f7dd144c947aa0 success 206 no
41091004918 c77b0c13c34616d1ce4698771bdd445fd50c7a99 cancelled; no MongoDB job — not counted
41085859817 / 124183998346 4731e2b73a132d3cc00075bdeb0732b15ec573e7 success 206 no
41084627144 d85136b562a079f1c98533204c9ad636bd736ffd cancelled; no MongoDB job — not counted
41084390016 ec4cc677e32d47410fa4258d5401b91fdcf6cf39 cancelled; no MongoDB job — not counted
41076110474 / 124154771029 bf2966969a0bbce074eac8614766d1187bfc1755 success 206 no
41074175594 / 124126997725 82d064c1a692b5a5a97c8eba815f7701edb59d22 success 206 no
41038215347 / 124005081577 a76b57a995db8e2e00ad64c3fadd7c2c825e98b9 success 206 no
41004872500 / 123897940866 63c361dd3b0b32d55ab7c2276a660a8fd02dd127 success 206 no
40992075134 / 123877826145 69998022e041be41c14c98a6912f67f203dd65d9 failure 206 yes
40991758617 3dde72b25ea6fec521a185f4151badaa9054f29b cancelled; no MongoDB job — not counted
40991706139 / 123855998476 c1b1f947e885508d6583f5c3ebf3206b582812ef failure 206 yes
40984409791 / 123832649112 769cf381aa94ae3845c860051401352d8e9655f7 success 206 no
40958399480 / 123745965350 d482876363aca49812dccba9da1987a34a171e5c success 206 no
40956914440 215e95886ecb606e56bef91f794f83e50d1fc30f cancelled; no MongoDB job — not counted
40947925538 / 123709155604 a43c69baac2cc3f6e799a5d9813a5dd947c066e8 success 206 no
40922125033 / 123632903571 481326b3e55f7e458b5892007a53c70be46b5a66 success 206 no
40914588301 / 123603897836 716fa488bf4d3ebb5f3a734a74b47d2e093becde success 206 no
40905807668 / 123561388298 bfa60342cae9d387c7bfb628e9b540706477009b success 206 no

Historical same-baseline-source passing job: 41175594640 / 124467031086, source revision 6a8f53125b8788df3c409088381057a3c0dacfff, 206 succeeded / 0 failed / 0 skipped.

Duplicate and related issue reports

Searched open and closed issues for MongoDbReplicaSetFunctionalTests, the exact new test class, InterruptedDueToReplStateChange, and the affected healthy-all-nodes method; inspected all five directly related issue bodies and available comments. No issue matched the new injected test class. No additional closed matching issue was returned by these searches.

Issue Primary reports Relationship to this signature
#21593 Runs 40991706139 and 40992075134 Both original-signature logs verified; included in the 2/22 denominator, not counted again as issue occurrences
#21680 41394317897 / 125112814478 Independently verified 11602 at the same source line; likely duplicate tracking, not modified
#21133 39216025977 Same rs0 healthy-wait symptom; underlying 11602 not independently checked
#20478 36151000465, 36318348933, 39697617337 Related topology/data functional cases; generic symptom is not proof of identical cause
#20512 36201574198, 37349943397 Same test with topology None; underlying 11602 not independently checked
#19980 34240077767, 38991596691 Same healthy-all-nodes symptom; underlying 11602 not independently checked

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

  • Only Ubuntu and the frozen MongoDB project workload were exercised. Windows/macOS, quarantined/outerloop tests, dependent downstream projects, and any later head are untested.
  • Historical CI ran across different revisions/time windows; its rate was used as an approximate project-level planning rate, not an immutable independent per-test probability.
  • The natural pre/post comparison differs by the approved existing PR diff, including two fixed-only regression tests; raw testcase totals are therefore unequal.
  • All infrastructure failures, zero-test/invalid outcomes, and different-signature test failures remain visible; none justify a whole-workload green claim.
  • Eight pre-fix failed-runner artifacts were downloaded alongside every runner's full log. A transient SDK download message in one successful fixed runner was not a workload failure: the build completed and all 208 tests passed. Counters were parsed from the MTP summary, not arbitrary restore/build text.
  • Finite correlated CI samples cannot prove a zero residual failure rate; no root-cause confidence is derived solely from issue labels, author claims, or injected fakes.
  • The only posted text is the user-previewed start announcement, posted before the experiment dispatches. No final report, review, approval, issue update, new PR, quarantine change, or merge was made.
  • This exact draft and evidence are returned to the coordinator for the separately requested independent GPT-6.1 Sol/high audit. The validation agent did not launch reviewers or treat its own report assembly as that audit.
  • Temporary investigation refs and their evidence are retained for reproducibility; no author branch was changed or removed.

@davidfowl
David Fowler (davidfowl) merged commit 18e1012 into main Nov 3, 2026
340 of 343 checks passed
@microsoft-github-policy-service microsoft-github-policy-service Bot added this to the 17.0 milestone Nov 3, 2026
@aspire-repo-bot

Copy link
Copy Markdown
Contributor

✅ No documentation update needed.

docs_optional → internal_refactor. No signals triggered (signal_count 0). Changed files: src/Aspire.Hosting.MongoDB/ReplicaSet/MongoDBReplicaSetBuilderExtensions.cs (internal init-loop wait for primary before reconfig, fixing a flaky rs0 FailedToStart race) and one test file under tests/. No new public API, options, strings, or documented behavior change.

David Fowler (davidfowl) added a commit that referenced this pull request Nov 17, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-health Fixes CI flakiness or CI infrastructure (AspireAgent queue) flaky-test needs-area-label An area label is needed to ensure this gets routed to the appropriate area owners

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MongoDB replica set initialization fails intermittently with InterruptedDueToReplStateChange (Hosting.MongoDB functional tests flaky)

3 participants