Skip to content

Reconnect after MongoDB primary changes - #44

Merged
abnegate merged 1 commit into
mainfrom
fix/not-writable-primary-reconnect
Jul 30, 2026
Merged

Reconnect after MongoDB primary changes#44
abnegate merged 1 commit into
mainfrom
fix/not-writable-primary-reconnect

Conversation

@abnegate

@abnegate abnegate commented Jul 30, 2026

Copy link
Copy Markdown
Member

Summary

  • invalidate stale transports for every MongoDB primary-change response recognized by transaction retry logic
  • lazily reconnect before the next operation while preserving logical session state
  • keep permanent command and write errors on the existing transport
  • retain compatibility with the package's declared PHP 8.0 minimum

Validation

  • focused Client suite: 23 tests, 143 assertions
  • full suite: 51 tests, 247 assertions
  • Pint check
  • PHPStan src analysis
  • PHP 8.0 syntax check

Copilot AI review requested due to automatic review settings July 30, 2026 04:59

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Client now invalidates its connection when parsing NotWritablePrimary error code 10107, both for write errors and command-level errors, before replaying the MongoDB exception. A PHPUnit test verifies transport closure and cleared client state.

Changes

NotWritablePrimary handling

Layer / File(s) Summary
Error classification and invalidation
src/Client.php
Adds error-code classification and invalidates the client before throwing matching write or command errors.
Connection cleanup regression coverage
tests/ClientTest.php
Verifies exception code 10107, transport closure, and cleared connection/session state.

Estimated code review effort: 2 (Simple) | ~10 minutes

Sequence Diagram(s)

sequenceDiagram
  participant MongoDBServer
  participant SyncTransport
  participant Client
  MongoDBServer->>SyncTransport: Return response with error code 10107
  SyncTransport->>Client: Deliver response frame
  Client->>Client: Detect NotWritablePrimary
  Client->>SyncTransport: Invalidate connection
  Client-->>MongoDBServer: Replay MongoDB exception to caller
Loading

Suggested reviewers: copilot, chiragagg5k

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: invalidating and reconnecting after MongoDB primary changes.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/not-writable-primary-reconnect

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Comment thread src/Client.php Outdated
Comment thread src/Client.php Outdated
Comment thread src/Client.php Outdated
@greptile-apps

greptile-apps Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR now reconnects after MongoDB primary changes while retaining transaction session state.

  • Recognizes command and write errors associated with primary changes.
  • Invalidates the stale transport and establishes a fresh connection on the next operation.
  • Preserves sessions across reconnection and adds regression coverage for transaction retries and permanent write errors.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
src/Client.php Adds primary-change classification, session-preserving transport invalidation, and deferred reconnection; the previously reported session, PHP compatibility, and error-code coverage issues are resolved.
tests/ClientTest.php Adds coverage for all recognized primary-change codes, write-error handling, session preservation, fresh-transport transaction retries, and permanent write errors.

Reviews (2): Last reviewed commit: "(fix): reconnect after MongoDB primary c..." | Re-trigger Greptile

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🧹 Nitpick comments (1)
tests/ClientTest.php (1)

493-514: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Cover the writeErrors branch too.

This test exercises only top-level errmsg handling, while the implementation also adds 10107 invalidation for writeErrors. Add a response containing writeErrors[0] with code 10107 and assert transport/state cleanup; retain a permanent write-error case to verify existing behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/ClientTest.php` around lines 493 - 514, Extend
testNotWritablePrimaryClosesTransportBeforeTheErrorIsReplayed to cover a
response whose writeErrors[0] has code 10107, asserting the same transport close
and client state cleanup. Also retain or add a permanent write-error case with a
non-10107 code to verify existing behavior remains unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/Client.php`:
- Around line 1805-1810: Update the invalidate handling in the write-error paths
around the transaction retry flow, including both referenced 10107 branches, so
invalidating a not-writable-primary connection replaces the physical transport
without removing the logical transaction session from $this->sessions. Ensure
withTransaction can reuse the existing session when it retries via
startTransaction($session), while preserving normal session cleanup for
non-transactional invalidation.
- Around line 89-90: Update the composer.json PHP version constraint from >=8.0
to >=8.3 to match the typed class constant syntax used by
Client::NOT_WRITABLE_PRIMARY_ERRORS.

---

Nitpick comments:
In `@tests/ClientTest.php`:
- Around line 493-514: Extend
testNotWritablePrimaryClosesTransportBeforeTheErrorIsReplayed to cover a
response whose writeErrors[0] has code 10107, asserting the same transport close
and client state cleanup. Also retain or add a permanent write-error case with a
non-10107 code to verify existing behavior remains unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: df6546ee-1d14-4b06-89e2-4335780414b5

📥 Commits

Reviewing files that changed from the base of the PR and between 34d9ab4 and d62f3e1.

📒 Files selected for processing (2)
  • src/Client.php
  • tests/ClientTest.php

Comment thread src/Client.php Outdated
Comment on lines +89 to +90
private const array NOT_WRITABLE_PRIMARY_ERRORS = [10107];

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

files="$(fd -a -t f | rg '(^|/)(composer\.json|composer\.lock|\.php-version|\.tool-versions|Dockerfile[^/]*|[^/]+\.ya?ml)$' || true)"
if [ -n "$files" ]; then
  printf '%s\n' "$files" | xargs rg -n -i 'php|php-version|PHP_VERSION'
else
  echo "No PHP toolchain declarations found"
fi

Repository: utopia-php/mongo

Length of output: 26517


🌐 Web query:

PHP 8.3 typed class constant arrays declared type required const array syntax

💡 Result:

As of PHP 8.3, you can explicitly declare types for class constants, including arrays [1][2]. The syntax requires placing the type declaration between the visibility modifier (if present) and the constant name [3][2]. For an array type, the syntax is as follows: public const array MY_ARRAY = ['value1', 'value2']; Key details regarding typed class constants in PHP 8.3: - Strict Typing: Class constants are always evaluated strictly, regardless of the declare(strict_types=1) directive [3][4]. - Covariance: If a constant is overridden in a child class or interface implementation, the type cannot be widened [3][4]. - Array Content: When using the array type, the contents of the array must be scalar types [2][5]. - Backward Compatibility: Declaring a type for a class constant is a breaking change for existing code where child classes might redefine the constant with a different type [3]. All subclasses and implementations must adhere to the declared type, otherwise, a fatal error will occur [3]. - Supported Types: Aside from array, you can use scalar types such as bool, int, float, and string, as well as nullable, union, intersection, and DNF types [3][4][2]. void, callable, and never types are not supported [4].

Citations:


Raise the minimum supported PHP version.

private const array is a PHP 8.3 typed class constant, but composer.json still declares "php": ">=8.0", so Composer can install this on PHP 8.0–8.2 where it will fail with a parse error. Align the package version constraint with the PHP 8.3 syntax.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Client.php` around lines 89 - 90, Update the composer.json PHP version
constraint from >=8.0 to >=8.3 to match the typed class constant syntax used by
Client::NOT_WRITABLE_PRIMARY_ERRORS.

Comment thread src/Client.php
@abnegate
abnegate force-pushed the fix/not-writable-primary-reconnect branch from d62f3e1 to 2ab78cf Compare July 30, 2026 05:14
@abnegate
abnegate merged commit 78818fd into main Jul 30, 2026
5 checks passed
@abnegate
abnegate deleted the fix/not-writable-primary-reconnect branch July 30, 2026 05:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants