Skip to content

Conversation

@sylwiaszunejko
Copy link
Collaborator

@sylwiaszunejko sylwiaszunejko commented Dec 18, 2025

This PR fixes inefficiencies in the host initialization mechanism when bootstrapping a cluster.

Previously, the driver created Host instances with connections from the contact points provided in the cluster configuration using random host IDs. After establishing the control connection and reading from system.peers, these initial Host instances were discarded and replaced with new ones created using the correct host metadata. This approach resulted in unnecessary creation and teardown of multiple connections.

Changes

  • The control connection is now initialized only using the endpoints specified in the cluster configuration.
  • After a successful control connection is established, the driver reads from system.local and system.peers.
  • Based on this metadata, Host instances are created with the correct host_id values.
  • Connections are then initialized directly on these properly constructed Host instances.

Fixes: #619

@sylwiaszunejko
Copy link
Collaborator Author

Some tests are still failing, but I wanted to ask if the direction is good @dkropachev

@sylwiaszunejko
Copy link
Collaborator Author

@Lorak-mmk maybe you know, why this test assumes that the new_host should be different?

def test_get_control_connection_host(self):
        """
        Test to validate Cluster.get_control_connection_host() metadata

        @since 3.5.0
        @jira_ticket PYTHON-583
        @expected_result the control connection metadata should accurately reflect cluster state.

        @test_category metadata
        """

        host = self.cluster.get_control_connection_host()
        assert host == None

        self.session = self.cluster.connect()
        cc_host = self.cluster.control_connection._connection.host

        host = self.cluster.get_control_connection_host()
        assert host.address == cc_host
        assert host.is_up == True

        # reconnect and make sure that the new host is reflected correctly
        self.cluster.control_connection._reconnect()
        new_host = self.cluster.get_control_connection_host()
        assert host != new_host

@Lorak-mmk
Copy link

Lorak-mmk commented Dec 18, 2025

I have no idea.
In Rust Driver we have logic that if CC breaks then we try to connect it to all other hosts (because the one it was connected to is presumed non-working for now).
I see no such logic in Python Driver. This part was added in commit 2796ee5:
image

Was this test passing until now and non-flaky? If so, then perhaps there is such logic somewhere.

@Lorak-mmk
Copy link

Now that I think of it: I see that driver uses LBP to decide order of hosts to connect. See _connect_host_in_lbp and _reconnect_internal.
LBP uses by default is Round Robin, so on reconnect it will start from a different host than at the beginning, right? It would explain why each CC reconnect should land at different host in healthy cluster.

@sylwiaszunejko
Copy link
Collaborator Author

Now that I think of it: I see that driver uses LBP to decide order of hosts to connect. See _connect_host_in_lbp and _reconnect_internal. LBP uses by default is Round Robin, so on reconnect it will start from a different host than at the beginning, right? It would explain why each CC reconnect should land at different host in healthy cluster.

Makes sense, second question: in this test:

def test_profile_lb_swap(self):
        """
        Tests that profile load balancing policies are not shared

        Creates two LBP, runs a few queries, and validates that each LBP is execised
        seperately between EP's

        @since 3.5
        @jira_ticket PYTHON-569
        @expected_result LBP should not be shared.

        @test_category config_profiles
        """
        query = "select release_version from system.local where key='local'"
        rr1 = ExecutionProfile(load_balancing_policy=RoundRobinPolicy())
        rr2 = ExecutionProfile(load_balancing_policy=RoundRobinPolicy())
        exec_profiles = {'rr1': rr1, 'rr2': rr2}
        with TestCluster(execution_profiles=exec_profiles) as cluster:
            session = cluster.connect(wait_for_all_pools=True)

            # default is DCA RR for all hosts
            expected_hosts = set(cluster.metadata.all_hosts())
            rr1_queried_hosts = set()
            rr2_queried_hosts = set()

            rs = session.execute(query, execution_profile='rr1')
            rr1_queried_hosts.add(rs.response_future._current_host)
            rs = session.execute(query, execution_profile='rr2')
            rr2_queried_hosts.add(rs.response_future._current_host)

            assert rr2_queried_hosts == rr1_queried_hosts

in this tests it is assumed that both queries should use the same host, as they use different instances of RoundRobinPolicy and they start from the same host? But how this can be true if the position when we start is randomized here: https://github.com/scylladb/python-driver/blob/master/cassandra/policies.py#L182

@Lorak-mmk
Copy link

No idea. Perhaps populate is not called for those policies for some reason, and they are populated using on_up/down etc?
Try to print a log / stacktrace in populate and run this test.

@sylwiaszunejko
Copy link
Collaborator Author

Now that I think of it: I see that driver uses LBP to decide order of hosts to connect. See _connect_host_in_lbp and _reconnect_internal. LBP uses by default is Round Robin, so on reconnect it will start from a different host than at the beginning, right? It would explain why each CC reconnect should land at different host in healthy cluster.

Makes sense, second question: in this test:

def test_profile_lb_swap(self):
        """
        Tests that profile load balancing policies are not shared

        Creates two LBP, runs a few queries, and validates that each LBP is execised
        seperately between EP's

        @since 3.5
        @jira_ticket PYTHON-569
        @expected_result LBP should not be shared.

        @test_category config_profiles
        """
        query = "select release_version from system.local where key='local'"
        rr1 = ExecutionProfile(load_balancing_policy=RoundRobinPolicy())
        rr2 = ExecutionProfile(load_balancing_policy=RoundRobinPolicy())
        exec_profiles = {'rr1': rr1, 'rr2': rr2}
        with TestCluster(execution_profiles=exec_profiles) as cluster:
            session = cluster.connect(wait_for_all_pools=True)

            # default is DCA RR for all hosts
            expected_hosts = set(cluster.metadata.all_hosts())
            rr1_queried_hosts = set()
            rr2_queried_hosts = set()

            rs = session.execute(query, execution_profile='rr1')
            rr1_queried_hosts.add(rs.response_future._current_host)
            rs = session.execute(query, execution_profile='rr2')
            rr2_queried_hosts.add(rs.response_future._current_host)

            assert rr2_queried_hosts == rr1_queried_hosts

in this tests it is assumed that both queries should use the same host, as they use different instances of RoundRobinPolicy and they start from the same host? But how this can be true if the position when we start is randomized here: https://github.com/scylladb/python-driver/blob/master/cassandra/policies.py#L182

This test was working because populate was called before cc was created, so we only knew about contact points provided in cluster config (so only one host) I believe current approach (calling populate on lbp after creating cc so we can update lbp with all known hosts) is much better so we should remove this test @Lorak-mmk WDYT?

@Lorak-mmk
Copy link

In the previous approach (calling populate with one host) were the on_add calls correct (so one call for each host, besides CC host)?
If so, then both versions are correct. I think we could then switch to proposed version.

@Lorak-mmk
Copy link

You could then adjust the test, not remove it.

@sylwiaszunejko
Copy link
Collaborator Author

sylwiaszunejko commented Dec 19, 2025

In the previous approach (calling populate with one host) were the on_add calls correct (so one call for each host, besides CC host)? If so, then both versions are correct. I think we could then switch to proposed version.

on_add is called properly, but if there is only one host during populate the starting position for RoundRobinPolicy is always the same even if some hosts are added later:

if len(hosts) > 1:
            self._position = randint(0, len(hosts) - 1)

@sylwiaszunejko sylwiaszunejko force-pushed the remove_random_ids branch 2 times, most recently from adddec1 to 3e864fc Compare December 20, 2025 12:58
@sylwiaszunejko sylwiaszunejko self-assigned this Dec 22, 2025
@sylwiaszunejko sylwiaszunejko marked this pull request as ready for review December 22, 2025 13:21
@Lorak-mmk
Copy link

Please let me review before merging,

Comment on lines 221 to 234
with pytest.raises((WriteTimeout, Unavailable)):
self.session.execute(query, timeout=None)
finally:
get_node(1).resume()

# Change the scales stats_name of the cluster2
cluster2.metrics.set_stats_name('cluster2-metrics')

stats_cluster1 = self.cluster.metrics.get_stats()
stats_cluster2 = cluster2.metrics.get_stats()

# Test direct access to stats
assert 1 == self.cluster.metrics.stats.write_timeouts
assert (1 == self.cluster.metrics.stats.write_timeouts or 1 == self.cluster.metrics.stats.unavailables)
assert 0 == cluster2.metrics.stats.write_timeouts

Choose a reason for hiding this comment

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

Why did the exception thrown change?

Copy link
Collaborator

@dkropachev dkropachev Jan 12, 2026

Choose a reason for hiding this comment

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

It is an expected error in given scenario.
Only difference between WriteTimeout and Unavailable is WriteTimeout happens when coordinator scheduled a query not knowing that node is down and not getting response back, while Unavailable is when coordinator knows that node is down and do not even try.

