Skip to content

Clean up cursor management - #912

Merged
benc-db merged 18 commits into
mainfrom
dont_expose_cursors
Feb 5, 2025
Merged

benc-db merged 18 commits into
mainfrom
dont_expose_cursors

Conversation

@benc-db

@benc-db benc-db commented Jan 24, 2025 •

Copy link
Copy Markdown
Collaborator

Description

This is a step towards improving cancellation behavior by limiting the exposure of cursors, and preventing further operations on connections/cursors that have already been scheduled for close/cancel. I'm not positive this fixes the issue that kicked off this work, as I have had a hard time reproing the issue (dbt operation gets cancelled, query continues running). But, at a minimum, this should reduce the likelihood of that happening by ensuring everything is cancelled prior to closing by making sure that once cancellation has started, no new operations start running (hence the lock). Further, no raw cursors are handed out, and we ensure that every cursor is closed before the next cursor for the connection is opened. Since the connections have thread affinity, and within a thread we have sequential operation, there should be no reason to keep multiple cursors open from the same connection at the same time. We also now have much more extensive unit testing of the connection/cursor management behavior than previously.

This PR starts removing the event classes as well. In the end I think they added more overhead without actually improving readability, since we don't have access to real event classes that they use in Dbt.

Apologies for the random files with formatting changes; not sure why Ruff decided those needed to change. The import files to review are connections.py, handle.py, and test_handle.py.

Checklist

  • I have run this code in development and it appears to resolve the stated issue
  • This PR includes tests, or tests are not required/relevant for this PR
  • I have updated the CHANGELOG.md and added information about my change to the "dbt-databricks next" section.

Comment thread dbt/adapters/databricks/handle.py Outdated
return f"Connection(session-id={session_id})"


def clean_sql(sql: str) -> str:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Looking for recommendations on how we want to handle pure functions. They can live raw like this, or they could be static methods on a class. That class could be DatabricksHandle, or it could be a separate class that acts as a namespace, since the operations don't actually operate on DatabricksHandles (they operate on data that is private to them).

Revert now that PAT has been updated
Comment thread dbt/adapters/databricks/handle.py Resolved

class CursorWrapper:
"""
Wrap the DBSQL cursor to abstract the details from DatabricksConnectionManager.

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.

it would better if it can also implement __enter__ and __exit__ so that it can be open with with statement which can automatically be closed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I'll look into this; I agree that it is better ergonomically, I just know there are a couple of paths in the code today that create the cursor and return it to another function that later gets the results. I might need to restructure the connection manager to make use of that. For this PR, I can implement the enter/exit, and then maybe switch to using it in another PR.

Comment thread dbt/adapters/databricks/handle.py Outdated

def __init__(
self,
conn: Optional[Connection],

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.

in which case conn will be None? Why it needs to construct with None?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

When I was testing, I found cases where PySQL would return None for the connection without raising an error. In connection manager, the existing code expects these cases. I will look into it, because this class without a connection is a little strange.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Found and fixed, thanks.

Comment thread dbt/adapters/databricks/handle.py Outdated
def session_id(self) -> str:
if self._conn:
return self._conn.get_session_id_hex()
return "N/A"

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.

should it be None?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reasonable. This is replicating existing functionality, but since it's only used in logging, it should be fine to switch.

Comment thread dbt/adapters/databricks/utils.py Outdated

def handle_exceptions_as_warning(op: Callable[[], None], log_gen: ExceptionToStrOp) -> None:
try:
return op()

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.

nit: the declaration of op returns None, but what if op returns some value instead of None, so it does not match the return type of this function.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good point. This is something that would be fine in a statically typed world, but wrong in python lol.

Comment thread dbt/adapters/databricks/handle.py Outdated

def _cleanup(
self,
connect_op: ConnectionOp,

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.

given this is the private function, can it do the cleanup (close cursor) directly?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I'm not certain which of two things you mean:
a.) why do we need to take a function as an argument or
b.) why do we call an operation against the cursor wrapper rather than the underlying cursor?

If the question is 'a', it's because we have two scenarios with identical structure, but slightly different details (i.e. in one we need to call close and in the other we need to call cancel). The alternative to taking a function as an argument is just to have the two public methods with identical structure.

If the question is 'b', it's so that I can make sure that if any other parts of the code are still holding the CursorWrapper, if they try to close it again we don't get a warning from PySQL (that users keep thinking is an error :/).

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.

Actually I mean if _cleanup is a private function, can we do all the actual cleanup logic inside. e.g.do the cursor.close in the _cleanup rather than in the op function.

Comment thread dbt/adapters/databricks/handle.py Outdated
utils.handle_exceptions_as_warning(lambda: cleanup(self._cursor), failLog)

def fetchall(self) -> Sequence[tuple]:
return self._cursor.fetchall()

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.

should it check open before fetch?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Probably. The question then is should we no op or raise an exception...I guess this is where the context manager is a good option, because I'm inclined to no op (since the only case where this should happen is if someone is holding a cursorwrapper after a program cancel has been requested), but if this happens in any scenario other than cancel, it means an assumption in the code execution has been violated and should fail with an assert.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Since I raised as an exception on connection, also raising here. I think the calling code won't know what to do if we no op, so better to halt execution immediately. Would prefer we cleanup quietly, but this is the best I think we can do for now.

Comment thread dbt/adapters/databricks/handle.py Outdated

def _cleanup(
self,
connect_op: ConnectionOp,

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.

Actually I mean if _cleanup is a private function, can we do all the actual cleanup logic inside. e.g.do the cursor.close in the _cleanup rather than in the op function.

jackyhu-db
jackyhu-db previously approved these changes Feb 5, 2025
@benc-db
benc-db merged commit 75a71dd into main Feb 5, 2025
sd-db added a commit that referenced this pull request Jun 23, 2026
### Description

Removes internal logging-event classes that have had **no call sites**
since the cursor-management (#910/#912) and pipeline (#849) refactors.
They are dead code: zero consumers across source and tests, no
`events/__init__.py` re-export, and no dynamic/string references. Git
history confirms they were once used and their consumers were later
deleted (orphaned, not never-wired).

Removed:
- `events/credential_events.py` — whole module (`CredentialLoadError`,
`CredentialSaveError`, `CredentialShardEvent`)
- `events/pipeline_events.py` — whole module (`PipelineEvent`,
`PipelineRefresh`, `PipelineRefreshError`)
- `events/connection_events.py` — `ConnectionReset`, `ConnectionReuse`,
`ConnectionIdleClose`, `ConnectionCreated`

Kept (still live or still a needed base): `ConnectionEvent`,
`ConnectionCreateError`, the `ConnectionWrapperEvent` base,
`ConnectionCreate`, and all of `events/base.py` /
`events/other_events.py` / `logging.py`.

Targeting `1.13.latest` rather than a patch: although these were never
public API, they sit at importable paths, so the removal is scoped to
the next minor as a safety margin.

Full unit suite passes (1081 passed, 6 skipped); ruff/ruff-format/mypy
clean.

### Checklist

- [x] I have run this code in development and it appears to resolve the
stated issue
- [x] This PR includes tests, or tests are not required/relevant for
this PR
- [x] I have updated the `CHANGELOG.md` and added information about my
change to the "dbt-databricks next" section.

This branch was previously deployed

1 inactive deployment
azure-prod — 44a9da8b Deployed Feb 5, 2025 by benc-db
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