Skip to content

ref: fix typing for sentry.db.postgres.base #96694

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,6 @@ module = [
"sentry.api.endpoints.organization_events_spans_performance",
"sentry.api.endpoints.organization_releases",
"sentry.api.paginator",
"sentry.db.postgres.base",
"sentry.eventstore.models",
"sentry.identity.gitlab.provider",
"sentry.identity.oauth2",
Expand Down
44 changes: 20 additions & 24 deletions src/sentry/db/postgres/base.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import psycopg2 as Database
from types import TracebackType
from typing import Self

# Some of these imports are unused, but they are inherited from other engines
# and should be available as part of the backend ``base.py`` namespace.
import psycopg2
from django.db.backends.postgresql.base import DatabaseWrapper as DjangoDatabaseWrapper
from django.db.backends.postgresql.operations import DatabaseOperations

Expand Down Expand Up @@ -61,10 +61,7 @@ def clean_bad_params(params):


class CursorWrapper:
"""
A wrapper around the postgresql_psycopg2 backend which handles various events
from cursors, such as auto reconnects and lazy time zone evaluation.
"""
"""A wrapper around the postgresql_psycopg2 backend which handles auto reconnects"""

def __init__(self, db, cursor):
self.db = db
Expand All @@ -76,6 +73,18 @@ def __getattr__(self, attr):
def __iter__(self):
return iter(self.cursor)

def __enter__(self) -> Self:
self.cursor.__enter__()
return self

def __exit__(
self,
type: type[BaseException] | None,
value: BaseException | None,
traceback: TracebackType | None,
) -> None:
return self.cursor.__exit__(type, value, traceback)

@capture_transaction_exceptions
@auto_reconnect_cursor
@more_better_error_messages
Expand All @@ -92,29 +101,16 @@ def executemany(self, sql, paramlist=()):


class DatabaseWrapper(DjangoDatabaseWrapper):
SchemaEditorClass = DatabaseSchemaEditorProxy
SchemaEditorClass = DatabaseSchemaEditorProxy # type: ignore[assignment] # a proxy class isn't exactly the original type
queries_limit = 15000

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ops = DatabaseOperations(self)

@auto_reconnect_connection
def _set_isolation_level(self, level):
return super()._set_isolation_level(level)

@auto_reconnect_connection
def _cursor(self, *args, **kwargs):
return super()._cursor()

Comment on lines -106 to -108
Copy link
Member Author

Choose a reason for hiding this comment

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

def cursor just calls def _cursor anyway so this should be a tiny simplification

# We're overriding this internal method that's present in Django 1.11+, because
# things were shuffled around since 1.10 resulting in not constructing a django CursorWrapper
# with our CursorWrapper. We need to be passing our wrapped cursor to their wrapped cursor,
# not the other way around since then we'll lose things like __enter__ due to the way this
# wrapper is working (getattr on self.cursor).
def _prepare_cursor(self, cursor):
cursor = super()._prepare_cursor(CursorWrapper(self, cursor))
return cursor
def cursor(self) -> CursorWrapper:
return CursorWrapper(self, super().cursor())

def close(self, reconnect=False):
"""
Expand All @@ -124,7 +120,7 @@ def close(self, reconnect=False):
if not self.connection.closed:
try:
self.connection.close()
except Database.InterfaceError:
except psycopg2.InterfaceError:
# connection was already closed by something
# like pgbouncer idle timeout.
pass
Expand Down
2 changes: 1 addition & 1 deletion src/sentry/db/postgres/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def inner(self, *args, **kwargs):
raise

self.db.close(reconnect=True)
self.cursor = self.db._cursor()
self.cursor = self.db.cursor()
Copy link
Contributor

Choose a reason for hiding this comment

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

Bug: Auto-Reconnect Cursor Wraps Incorrectly

The auto_reconnect_cursor decorator, when applied to CursorWrapper methods, now incorrectly re-initializes self.cursor to another CursorWrapper instance instead of the raw underlying cursor. This happens because self.db.cursor() returns a CursorWrapper, leading to improper nested wrapping and breaking the CursorWrapper's delegation mechanism.

Locations (1)
Fix in Cursor Fix in Web

Copy link
Member Author

Choose a reason for hiding this comment

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

that's what already happens silly bot


Comment on lines +24 to 25
Copy link
Contributor

Choose a reason for hiding this comment

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

Potential bug: Auto-reconnect logic double-wraps cursors, causing `AttributeError` or recursion when `self.cursor` is reassigned after reconnection.
  • Description: The CursorWrapper expects self.cursor to be the underlying psycopg2 cursor. However, during a database reconnection, the auto_reconnect_cursor decorator at src/sentry/db/postgres/decorators.py:24 assigns self.db.cursor() to self.cursor. Since self.db.cursor() now returns a CursorWrapper, this results in a CursorWrapper containing another CursorWrapper. This double-wrapping can lead to AttributeError exceptions, infinite recursion, or method resolution issues when accessing cursor-specific methods, effectively crashing the application during reconnection events.
  • Suggested fix: Modify the auto_reconnect_cursor decorator to ensure self.cursor is assigned the raw psycopg2 cursor, not another CursorWrapper, after reconnection. This might involve adjusting self.db.cursor()'s behavior or explicitly unwrapping the cursor before assignment to prevent nested wrappers.
    severity: 0.9, confidence: 0.95

Did we get this right? 👍 / 👎 to inform future reviews.

Copy link
Member Author

Choose a reason for hiding this comment

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

you too, read the original code

return func(self, *args, **kwargs)

Expand Down
Loading