So, reason is why we start getting Unavailable is that a delay between get_node(1).pause() and self.session.execute(query, timeout=None) is increased, which is most-likely has something to do with absence of dropping node pool for fake node records driver used to create before.

I would say it is safe to just add Unavailable to expected exceptions and move on.

@sylwiaszunejko
Copy link
Collaborator Author

sylwiaszunejko commented Dec 30, 2025

@Lorak-mmk I haven't yet figured out why in test_metrics_per_cluster session.execute sometimes throws cassandra.Unavailable: Error from server: code=1000 [Unavailable exception] message="Cannot achieve consistency level for cl ALL. Requires 3, alive 2" info={'consistency': 'ALL', 'required_replicas': 3, 'alive_replicas': 2} after one of three nodes is paused, but the rest is addressed

Copy link

@Lorak-mmk Lorak-mmk left a comment

Choose a reason for hiding this comment

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

Commit Don't create Host instances with random host_id should be the last one, right? Without test fixes introduced in subsequent commit, this commit can't pass tests I think.

@sylwiaszunejko sylwiaszunejko force-pushed the remove_random_ids branch 3 times, most recently from 7b7cf1f to 02acb4c Compare January 9, 2026 13:44
… starting point

The `test_profile_lb_swap` test logic assumed that `populate`
was called before control connection (cc) was created, meaning
only the contact points from the cluster configuration were
known (a single host). Due to that the starting point was not random.

This commit updates the test to reflect the new behavior, where `populate`
is called on the load-balancing policy after the control connection is
created. This allows the policy to be updated with all known hosts and
ensures the starting point is properly randomized.
Previously, the driver relied on the load-balancing policy (LBP) to determine
the order of hosts to connect to. Since the default LBP is Round Robin, each
reconnection would start from a different host.

After removing fake hosts with random IDs at startup, this behavior changed.
When the LBP is not yet initialized, the driver now uses the endpoints provided
by the control connection (CC), so there is no guarantee that different hosts
will be selected on reconnection.

This change updates the test logic to first establish a connection and
initialize the LBP, and only then verify that two subsequent reconnections
land on different hosts in a healthy cluster.
Only compare hosts endpoints not whole Host instances as we
don't know hosts ids.
In DC aware lbp when local_dc is not provided we set it in
on_add and it needs to be initialized for distance to give
proper results.
Previously, we used endpoints provided to the cluster to create Host
instances with random host_ids in order to populate the LBP before the
ControlConnection was established. This logic led to creating many
connections that were opened and then quickly closed, because once we
learned the correct host_ids from system.peers, we removed the old Hosts
with random IDs and created new ones with the proper host_ids.

This commit introduces a new approach. To establish the ControlConnection,
we now use only the resolved contact points from the cluster configuration.
Only after a successful connection do we populate Host information in the
LBP. If the LBP is already initialized during ControlConnection
reconnection, we reuse the existing values.
Comment on lines 221 to 234
with pytest.raises((WriteTimeout, Unavailable)):
self.session.execute(query, timeout=None)
finally:
get_node(1).resume()

# Change the scales stats_name of the cluster2
cluster2.metrics.set_stats_name('cluster2-metrics')

stats_cluster1 = self.cluster.metrics.get_stats()
stats_cluster2 = cluster2.metrics.get_stats()

# Test direct access to stats
assert 1 == self.cluster.metrics.stats.write_timeouts
assert (1 == self.cluster.metrics.stats.write_timeouts or 1 == self.cluster.metrics.stats.unavailables)
assert 0 == cluster2.metrics.stats.write_timeouts
Copy link
Collaborator

@dkropachev dkropachev Jan 12, 2026

Choose a reason for hiding this comment

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

It is an expected error in given scenario.
Only difference between WriteTimeout and Unavailable is WriteTimeout happens when coordinator scheduled a query not knowing that node is down and not getting response back, while Unavailable is when coordinator knows that node is down and do not even try.

So, reason is why we start getting Unavailable is that a delay between get_node(1).pause() and self.session.execute(query, timeout=None) is increased, which is most-likely has something to do with absence of dropping node pool for fake node records driver used to create before.

I would say it is safe to just add Unavailable to expected exceptions and move on.

@dkropachev dkropachev merged commit a0cde2e into scylladb:master Jan 14, 2026
21 checks passed
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.

Unexpected NoHostAvailable error

3 participants