Skip to content

Invalid SessionHandle: SessionHandle [...] #204

Done

Description

@noctuid

This is not the same as #160 as the error message is slightly different and the fix for that does not work. This happens well before an hour or any timeout could be reached (I've seen it within minutes of starting our backend locally before). It looks like there are other situations where this can happen besides a timeout.

My understanding is that the sqlalchemy dialect should let sqlalchemy know to invalidate the connection rather than just failing/erroring (e.g. see here), though I don't know enough to understand the correct way to do that. Based on the sqlalchemy documentation,it sounds like the pre-ping is dialect-specific. Not sure if that needs to be changed or something else. The sqlalchemy documentation has an example for handling specific errors as disconnects, but it's only for sqlalchemy 2.0, so that's not really useful here.

Activity

  1. susodapop commented on Aug 18, 2023

    @susodapop
    Contributor

    What version of databricks-sql-connector do you have installed? Can you provide any reproduction steps?

  2. noctuid commented on Aug 18, 2023

    @noctuid
    Author

    2.7.0.

    I can't provide reproduction steps because it does not happen consistently, but I see this error at least one time most weeks.

    It's worth noting that this also happened when we were using sqlalchemy-databricks and also for that pyhive dialect (haven't used but see the previously linked ticket). Again, my understanding based on the sqlalchemy documentation/code is that ideally the dialect implementation would check for this error "Invalid SessionHandle: SessionHandle" and invalidate the connection. I'm not sure if it is as simple as checking for this in the is_disconnect method like in this sqlalchemy dialect. I don't think there is a specific code associated with these errors though, only the message. Not sure if it will be helpful, but I will add an is_disconnect in our code and see if that actually fixes the issue.

  3. susodapop commented on Aug 31, 2023

    @susodapop
    Contributor

    Thanks @noctuid did adding this is_disconnect effectively workaround your issue? The concern we have with automatically dropping and re-creating the session is that sessions have state, which we'd need to somehow track and re-create when building a new session.

  4. noctuid commented on Sep 1, 2023

    @noctuid
    Author

    We just implemented the change and are still testing/waiting to determine whether it works. I believe even with an is_disconnect function there will still be an error if this happens in the middle of a query or in between queries (that's what I saw when testing marking an invalid query as a disconnect), so this doesn't help in that case. We are using pool_pre_ping=True and mainly hoping that it will prevent issues if this is detected in the pre-ping or at least that the connection will be invalidated, so the next API call will succeed. Right now when this happens, our application will continuously try to use the invalid connections. We previously used a custom execute method that tried to catch this error and manually invalidate the connection, but that was not working fully.

    This may not be very helpful, but I did not see this issue in 0.9.4. The databricks-sql-python repo history doesn't go back that far, so I'm not sure it's even the same codebase. We have two applications using this library. The first was using version 0.9.4 without sqlalchemy until recently (didn't see the Invalid SessionHandle issue), and the other was using >2 with the sqlalchemy-databricks library (did see the Invalid SessionHandle issue). It looks like the Invalid SessionHandle issue appeared in the 2nd application when moving from 0.9.4 to 2.0.2 last August. After moving from 0.9.4 to 2.7.0 in the first application recently (still not using the sqlalchemy), we now see the Invalid SessionHandle issue there as well.

  5. noctuid commented on Oct 10, 2023

    @noctuid
    Author

    Our disconnect check basically looks like this (with some logging removed):

    def is_databricks_disconnect(self, e, _connection, _cursor):
        if "Invalid SessionHandle: SessionHandle" in str(e):
           return True
        return False
    ...
    DatabricksDialect.is_disconnect = is_databricks_disconnect

    It appears to be working as long as the error is caught in the pre-ping. Before, invalid connections would never be removed from the pool until the pool_recycle time was reached. We still see the issue in long running endpoints (e.g. >10 minutes) when using fastapi dependencies (fastapi sqlalchemy docs for reference). We are currently trying to create new sessions in that endpoint instead of reusing the same session for the entire duration to hopefully fix the problem, but so far adding an is_disconnect method is a better solution than anything else we've tried.

  6. tiaaburton commented on Oct 16, 2023

    @tiaaburton

    I have faced Attempted to close session that was already closed: Invalid SessionHandle: SessionHandle [...] when using the context manager version and even after adding pool_pre_ping=True. Using the example in the main repo README where the context is not managed allowed me to perform a try and except on the cursor.close() and to either close the connection or catch the InvalidSession error, pass, and re-establish a new connection without having my program crash.

    For example, my starting code was similar to the snippet below:

    with sql.connect(
        server_hostname=host,
        http_path=http_path,
        access_token=access_token
    ) as connection:
        with connection.cursor() as cursor:
    
            for _ in range(2):
                cursor.execute('SELECT * FROM RANGE(10)')
                result = cursor.fetchall()
                for row in result:
                  print(row)
                time.sleep(60 * 15) # Example pause to represent another action in the code that requires significant time
    
    # Finishes by raising the issue and exiting the program.
    

    However, this method caused no issues:

    for _ in range(2):
        connection = sql.connect(
            server_hostname=host,
            http_path=http_path,
            access_token=access_token
        )
        cursor = connection.cursor()
        cursor.execute('SELECT * FROM RANGE(10)')
        result = cursor.fetchall()
        for row in result:
          print(row)
        time.sleep(60 * 15) # Example pause to represent another action in the code that requires significant time
    
        try:
            cursor.close()
            connection.close()
        except DatabaseError:
            pass
    
    # Finishes by raising the issue, but the program continues.
    

    It's less elegant but gives a little bit more control, and that error is no longer an issue for successive queries databrick queries. I have a for loop that is iterating through about 30 entities, and each iteration has about 3 queries. My workflow uses Google Cloud APIs, occasionally hits the quotas, and requires multiple pauses before continuing. I have seen no issues with removing the context manager and my program finishes in 40 minutes.

  7. Bidek56 commented on Oct 18, 2025

    @Bidek56

    @noctuid Where do I add the DatabricksDialect.is_disconnect = is_databricks_disconnect code as per #204 (comment)

    I am using databricks-sqlalchemy and I am facing a similar
    sqlalchemy.exc.DatabaseError: (databricks.sql.exc.DatabaseError) Invalid SessionHandle: SessionHandle error.

  8. noctuid commented on Oct 18, 2025

    @noctuid
    Author

    Anywhere that will run during application start. I think the only difference for the new separate databricks-sqlalchemy library is where to import DatabricksDialect from.

  9. cathleeny commented on Dec 3, 2026

    @cathleeny
    Collaborator

    This is fixed in databricks-sqlalchemy 2.0.9 by databricks/databricks-sqlalchemy#54: the dialect implements do_ping, so the pool can detect an expired session and replace the connection. To pick this up:

    1. Upgrade to databricks-sqlalchemy>=2.0.9.
    2. Create the engine with pool_pre_ping=True, e.g. create_engine(url, pool_pre_ping=True).

    Note that the SQLAlchemy dialect now lives in databricks/databricks-sqlalchemy. Closing as completed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions