Skip to content

FEAT: retry transient failures in Cursor.execute() with RetryPolicy (GH-682) - #908

Open
om singhal (Om-singhaI) wants to merge 1 commit into
microsoft:mainfrom
Om-singhaI:om/feat/retry-policy-statement-v2
Open

om singhal (Om-singhaI) wants to merge 1 commit into
microsoft:mainfrom
Om-singhaI:om/feat/retry-policy-statement-v2

Conversation

@Om-singhaI

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

GitHub Issue: #682


Summary

Second half of #682, after #751. Adds statement retry: retry_policy= on Connection.cursor() and on a single Cursor.execute() call, with the same RetryPolicy, backoff and full jitter that #751 merged. Without a policy nothing changes.

How it works

  • The loop wraps only the native execute and its check_error. Parameter conversion and everything before it run once.
  • The SQLSTATE comes from one extra DDBCSQLCheckError read before check_error raises. ODBC keeps the diagnostic records until the next call on the handle other than a diagnostic read, and executemany already reads a failed handle twice. If that read fails, the statement is not retried. helpers.py and exceptions.py are untouched.
  • A statement is retried only while Connection.autocommit is True at the moment it failed. With autocommit off the driver can't see the transaction state, so the error is raised at once and the app retries its own transaction. That read runs last, and an error from it, or any value other than True, counts as a no. connect() defaults to autocommit off, so statement retry only takes effect once the app turns autocommit on.
  • Autocommit on still isn't exactly once. A procedure or batch replays work it already committed, and a timeout can land after the server committed. A transaction opened in SQL text (BEGIN TRANSACTION or SET IMPLICIT_TRANSACTIONS ON) is invisible to the driver too, so after a deadlock only the failed statement runs again. Cursor.execute says so.
  • The new RetryPolicy.is_retriable_on_same_connection() narrows the policy for this scope. Class 08, HYT01 and 40003 are never retried on the same connection, so of the defaults only HYT00 and 40001 are. A custom set gets the same filter.
  • Each retry runs on a fresh statement handle (the failed one is released, as today) with a fresh copy of the parameters, since the native detector rewrites list slots in place. A parameterized statement is prepared again on the new handle.
  • Whether the cursor is closed and whether autocommit is on are checked again after the delay.
  • Retry logging follows connect(): a warning per retry, and a warning when it gives up after a retry, also when the native call raises. Each failed attempt still logs what a failed execute logs today (the check_error error lines and the Execute failed, resetting cursor warning), since helpers.py is untouched. Refusing a listed code on the first attempt, for example with autocommit off, is a debug line. None of the retry lines include SQL text or parameter values.

Scope

  • Covered: Cursor.execute(). The row by row fallback of executemany() and batch_execute(reuse_cursor=...) go through it, so they follow the cursor's policy.
  • Not covered: Connection.execute() (new cursor, no policy), the batched executemany() path, bulk copy and the async cursor.
  • A cursor never picks up the policy given to connect(). The issue sketched inheritance; I kept it explicit so a connect policy can't start replaying statements by itself. If you'd rather inherit, it's a two line fallback in Cursor.__init__.
  • Azure SQL throttling is still out. It needs the native error number, which FEAT: Expose SQLSTATE (and native error number) as attributes on exception objects #581 would expose, so I left it rather than match on message text.

Testing

  • tests/test_043_cursor_retry_policy.py: 44 passed, no server. The native execute and diagnostic calls are faked, and retry._sleep and _random are patched so delays are asserted exactly. It covers one attempt and no extra read without a policy, delays [1.0, 2.0] for two failures, the original values on a fresh handle for every attempt, a reused plan prepared again, autocommit off or reading back as anything but True, a failed autocommit read and the checks after the delay, 08S01, 40003, HYT01 and unlisted codes not retried, the give up log lines, TypeError for a bad retry_policy, and no SQL or values in the log lines.
  • tests/test_028_stub_signature_parity.py now also pins Connection.cursor, Cursor.__init__ and Cursor.execute: 7 passed. tests/test_027_retry_policy.py: 74 passed.
  • The strict typing gate (tests/test_typing.py -m typing, mypy 2.3.1) is clean, and so are black and flake8 with the CI flags.
  • Not run against a live server.

…icrosoftGH-682)

Adds retry_policy= on Connection.cursor() and a per call override on
Cursor.execute(). A cursor never inherits the policy given to connect(), and
without a policy nothing changes. The loop wraps only the native execute and
its error check, runs each retry on a fresh handle with a fresh copy of the
parameters, and retries only while autocommit is on, checked before and after
the delay. Class 08, HYT01 and 40003 are never retried on the same connection;
the new RetryPolicy.is_retriable_on_same_connection() says which codes are.
@azure-pipelines

Copy link
Copy Markdown
Contributor
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

PR Performance Report

Performance could not be assessed.

No matching performance run appeared within the 220-minute wait for 4a58647fa2e257186f78cfe5526ae84e964ba4f3. No result is available.

@jahnvi480

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Contributor
Azure Pipelines:
Successfully started running 1 pipeline(s).

@github-actions

Copy link
Copy Markdown

Code Coverage Report

Diff coverage Overall coverage Lines covered
100% 86% 11867 of 13754

Files needing attention

mssql_python.pybind.performance_counter.hpp: 0.7%
mssql_python.pybind.logger_bridge.cpp: 57.9%
mssql_python.pybind.ddbc_bindings.h: 64.5%
mssql_python.pybind.logger_bridge.hpp: 70.8%
mssql_python._native_fetch.py: 77.7%
mssql_python.pybind.ddbc_bindings.cpp: 81.4%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.pybind.connection.connection_pool.cpp: 82.5%
mssql_python.pybind.connection.connection.cpp: 83.1%
mssql_python.logging.py: 86.8%

View Azure DevOps build

Comment thread mssql_python/cursor.py
check_error(ddbc_sql_const.SQL_HANDLE_STMT.value, self.hstmt, ret)
except Exception as e: # pylint: disable=broad-exception-caught
logger.warning("Execute failed, resetting cursor: %s", e)
self._reset_cursor()

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.

Missing give-up warning: calls _reset_cursor() before final retry logging. If handle recreation fails after attempt 2, execution exits without the promised attempt-count/reason warning. Log that failure while preserving exception propagation.

assert "autocommit is off" in warnings[1] and "after the delay" in warnings[1]


def test_reset_cursor_failure_after_a_failed_attempt_propagates_unwrapped(

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.

test_043_cursor_retry_policy.py:640 covers reset failure only on attempt 1. Add a case with two failures and fail_alloc_at=3, asserting the final warning. Also commit live timeout regression coverage—the current fake-only tests cannot verify native diagnostics and re-preparation.

@jahnvi480

Copy link
Copy Markdown
Contributor

om singhal (@Om-singhaI) Please update your PR and resolve the comments that you have received

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