Skip to content

Commit 9e92ecb

Browse files
author
Jesse Whitehouse
committed
Update docstrings and comments
Signed-off-by: Jesse Whitehouse <jesse.whitehouse@databricks.com>
1 parent 10180a2 commit 9e92ecb

2 files changed

Lines changed: 95 additions & 36 deletions

File tree

‎src/databricks/sql/auth/retry.py‎

Lines changed: 94 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -37,21 +37,50 @@ def get(cls, value: str):
3737

3838
class DatabricksRetryPolicy(Retry):
3939
"""
40-
41-
Implements the entirety of our retry policy across connectors.
42-
Same as urllib3.Retry but implements retry_wait_min and retry_wait_max as part of its exponential backoff calculation
43-
44-
Retry Policy arguments are defined in the docstring for our ThriftBackend class
45-
46-
delay_default is the time in seconds the connector will wait between requests polling for a GetOperationStatus request.
47-
48-
Retry.allowed_methods is set to POST
49-
Retry.status_forcelist is set to codes 429 and 503
50-
51-
kwargs is used by urllib3 to pass state between successive Retry iterations.
52-
53-
Some of these parameters are counters that change from one retry to the next
54-
Others are like local constants that do not change between retries
40+
Implements our v3 retry policy by extending urllib3's robust default retry behaviour.
41+
42+
See `should_retry()` for details about we do and do not retry.
43+
44+
:param delay_min:
45+
Float of seconds for the minimum delay between retries. Passed to urllib3 as its
46+
backoff_factor.
47+
48+
:param delay_max:
49+
Float of seconds for the maximum delay between retries. Passed to urllib3 as its
50+
backoff_max
51+
52+
:param stop_after_attempts_count:
53+
Integer maximum number of attempts that will be retried. Passed to urllib3 as its
54+
total.
55+
56+
:param stop_after_attempts_duration:
57+
Float of maximum number of seconds from the beginning of the first request that a
58+
request may be retried. This behaviour is not implemented in urllib3.
59+
60+
:param delay_default:
61+
Float of seconds the connector will wait between sucessive GetOperationStatus
62+
requests. This parameter is not used to retry failed network requests. We include
63+
it in this class to keep all retry behaviour encapsulated in this file.
64+
65+
:param force_dangerous_codes:
66+
List of integer HTTP status codes that the connector will retry, even for dangerous
67+
commands like ExecuteStatement. This is passed to urllib3 by extending its status_forcelist
68+
69+
:param _retry_start_time:
70+
Float unix timestamp. Used to monitor the overall request duration across successive
71+
retries. Never set this value directly. Use self.start_retry_time() instead. Users
72+
never set this value. It is set by ThriftBackend immediately before issuing a network
73+
request.
74+
75+
:param _command_type:
76+
CommandType of the current request being retried. Used to modify retry behaviour based
77+
on the type of Thrift command being issued. See self.should_retry() for details. Users
78+
never set this value directly. It is set by ThriftBackend immediately before issuing
79+
a network request.
80+
81+
:param urllib3_kwargs:
82+
Dictionary of arguments that are passed to Retry.__init__. Any setting of Retry() that
83+
Databricks does not override or extend may be modified here.
5584
"""
5685

