Skip to content

Wait for MongoDB single-member primary to accept writes before reporting healthy - #21638

Merged
David Fowler (davidfowl) merged 1 commit into
mainfrom
aspireagent/fix-21637-mongodb-single-member-writable-primary
Nov 17, 2026
Merged

David Fowler (davidfowl) merged 1 commit into
mainfrom
aspireagent/fix-21637-mongodb-single-member-writable-primary

Conversation

@davidfowl

Copy link
Copy Markdown
Collaborator

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 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?
    • 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)

…ing healthy

A newly elected member reports PRIMARY in replSetGetStatus (myState: 1)
before it finishes drain mode and rejects writes with NotWritablePrimary
until hello reports isWritablePrimary. Use hello.isWritablePrimary for
both initialization and the health check.

Fixes #21637

Co-authored-by: Copilot <[email protected]>
@github-actions

github-actions Bot commented Nov 1, 2026

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 -- 21638

Or

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

@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 Nov 1, 2026
@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

Tests selector

4 / 100 PR test projects · 2 PR jobs, from 3 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/MongoDBBuilderExtensions.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

🔧 src/Aspire.Hosting.MongoDB/MongoDBSingleMemberReplicaSet.cs (changed source)
→ 1 directly: Aspire.Hosting.MongoDB.Tests

🧪 tests/Aspire.Hosting.MongoDB.Tests/SingleMemberReplicaSetTests.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 8f37d4b.

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.

🟢 Approval recommended

No active review issues are reported for the MongoDB write-readiness change.

No open issues 🎉

What changed in this PR

Fixes the single-member MongoDB readiness race behind #21637 by waiting until the elected primary accepts writes before reporting healthy. This prevents consumers using WaitFor from starting during the primary’s drain phase.

Changes:

  • Initialization and health checks now require hello.isWritablePrimary, the expected replica-set name, and exactly one host.
  • Adds regression tests for draining primaries and readiness validation.
  • Updates documentation to describe write-ready health semantics.
File Description
tests/​Aspire.Hosting.MongoDB.Tests/​SingleMemberReplicaSetTests.cs Adds draining-primary regression tests and updates readiness cases.
src/​Aspire.Hosting.MongoDB/​README.md Clarifies that readiness waits for write acceptance.
src/​Aspire.Hosting.MongoDB/​MongoDBSingleMemberReplicaSet.cs Uses hello to check writable-primary readiness during initialization.
src/​Aspire.Hosting.MongoDB/​MongoDBBuilderExtensions.cs Applies the readiness predicate to health checks and updates API documentation.

Review effort: Balanced

@davidfowl
David Fowler (davidfowl) marked this pull request as ready for review November 1, 2026 06:31
@davidfowl David Fowler (davidfowl) added the ci-health Fixes CI flakiness or CI infrastructure (AspireAgent queue) label Nov 1, 2026 — with Copilot SWE Agent
@radical

Copy link
Copy Markdown
Member

[automated] Starting paired CI validation of #21638 against its frozen pre-fix source, using the regular Aspire.Hosting.MongoDB.Tests workload on fresh ubuntu-latest runners with Docker. Each runner will execute the workload once. The initial batches are 25 pre-fix and 50 fixed runners; additional stages are adaptive, with a cumulative cap of 250 provisioned runners per arm, including infrastructure/invalid samples. Results will distinguish the reported single-member not-primary failure from other failures. Finite sampling cannot prove a zero failure rate. This is validation only, not PR approval.

@radical

Ankit Jain (radical) commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

[automated] The reported single-member not-primary failure reproduced once on baseline source and was not observed in 250 fixed-source workload executions. Efficacy remains suggestive, not conclusive; none of the six workflows was wholly green.

Audited 2026-11-08. PR #21638 is open, non-draft, at 8f37d4b460804f9139f0612463641182a26bc5d9. Baseline product/test source is 370ac3d57773ae74aba148cf10c8db213199ebaa. Every validation run uses a workflow-only child of the corresponding frozen source; the fixed source therefore still matches the live PR. Each worker's checkout log confirms its run-head SHA.

Observed executions, not aggregate workflow conclusions

All six are completed workflow_dispatch runs, attempt 1, created on 2026-11-03. Every workload worker built successfully and produced one complete, nonzero MTP summary on Ubuntu 24.04.5 LTS, x64, Docker 28.0.4, running Aspire.Hosting.MongoDB.Tests with quarantine and outerloop excluded. Each baseline workload reported 206 tests; each fixed workload reported 209, reflecting the changed unit-test suite. No tests were reported skipped. No Windows, macOS, or ARM execution is represented.