5786
def __init__(
@@ -130,7 +159,7 @@ def new(self, **urllib3_incremented_counters: typing.Any) -> Retry:
130159
The arguments it passes to `.new()` (total, connect, read, etc.) are those which modified by `.increment()`.
131160
132161
Since our subclass has a new __init__ signature and requires custom state variables, we override the method
133-
to pipe our Databricks-specific state while preserving the super-class's behaviour behaviour.
162+
to pipe our Databricks-specific state while preserving the super-class's behaviour.
134163
"""
135164

136165
# These arguments will match the function signature for self.__init__
@@ -196,7 +225,9 @@ def get_operation_status_delay(self) -> float:
196225
return self.delay_default
197226

198227
def start_retry_timer(self):
199-
"""Timer is used to monitor the overall time across successive requests"""
228+
"""Timer is used to monitor the overall time across successive requests
229+
230+
Should only be called by ThriftBackend before sending a Thrift command"""
200231
self._retry_start_time = time.time()
201232

202233
def check_timer_duration(self):
@@ -212,17 +243,13 @@ def check_proposed_wait(self, proposed_wait: Union[int, float]) -> None:
212243
f"Retry request would exceed Retry policy max retry duration of {self.stop_after_attempts_duration} seconds"
213244
)
214245

215-
def get_backoff_time(self) -> float:
216-
"""Calls urllib3's built-in get_backoff_time but raises an exception if stop_after_attempts_duration would be exceeded.
217-
If proposed backoff exceeds the configured delay_max, the delay_max is used instead"""
218-
219-
proposed_backoff = super().get_backoff_time()
220-
proposed_backoff = min(proposed_backoff, self.delay_max)
221-
self.check_proposed_wait(proposed_backoff)
246+
def sleep_for_retry(self, response: BaseHTTPResponse) -> bool: # type: ignore
247+
"""Sleeps for the duration specified in the response Retry-After header, if present
222248
223-
return proposed_backoff
249+
A MaxRetryDurationError will be raised if doing so would exceed self.max_attempts_duration
224250
225-
def sleep_for_retry(self, response: BaseHTTPResponse) -> bool: # type: ignore
251+
This method is only called by urllib3 internals.
252+
"""
226253
retry_after = self.get_retry_after(response)
227254
if retry_after:
228255
self.check_proposed_wait(retry_after)
@@ -231,18 +258,47 @@ def sleep_for_retry(self, response: BaseHTTPResponse) -> bool: # type: ignore
231258

232259
return False
233260

234-
def should_retry(self, method: str, status_code: int) -> Tuple[bool, str]:
235-
"""We retry by default with the following exceptions:
261+
def get_backoff_time(self) -> float:
262+
"""Calls urllib3's built-in get_backoff_time.
236263
237-
Any 200 status code -> Because the request succeeded
238-
Any 501 status code -> Because it's not recoverable ever. Raise a NonRecoverableNetworkError.
239-
Any 404 if the command was CancelOperation or CloseSession and this is not the first request
240-
Any ExecuteStatement command unless it has code 429 or 504
264+
Never returns a value larger than self.delay_max
265+
A MaxRetryDurationError will be raised if the calculated backoff would exceed self.max_attempts_duration
266+
267+
Note: within urllib3, a backoff is only calculated in cases where a Retry-After header is not present
268+
in the previous unsuccessful request.
241269
"""
242270

243-
# TODO: Port in the NoRetryReason enum for logging?
244-
# TODO: something needs to go here about max wall-clock duration.
245-
# It doesn't belong in the backoff calculation method
271+
proposed_backoff = super().get_backoff_time()
272+
proposed_backoff = min(proposed_backoff, self.delay_max)
273+
self.check_proposed_wait(proposed_backoff)
274+
275+
return proposed_backoff
276+
277+
def should_retry(self, method: str, status_code: int) -> Tuple[bool, str]:
278+
"""This method encapsulates the connector's approach to retries.
279+
280+
We always retry a request unless one of these conditions is met:
281+
282+
1. The request received a 200 (Success) status code
283+
Because the request succeeded. No retry is required.
284+
2. The request received a 501 (Not Implemented) status code
285+
Because this request can never succeed.
286+
3. The request received a 404 (Not Found) code and the request CommandType
287+
was CloseSession or CloseOperation. This code indicates that the session
288+
or cursor was already closed. Further retries will always return the same
289+
code.
290+
4. The request CommandType was ExecuteStatement and the HTTP code does not
291+
appear in the default status_forcelist or force_dangerous_codes list. By
292+
default, thisd means ExecuteStatement is only retried for codes 429 and 503.
293+
This limit prevents automatically retrying non-idempotent commands that could
294+
be destructive.
295+
296+
5. OSErrors (handled automatically by urllib3 outside this method)
297+
6. Redirects (handled automatically by urllib3 outside this method)
298+
299+
Returns True if the request should be retried. Returns False or raises an exception
300+
if a retry would violate the configured policy.
301+
"""
246302

247303
# Request succeeded. Don't retry.
248304
if status_code == 200:
@@ -309,7 +365,9 @@ def is_retry(
309365
self, method: str, status_code: int, has_retry_after: bool = False
310366
) -> bool:
311367
"""
312-
Overriden to support varied behaviour based on the current CommandType
368+
Called by urllib3 when determining whether or not to retry
369+
370+
Logs a debug message if the request will be retried
313371
"""
314372

315373
should_retry, msg = self.should_retry(method, status_code)

‎src/databricks/sql/thrift_backend.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,7 @@ def __init__(
220220

221221
self._request_lock = threading.RLock()
222222

223+
# TODO: Move this bounding logic into DatabricksRetryPolicy for v3 (PECO-918)
223224
def _initialize_retry_args(self, kwargs):
224225
# Configure retries & timing: use user-settings or defaults, and bound
225226
# by policy. Log.warn when given param gets restricted.

0 commit comments

Comments
 (0)