Run Arm Workers / executions Workloads passed / failed Original-signature events Other test-failure events
41705698398 Baseline S1 25 / 25 22 / 3 0 3
41705706847 Fixed S1 50 / 50 39 / 11 0 13
41708104011 Baseline S2 25 / 25 16 / 9 0 11
41708111019 Fixed S2 50 / 50 43 / 7 0 8
41710254984 Baseline S3 50 / 50 40 / 10 1 11
41710263269 Fixed S3 150 / 150 115 / 35 0 38
Total 100 baseline / 250 fixed 350 / 350 275 / 75 1 84

Failure events are individual failed test cases, not failed workers; one worker can contain several. All six generic results jobs fail because reproduce is failure, not because the results job identifies the bug.

Separate conclusions

  • Operator validity: All 350 workers executed the requested ordinary project workload once. No missing worker summaries, zero-test samples, build failures, or pre-test infrastructure failures were found. Source pairing and OS/architecture are confirmed.
  • Natural reproduction: Baseline S3 worker #31 failed SingleMemberReplicaSetFunctionalTests.TransactionsAndChangeStreamsWorkWithoutADeveloperCertificate with MongoDB.Driver.MongoNotPrimaryException : Server returned not primary error. at MongoDatabase.CreateCollectionAsync, VerifyTransactionsAndChangeStreamsAsync:251, and VerifyFeaturesAsync:57. This matches the original historical job, whose primary log was also inspected. One matching event in 100 baseline workload executions; the worker also had a separate multi-member failure.
  • Fixed-source outcomes: No original-signature failure was reported in 250 fixed workloads, but 53 workloads failed with 59 other test-failure events. Across both arms, 82 events were multi-member MongoDbReplicaSetFunctionalTests initialization failures: resource rs0 failed to start, with MongoNodeIsRecoveringException, code 11602, InterruptedDueToReplStateChange. The other two events were Polly.Timeout.TimeoutRejectedException with a two-minute timeout: fixed S1 worker #46, SingleMemberReplicaSetFunctionalTests.MongoExpressConnectsWithTls; and fixed S3 worker #85, MongoDbFunctionalTests.VerifyWithInitFiles. These are real test failures, not the reported not-primary signature. Their underlying causes and relationship to the fix are not established by this audit.
  • Efficacy: The direction supports the fix, but one baseline hit is too sparse to establish a reliable before/after improvement or zero residual risk. The workload is paired by source and environment, not identical in test count or batch size. Console summaries and failed-test diagnostics establish the observations; per-test success records are unavailable. This is validation evidence, not approval or a claim that the fixed project is clean.

Budget and evidence limits

The six campaign workflow dispatches occurred on 2026-11-03. The kickoff specified a 250-runners-per-arm cap, but does not establish whether a separate workflow-run limit applied at the time. The six pre-existing runs count toward the current five-workflow-run ceiling, regardless of conclusion, leaving no authority for additional runs. No reruns are recorded. Actual expenditure is 100 baseline plus 250 fixed workload jobs, plus 12 executed setup/results jobs; six CLI-image jobs were skipped. No further dispatch was made during this audit.

All six full log archives and all 75 failure artifacts were retrieved. Artifacts contain DCP .log and .json diagnostics, not TRX or per-test result files. The 85 failed-test headers and exceptions reconcile exactly with worker MTP summaries (72,850 total test-case executions). No success artifacts were offered by these workflows. Actions timing reports billable.UBUNTU.total_ms: 0; that does not establish zero resource use or a monetary charge. Job timestamps establish execution, not billing.

Live PR comments and reviews show no later validation-result report after the 2026-11-03 kickoff. Paginated reproduction-workflow discovery from 2026-11-03 through 2026-11-08 found only these six matching validation-branch runs; this does not exclude deleted runs or different branch names.

-- AnkitAgent

@davidfowl David Fowler (davidfowl) added the area-integrations Issues pertaining to Aspire Integrations packages label Nov 8, 2026 — with Copilot SWE Agent

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.

LGTM — single-member readiness now waits for MongoDB's writable-primary signal while preserving set-name and single-member checks. The change adds no public API and keeps the existing experimental configuration and connection behavior intact.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-integrations Issues pertaining to Aspire Integrations packages ci-health Fixes CI flakiness or CI infrastructure (AspireAgent queue) 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.

[CI Failure] Flaky: SingleMemberReplicaSetFunctionalTests write fails with NotWritablePrimary after MongoDB reports healthy

4 participants