You are viewing a plain text version of this content. The canonical link for it is here.
Posted to pr@cassandra.apache.org by "bbotella (via GitHub)" <gi...@apache.org> on 2025/08/18 14:13:03 UTC

[PR] CASSSIDECAR-245: Implementation of CassandraClusterSchema [cassandra-sidecar]

bbotella opened a new pull request, #251:
URL: https://github.com/apache/cassandra-sidecar/pull/251

   CASSSIDECAR-245: Implementation of CassandraClusterSchema


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] CASSSIDECAR-245: Implementation of CassandraClusterSchema [cassandra-sidecar]

Posted by "bbotella (via GitHub)" <gi...@apache.org>.
bbotella merged PR #251:
URL: https://github.com/apache/cassandra-sidecar/pull/251


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] CASSSIDECAR-245: Implementation of CassandraClusterSchema [cassandra-sidecar]

Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #251:
URL: https://github.com/apache/cassandra-sidecar/pull/251#discussion_r2335034731


##########
server/src/test/java/org/apache/cassandra/sidecar/db/CdcDatabaseAccessorTests.java:
##########
@@ -0,0 +1,522 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.sidecar.db;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.UUID;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import com.datastax.driver.core.BoundStatement;
+import com.datastax.driver.core.PreparedStatement;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.ResultSetFuture;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.Session;
+import com.google.inject.Provider;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.TokenRange;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.apache.cassandra.sidecar.common.server.CQLSessionProvider;
+import org.apache.cassandra.sidecar.db.schema.CdcStatesSchema;
+import org.apache.cassandra.sidecar.db.schema.TableHistorySchema;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.sidecar.utils.TokenSplitUtil;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.jetbrains.annotations.NotNull;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.apache.cassandra.sidecar.db.CdcDatabaseAccessor.await;
+import static org.apache.cassandra.sidecar.utils.TokenSplitUtil.overlaps;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests for {@link CdcDatabaseAccessor}
+ */
+public class CdcDatabaseAccessorTests
+{
+    @Test
+    public void testDataStoreBasic()
+    {
+        MockCdcStateV2 datastore = new MockCdcStateV2();
+        String jobId = UUID.randomUUID().toString();
+        ByteBuffer buf1 = ByteBuffer.wrap(new byte[]{ 'a', 'b', 'c' });
+        ByteBuffer buf2 = ByteBuffer.wrap(new byte[]{ 'e', 'f', 'g' });
+        assertTrue(datastore.isEmpty());
+        assertTrue(datastore.select(jobId, 0).isEmpty());
+        datastore.insert(jobId, 0, BigInteger.ZERO, BigInteger.TEN, buf1);
+        assertFalse(datastore.isEmpty());
+        assertByteBufferEquals(buf1, datastore.selectBuffers(jobId, 0).stream().findFirst().orElseThrow());
+
+        assertFalse(datastore.select(jobId, 0).isEmpty());
+        assertFalse(datastore.select(jobId, 0).isEmpty());
+        assertTrue(datastore.select(jobId, 1).isEmpty());
+        assertTrue(datastore.select(jobId, 1).isEmpty());
+        datastore.insert(jobId, 0, BigInteger.ZERO, BigInteger.valueOf(100), buf2);
+        assertEquals(2, datastore.select(jobId, 0).size());
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { 3, 4, 8, 16, 32, 64, 128, 256, 512, 1024 })
+    public void testDataStore(int numNodes)
+    {
+        Partitioner partitioner = Partitioner.Murmur3Partitioner;
+        MockCdcStateV2 datastore = new MockCdcStateV2();
+        String jobId = UUID.randomUUID().toString();
+        List<BigInteger> tokens = TokenSplitUtil.splitTokens(numNodes, partitioner);
+        TokenSplitUtil tokenSplitUtil = new TokenSplitUtil(numNodes);
+        assertTrue(datastore.isEmpty());
+
+        // write state and verify we can read back
+        ByteBuffer[] buffers = new ByteBuffer[tokens.size()];
+        for (int i = 0; i < tokens.size(); i++)
+        {
+            BigInteger lower = tokens.get(i);
+            BigInteger upper = i == tokens.size() - 1 ? partitioner.maxToken() : tokens.get(i + 1);
+            TokenRange range = TokenRange.openClosed(lower, upper);
+            ByteBuffer buf = randomBytes(i);
+            buffers[i] = buf;
+            int[] splits = tokenSplitUtil.findOverlappingSplitIds(partitioner, range);
+
+            Arrays.stream(splits).forEach(split -> assertTrue(datastore.select(jobId, split).isEmpty()));
+            Arrays.stream(splits).forEach(split -> datastore.insert(jobId, split, lower, upper, buf));
+        }
+        assertEquals(numNodes, datastore.store.size());
+
+        for (int i = 0; i < tokens.size(); i++)
+        {
+            BigInteger lower = tokens.get(i);
+            BigInteger upper = i == tokens.size() - 1 ? partitioner.maxToken() : tokens.get(i + 1);
+            TokenRange range = TokenRange.openClosed(lower, upper);
+            int[] splits = tokenSplitUtil.findOverlappingSplitIds(partitioner, range);
+            ByteBuffer expected = buffers[i];
+            Arrays.stream(splits).forEach(split -> assertByteBufferEquals(expected, datastore.selectBuffers(jobId, split).stream().findFirst().orElseThrow()));
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { 4, 8, 32, 128, 1024 })
+    public void testShrink(int numNodes)
+    {
+        Partitioner partitioner = Partitioner.Murmur3Partitioner;
+        MockCdcStateV2 datastore = new MockCdcStateV2();
+        String jobId = UUID.randomUUID().toString();
+        CdcStatesSchema mockCdcStatesSchema = mock(CdcStatesSchema.class, RETURNS_DEEP_STUBS);
+        TableHistorySchema mockTableHistorySchema = mock(TableHistorySchema.class, RETURNS_DEEP_STUBS);
+        List<BigInteger> tokensBeforeShrink = TokenSplitUtil.splitTokens(numNodes, partitioner);
+        List<BigInteger> tokensAfterShrink = TokenSplitUtil.splitTokens(numNodes / 2, partitioner);
+        TokenSplitUtil tokenSplitUtil = new TokenSplitUtil(numNodes);
+
+        Provider<TokenSplitUtil> mockTokenSplitUtilProvider = mock(Provider.class);
+        when(mockTokenSplitUtilProvider.get()).thenReturn(tokenSplitUtil);
+        CassandraBridgeFactory mockCassandraBridgeFactory = mock(CassandraBridgeFactory.class);
+
+        CdcDatabaseAccessor db = new CdcDatabaseAccessor(getMockInstanceMetaDataFetcher(), mockCdcStatesSchema,
+                                                         mockTableHistorySchema, getMockCQLSessionProvider(datastore, mockCdcStatesSchema),
+                                                         mockTokenSplitUtilProvider, mockCassandraBridgeFactory);
+
+        ByteBuffer[] buffers = new ByteBuffer[tokensBeforeShrink.size()];
+        for (int i = 0; i < tokensBeforeShrink.size(); i++)
+        {
+            BigInteger lower = tokensBeforeShrink.get(i);
+            BigInteger upper = i == tokensBeforeShrink.size() - 1 ? partitioner.maxToken() : tokensBeforeShrink.get(i + 1);
+            TokenRange range = TokenRange.openClosed(lower, upper);
+            buffers[i] = randomBytes(i);
+            int[] splits = tokenSplitUtil.findOverlappingSplitIds(partitioner, range);
+
+            Arrays.stream(splits).forEach(split -> assertTrue(datastore.select(jobId, split).isEmpty()));
+            await(db.storeStateAsync(jobId, range, buffers[i], System.currentTimeMillis()).stream());
+            List<byte[]> arrays = db.loadStateForRange(jobId, range).collect(Collectors.toList());
+            assertEquals(1, arrays.size());
+            assertByteBufferEquals(buffers[i], arrays.get(0));
+        }
+        assertEquals(numNodes, datastore.store.size());
+
+        for (int i = 0; i < tokensAfterShrink.size(); i++)
+        {
+            BigInteger lower = tokensAfterShrink.get(i);
+            BigInteger upper = i == tokensAfterShrink.size() - 1 ? partitioner.maxToken() : tokensAfterShrink.get(i + 1);
+            TokenRange range = TokenRange.openClosed(lower, upper);
+            List<byte[]> arrays = db.loadStateForRange(jobId, range).collect(Collectors.toList());
+            assertEquals(2, arrays.size());
+            assertByteBufferEquals(buffers[i * 2], arrays.get(0));
+            assertByteBufferEquals(buffers[(i * 2) + 1], arrays.get(1));
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { 4, 8, 32, 128, 1024 })
+    public void testExpand(int numNodes)
+    {
+        Partitioner partitioner = Partitioner.Murmur3Partitioner;
+        MockCdcStateV2 datastore = new MockCdcStateV2();
+        String jobId = UUID.randomUUID().toString();
+        CdcStatesSchema mockCdcStatesSchema = mock(CdcStatesSchema.class, RETURNS_DEEP_STUBS);
+        TableHistorySchema mockTableHistorySchema = mock(TableHistorySchema.class, RETURNS_DEEP_STUBS);
+        List<BigInteger> tokensBeforeExpansion = TokenSplitUtil.splitTokens(numNodes, partitioner);
+        List<BigInteger> tokensAfterExpansion = TokenSplitUtil.splitTokens(numNodes * 2, partitioner);
+        TokenSplitUtil tokenSplitUtil = new TokenSplitUtil(numNodes);
+
+        Provider<TokenSplitUtil> mockTokenSplitUtilProvider = mock(Provider.class);

Review Comment:
   NIT:
   ```suggestion
           Provider<TokenSplitUtil> tokenSplitUtilProvider = () -> tokenSplitUtil;
   ```



##########
server/src/test/java/org/apache/cassandra/sidecar/db/CdcDatabaseAccessorTests.java:
##########
@@ -0,0 +1,522 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.sidecar.db;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.UUID;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import com.datastax.driver.core.BoundStatement;
+import com.datastax.driver.core.PreparedStatement;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.ResultSetFuture;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.Session;
+import com.google.inject.Provider;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.TokenRange;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.apache.cassandra.sidecar.common.server.CQLSessionProvider;
+import org.apache.cassandra.sidecar.db.schema.CdcStatesSchema;
+import org.apache.cassandra.sidecar.db.schema.TableHistorySchema;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.sidecar.utils.TokenSplitUtil;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.jetbrains.annotations.NotNull;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;

Review Comment:
   let's migrate to `org.assertj.core.api.Assertions.assertThat` to be consistent with the repo



##########
server/src/main/java/org/apache/cassandra/sidecar/utils/CdcUtil.java:
##########
@@ -175,4 +192,119 @@ public static boolean matchIndexExtension(String fileName)
     {
         return fileName.endsWith(IDX_FILE_EXTENSION);
     }
+
+    /**
+     * @param schemaStr full cluster schema text.
+     * @return map of keyspace/table identifier to table create statements.
+     */
+    public static Map<TableIdentifier, String> extractCdcTables(@NotNull final String schemaStr)

Review Comment:
   maybe add a unit test for this function? 



##########
server/src/test/java/org/apache/cassandra/sidecar/db/CdcDatabaseAccessorTests.java:
##########
@@ -0,0 +1,522 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.sidecar.db;
+
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.TreeMap;
+import java.util.UUID;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import com.datastax.driver.core.BoundStatement;
+import com.datastax.driver.core.PreparedStatement;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.ResultSetFuture;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.Session;
+import com.google.inject.Provider;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.TokenRange;
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import org.apache.cassandra.sidecar.common.server.CQLSessionProvider;
+import org.apache.cassandra.sidecar.db.schema.CdcStatesSchema;
+import org.apache.cassandra.sidecar.db.schema.TableHistorySchema;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.sidecar.utils.TokenSplitUtil;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.jetbrains.annotations.NotNull;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.apache.cassandra.sidecar.db.CdcDatabaseAccessor.await;
+import static org.apache.cassandra.sidecar.utils.TokenSplitUtil.overlaps;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests for {@link CdcDatabaseAccessor}
+ */
+public class CdcDatabaseAccessorTests
+{
+    @Test
+    public void testDataStoreBasic()
+    {
+        MockCdcStateV2 datastore = new MockCdcStateV2();
+        String jobId = UUID.randomUUID().toString();
+        ByteBuffer buf1 = ByteBuffer.wrap(new byte[]{ 'a', 'b', 'c' });
+        ByteBuffer buf2 = ByteBuffer.wrap(new byte[]{ 'e', 'f', 'g' });
+        assertTrue(datastore.isEmpty());
+        assertTrue(datastore.select(jobId, 0).isEmpty());
+        datastore.insert(jobId, 0, BigInteger.ZERO, BigInteger.TEN, buf1);
+        assertFalse(datastore.isEmpty());
+        assertByteBufferEquals(buf1, datastore.selectBuffers(jobId, 0).stream().findFirst().orElseThrow());
+
+        assertFalse(datastore.select(jobId, 0).isEmpty());
+        assertFalse(datastore.select(jobId, 0).isEmpty());
+        assertTrue(datastore.select(jobId, 1).isEmpty());
+        assertTrue(datastore.select(jobId, 1).isEmpty());
+        datastore.insert(jobId, 0, BigInteger.ZERO, BigInteger.valueOf(100), buf2);
+        assertEquals(2, datastore.select(jobId, 0).size());
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { 3, 4, 8, 16, 32, 64, 128, 256, 512, 1024 })
+    public void testDataStore(int numNodes)
+    {
+        Partitioner partitioner = Partitioner.Murmur3Partitioner;
+        MockCdcStateV2 datastore = new MockCdcStateV2();
+        String jobId = UUID.randomUUID().toString();
+        List<BigInteger> tokens = TokenSplitUtil.splitTokens(numNodes, partitioner);
+        TokenSplitUtil tokenSplitUtil = new TokenSplitUtil(numNodes);
+        assertTrue(datastore.isEmpty());
+
+        // write state and verify we can read back
+        ByteBuffer[] buffers = new ByteBuffer[tokens.size()];
+        for (int i = 0; i < tokens.size(); i++)
+        {
+            BigInteger lower = tokens.get(i);
+            BigInteger upper = i == tokens.size() - 1 ? partitioner.maxToken() : tokens.get(i + 1);
+            TokenRange range = TokenRange.openClosed(lower, upper);
+            ByteBuffer buf = randomBytes(i);
+            buffers[i] = buf;
+            int[] splits = tokenSplitUtil.findOverlappingSplitIds(partitioner, range);
+
+            Arrays.stream(splits).forEach(split -> assertTrue(datastore.select(jobId, split).isEmpty()));
+            Arrays.stream(splits).forEach(split -> datastore.insert(jobId, split, lower, upper, buf));
+        }
+        assertEquals(numNodes, datastore.store.size());
+
+        for (int i = 0; i < tokens.size(); i++)
+        {
+            BigInteger lower = tokens.get(i);
+            BigInteger upper = i == tokens.size() - 1 ? partitioner.maxToken() : tokens.get(i + 1);
+            TokenRange range = TokenRange.openClosed(lower, upper);
+            int[] splits = tokenSplitUtil.findOverlappingSplitIds(partitioner, range);
+            ByteBuffer expected = buffers[i];
+            Arrays.stream(splits).forEach(split -> assertByteBufferEquals(expected, datastore.selectBuffers(jobId, split).stream().findFirst().orElseThrow()));
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = { 4, 8, 32, 128, 1024 })
+    public void testShrink(int numNodes)
+    {
+        Partitioner partitioner = Partitioner.Murmur3Partitioner;
+        MockCdcStateV2 datastore = new MockCdcStateV2();
+        String jobId = UUID.randomUUID().toString();
+        CdcStatesSchema mockCdcStatesSchema = mock(CdcStatesSchema.class, RETURNS_DEEP_STUBS);
+        TableHistorySchema mockTableHistorySchema = mock(TableHistorySchema.class, RETURNS_DEEP_STUBS);
+        List<BigInteger> tokensBeforeShrink = TokenSplitUtil.splitTokens(numNodes, partitioner);
+        List<BigInteger> tokensAfterShrink = TokenSplitUtil.splitTokens(numNodes / 2, partitioner);
+        TokenSplitUtil tokenSplitUtil = new TokenSplitUtil(numNodes);
+
+        Provider<TokenSplitUtil> mockTokenSplitUtilProvider = mock(Provider.class);
+        when(mockTokenSplitUtilProvider.get()).thenReturn(tokenSplitUtil);

Review Comment:
   NIT: 
   ```suggestion
           Provider<TokenSplitUtil> tokenSplitUtilProvider = () -> tokenSplitUtil;
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/db/schema/TableHistorySchema.java:
##########
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.db.schema;
+
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.PreparedStatement;
+import com.datastax.driver.core.Session;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import org.apache.cassandra.sidecar.config.SchemaKeyspaceConfiguration;
+import org.apache.cassandra.sidecar.config.ServiceConfiguration;
+import org.apache.cassandra.sidecar.coordination.ExecuteOnClusterLeaseholderOnly;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Schema definition and management for tracking table schema evolution history.
+ * This class extends {@link TableSchema} to provide specialized schema management for storing
+ * historical versions of table schemas in Cassandra Sidecar.
+ */
+@Singleton
+public class TableHistorySchema extends TableSchema implements ExecuteOnClusterLeaseholderOnly
+{
+    private static final String TABLE_SCHEMA_HISTORY = "table_schema_history";
+
+    private final SchemaKeyspaceConfiguration keyspaceConfig;
+
+    // prepared statements
+    private PreparedStatement insertTableSchema;
+    private PreparedStatement selectVersionTableSchema;
+
+    @Inject
+    public TableHistorySchema(ServiceConfiguration configuration)
+    {
+        this.keyspaceConfig = configuration.schemaKeyspaceConfiguration();
+    }
+
+    @Override
+    protected void prepareStatements(@NotNull Session session)
+    {
+        insertTableSchema = prepare(insertTableSchema, session, CqlLiterals.insertTableSchema(keyspaceConfig));
+        selectVersionTableSchema = prepare(selectVersionTableSchema, session, CqlLiterals.selectVersionTableSchema(keyspaceConfig));
+    }
+
+    @Override
+    protected String keyspaceName()
+    {
+        return keyspaceConfig.keyspace();
+    }
+
+    @Override
+    protected String tableName()
+    {
+        return TABLE_SCHEMA_HISTORY;
+    }
+
+    @Override
+    protected boolean exists(@NotNull Metadata metadata)
+    {
+        KeyspaceMetadata ksMetadata = metadata.getKeyspace(keyspaceConfig.keyspace());
+        if (ksMetadata == null)
+        {
+            return false;
+        }
+
+        return ksMetadata.getTable(TABLE_SCHEMA_HISTORY) != null;
+    }
+
+    @Override
+    protected String createSchemaStatement()
+    {
+        return String.format("CREATE TABLE IF NOT EXISTS %s.%s (" +
+                             "  keyspace_name text," +
+                             "  table_name text," +
+                             "  version uuid," +
+                             "  created_at timeuuid," +
+                             "  table_schema text," +
+                             "  PRIMARY KEY ((ks, tb), version)" +
+                             ")",
+                             keyspaceConfig.keyspace(), TABLE_SCHEMA_HISTORY);
+    }
+
+    public PreparedStatement insertTableSchema()
+    {
+        return insertTableSchema;
+    }
+
+    public PreparedStatement selectVersionTableSchema()
+    {
+        return selectVersionTableSchema;
+    }
+
+    private static class CqlLiterals
+    {
+        static String insertTableSchema(SchemaKeyspaceConfiguration config)
+        {
+            return withTable("INSERT INTO %s.%s (ks, tb, version, created_at, table_schema) " +

Review Comment:
   after the change above, we should use the new names for the keyspace, table columns
   ```suggestion
               return withTable("INSERT INTO %s.%s (keyspace_name, table_name, version, created_at, table_schema) " +
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/utils/TokenSplitUtil.java:
##########
@@ -0,0 +1,200 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.utils;
+
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.BoundType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.Host;
+import com.google.inject.Singleton;
+import org.apache.cassandra.bridge.TokenRange;
+import org.apache.cassandra.sidecar.cdc.CdcConfig;
+import org.apache.cassandra.sidecar.db.ServiceConfig;
+import org.apache.cassandra.sidecar.db.TokenSplitConfigAccessor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+
+/**
+ * Util class that divides token range into fixed number of splits to help distribute load. 
+ * The number of splits should be proportional to the cluster size, so that small clusters 
+ * store state in a small number of partitions, and large clusters store state across a 
+ * larger number of partitions.
+ */
+@Singleton
+public class TokenSplitUtil
+{
+    private static final Logger LOGGER = LoggerFactory.getLogger(TokenSplitUtil.class);
+
+    public static final Map<Partitioner, BigInteger> PARTITIONER_FULL_RANGE = Map.of(
+    Partitioner.Murmur3Partitioner, BigInteger.valueOf(2).pow(64),
+    Partitioner.RandomPartitioner, BigInteger.valueOf(2).pow(127)
+    );
+
+    public static final String NUM_SPLITS_KEY = "curr_num_splits";
+    // we can in the future add a current/prior split count so we can migrate from one to another after a cluster topology event
+//    public static final String PRIOR_NUM_SPLITS_KEY = "prior_num_splits";
+
+    public final int numSplits;
+    public final List<BigInteger> murmur3Tokens;
+    public final List<BigInteger> randomTokens;
+
+    @VisibleForTesting
+    public TokenSplitUtil(int numSplits)
+    {
+        this.numSplits = numSplits;
+        this.murmur3Tokens = splitTokens(numSplits, Partitioner.Murmur3Partitioner);
+        this.randomTokens = splitTokens(numSplits, Partitioner.RandomPartitioner);
+        LOGGER.info("Initialized token split util numSplits={}", numSplits);
+    }
+
+    public TokenSplitUtil(TokenSplitConfigAccessor tokenSplitConfigAccessor, CdcConfig cdcConfig, InstanceMetadataFetcher fetcher)
+    {
+        this(getOrInsert(tokenSplitConfigAccessor, cdcConfig, fetcher));
+    }
+
+    protected static int getOrInsert(TokenSplitConfigAccessor tokenSplitConfigAccessor, CdcConfig cdcConfig, InstanceMetadataFetcher fetcher)
+    {
+        Map<String, String> config = tokenSplitConfigAccessor.getConfig().getConfigs();
+        if (config != null && config.containsKey(NUM_SPLITS_KEY))
+        {
+            return Integer.parseInt(config.get(NUM_SPLITS_KEY));
+        }
+
+
+        int maxDcSize = fetcher.callOnFirstAvailableInstance(instanceMetadata -> instanceMetadata.delegate().metadata())

Review Comment:
   if sidecar cannot connect to CQL this will prevent the startup of the service. We should not fail here. Also we should have a more descriptive error message when we throw. But in general we should never throw when building the DAG for guice. 



##########
server/src/test/java/org/apache/cassandra/sidecar/utils/ByteBufUtilsTest.java:
##########
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.sidecar.utils;
+
+import java.io.ByteArrayInputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+
+import com.google.common.io.ByteArrayDataInput;
+import com.google.common.io.ByteStreams;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * Test for {@link ByteBufUtils}
+ */
+@SuppressWarnings("UnstableApiUsage")

Review Comment:
   this looks like it might not be needed?



##########
server/src/test/java/org/apache/cassandra/sidecar/utils/ByteBufUtilsTest.java:
##########
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.sidecar.utils;
+
+import java.io.ByteArrayInputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+
+import com.google.common.io.ByteArrayDataInput;
+import com.google.common.io.ByteStreams;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * Test for {@link ByteBufUtils}
+ */
+@SuppressWarnings("UnstableApiUsage")
+public class ByteBufUtilsTest
+{
+    @Test
+    public void testSkipBytesFully() throws IOException
+    {
+        testSkipBytesFully("abc".getBytes(StandardCharsets.UTF_8));
+        testSkipBytesFully("abcdefghijklm".getBytes(StandardCharsets.UTF_8));
+    }
+
+    @Test
+    public void testReadRemainingBytes() throws IOException
+    {
+        testReadRemainingBytes("");
+        testReadRemainingBytes("abc");
+        testReadRemainingBytes("abcdefghijklm");
+    }
+
+    @Test
+    public void testGetArray()
+    {
+        testGetArray("");
+        testGetArray("abc");
+        testGetArray("abcdefghijklm");
+    }
+
+    @Test
+    public void testHexString()
+    {
+        assertEquals("00000000000001F4", ByteBufUtils.toHexString((ByteBuffer) ByteBuffer.allocate(8).putLong(500L).flip()));
+        assertEquals("616263", ByteBufUtils.toHexString(ByteBuffer.wrap(new byte[]{ 'a', 'b', 'c' })));
+        assertEquals("000000000588C164", ByteBufUtils.toHexString((ByteBuffer) ByteBuffer.allocate(8).putLong(92848484L).asReadOnlyBuffer().flip()));
+        assertEquals("null", ByteBufUtils.toHexString(null));
+
+        assertEquals("616263", ByteBufUtils.toHexString(new byte[]{ 'a', 'b', 'c' }, 0, 3));
+        assertEquals("63", ByteBufUtils.toHexString(new byte[]{ 'a', 'b', 'c' }, 2, 1));
+    }
+
+    private static void testGetArray(final String str)
+    {
+        assertEquals(str, new String(ByteBufUtils.getArray(ByteBuffer.wrap(str.getBytes())), StandardCharsets.UTF_8));
+    }
+
+    private static void testReadRemainingBytes(final String str) throws IOException
+    {
+        assertEquals(str, new String(ByteBufUtils.readRemainingBytes(new ByteArrayInputStream(str.getBytes()), str.length()), StandardCharsets.UTF_8));
+    }
+
+    private static void testSkipBytesFully(final byte[] ar) throws IOException
+    {
+        final int len = ar.length;
+        final ByteArrayDataInput in = ByteStreams.newDataInput(ar, 0);

Review Comment:
   NIT:
   ```suggestion
          int len = ar.length;
           ByteArrayDataInput in = ByteStreams.newDataInput(ar, 0);
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/db/schema/TableHistorySchema.java:
##########
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.db.schema;
+
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.PreparedStatement;
+import com.datastax.driver.core.Session;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import org.apache.cassandra.sidecar.config.SchemaKeyspaceConfiguration;
+import org.apache.cassandra.sidecar.config.ServiceConfiguration;
+import org.apache.cassandra.sidecar.coordination.ExecuteOnClusterLeaseholderOnly;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Schema definition and management for tracking table schema evolution history.
+ * This class extends {@link TableSchema} to provide specialized schema management for storing
+ * historical versions of table schemas in Cassandra Sidecar.
+ */
+@Singleton
+public class TableHistorySchema extends TableSchema implements ExecuteOnClusterLeaseholderOnly
+{
+    private static final String TABLE_SCHEMA_HISTORY = "table_schema_history";
+
+    private final SchemaKeyspaceConfiguration keyspaceConfig;
+
+    // prepared statements
+    private PreparedStatement insertTableSchema;
+    private PreparedStatement selectVersionTableSchema;
+
+    @Inject
+    public TableHistorySchema(ServiceConfiguration configuration)
+    {
+        this.keyspaceConfig = configuration.schemaKeyspaceConfiguration();
+    }
+
+    @Override
+    protected void prepareStatements(@NotNull Session session)
+    {
+        insertTableSchema = prepare(insertTableSchema, session, CqlLiterals.insertTableSchema(keyspaceConfig));
+        selectVersionTableSchema = prepare(selectVersionTableSchema, session, CqlLiterals.selectVersionTableSchema(keyspaceConfig));
+    }
+
+    @Override
+    protected String keyspaceName()
+    {
+        return keyspaceConfig.keyspace();
+    }
+
+    @Override
+    protected String tableName()
+    {
+        return TABLE_SCHEMA_HISTORY;
+    }
+
+    @Override
+    protected boolean exists(@NotNull Metadata metadata)
+    {
+        KeyspaceMetadata ksMetadata = metadata.getKeyspace(keyspaceConfig.keyspace());
+        if (ksMetadata == null)
+        {
+            return false;
+        }
+
+        return ksMetadata.getTable(TABLE_SCHEMA_HISTORY) != null;
+    }
+
+    @Override
+    protected String createSchemaStatement()
+    {
+        return String.format("CREATE TABLE IF NOT EXISTS %s.%s (" +
+                             "  keyspace_name text," +
+                             "  table_name text," +
+                             "  version uuid," +
+                             "  created_at timeuuid," +
+                             "  table_schema text," +
+                             "  PRIMARY KEY ((ks, tb), version)" +
+                             ")",
+                             keyspaceConfig.keyspace(), TABLE_SCHEMA_HISTORY);
+    }
+
+    public PreparedStatement insertTableSchema()
+    {
+        return insertTableSchema;
+    }
+
+    public PreparedStatement selectVersionTableSchema()
+    {
+        return selectVersionTableSchema;
+    }
+
+    private static class CqlLiterals
+    {
+        static String insertTableSchema(SchemaKeyspaceConfiguration config)
+        {
+            return withTable("INSERT INTO %s.%s (ks, tb, version, created_at, table_schema) " +
+                             "VALUES (?, ?, ?, NOW(), ?)", config);
+        }
+
+        static String selectVersionTableSchema(SchemaKeyspaceConfiguration config)
+        {
+            return withTable("SELECT table_schema FROM %s.%s WHERE ks = ? AND tb = ? AND version = ?", config);

Review Comment:
   ```suggestion
               return withTable("SELECT table_schema FROM %s.%s WHERE keyspace_name = ? AND table_name = ? AND version = ?", config);
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/db/CdcDatabaseAccessor.java:
##########
@@ -0,0 +1,298 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.db;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.datastax.driver.core.ResultSetFuture;
+import com.datastax.driver.core.Row;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.ProvisionException;
+import com.google.inject.Singleton;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.TokenRange;
+import org.apache.cassandra.cdc.CdcKryoRegister;
+import org.apache.cassandra.cdc.state.CdcState;
+import org.apache.cassandra.sidecar.cdc.SidecarCdcStats;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.CQLSessionProvider;
+import org.apache.cassandra.sidecar.db.schema.CdcStatesSchema;
+import org.apache.cassandra.sidecar.db.schema.TableHistorySchema;
+import org.apache.cassandra.sidecar.utils.ByteBufUtils;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.sidecar.utils.TokenSplitUtil;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.apache.cassandra.spark.utils.ThrowableUtils;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Database accessor for CDC (Change Data Capture) state management operations.
+ * <p>
+ * This class provides specialized database access functionality for managing CDC state persistence
+ * and retrieval in Cassandra Sidecar. It extends {@link DatabaseAccessor} to provide CDC-specific
+ * operations including:
+ * <ul>
+ *   <li>Storing CDC state data across token range splits for distributed processing</li>
+ *   <li>Loading and merging CDC state from overlapping token ranges</li>
+ *   <li>Managing table schema history for CDC-enabled tables</li>
+ *   <li>Providing partitioner and metadata access for CDC operations</li>
+ * </ul>
+ * <p>
+ * The accessor handles token range splitting to ensure CDC state is properly distributed
+ * across multiple database partitions for scalability. It uses {@link TokenSplitUtil}
+ * to determine overlapping splits for both storage and retrieval operations.
+ * <p>
+ * Key features:
+ * <ul>
+ *   <li><strong>Token-aware storage:</strong> Automatically distributes CDC state across
+ *       appropriate token range splits</li>
+ *   <li><strong>State merging:</strong> Combines overlapping CDC state objects into
+ *       canonical views during retrieval</li>
+ *   <li><strong>Schema management:</strong> Tracks table schema versions for CDC operations</li>
+ *   <li><strong>Async operations:</strong> Provides asynchronous database operations for
+ *       better performance</li>
+ * </ul>
+ * <p>
+ * This class is thread-safe and designed as a singleton for injection into CDC components
+ * that require database access functionality.
+ *
+ * @see DatabaseAccessor
+ * @see CdcStatesSchema
+ * @see TokenSplitUtil
+ */
+@SuppressWarnings("resource")
+@Singleton
+public class CdcDatabaseAccessor extends DatabaseAccessor<CdcStatesSchema>
+{
+    private static final Logger LOGGER = LoggerFactory.getLogger(CdcDatabaseAccessor.class);
+    private final TableHistorySchema tableHistorySchema;
+    private final Provider<TokenSplitUtil> tokenSplitUtilProvider;
+    private volatile TokenSplitUtil tokenSplitUtil = null;
+    private volatile InstanceMetadataFetcher instanceMetadataFetcher;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    @Inject
+    public CdcDatabaseAccessor(InstanceMetadataFetcher instanceMetadataFetcher,
+                               CdcStatesSchema cdcStatesSchema,
+                               TableHistorySchema tableHistorySchema,
+                               CQLSessionProvider sessionProvider,
+                               Provider<TokenSplitUtil> tokenSplitUtilProvider,
+                               CassandraBridgeFactory cassandraBridgeFactory)
+    {
+        super(cdcStatesSchema, sessionProvider);
+        this.tableHistorySchema = tableHistorySchema;
+        this.tokenSplitUtilProvider = tokenSplitUtilProvider;
+        this.instanceMetadataFetcher = instanceMetadataFetcher;
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    @VisibleForTesting
+    public CdcDatabaseAccessor(InstanceMetadataFetcher instanceMetadataFetcher,

Review Comment:
   this is unused. Let's remove it?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] CASSSIDECAR-245: Implementation of CassandraClusterSchema [cassandra-sidecar]

Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #251:
URL: https://github.com/apache/cassandra-sidecar/pull/251#discussion_r2326271432


##########
server/build.gradle:
##########
@@ -148,6 +148,10 @@ dependencies {
     implementation("io.swagger.core.v3:swagger-models:${project.swaggerVersion}")
     implementation("io.swagger.core.v3:swagger-jaxrs2:${project.swaggerVersion}")
 
+    implementation(group: "org.apache.cassandra", name: "cassandra-analytics-common", version: "${[project.analyticsVersion]}")
+    implementation(group: "org.apache.cassandra", name: "cassandra-analytics-cdc_spark3_2.12", version: "${[project.analyticsVersion]}")
+    implementation "com.esotericsoftware:kryo-shaded:${kryoVersion}"

Review Comment:
   Let's  omit the kryo version. My fear is that the version number might get out of sync from what `cassandra-analytics-cdc_spark3_2.12` is bringing transitively.  I am also uneasy about `cassandra-analytics-cdc_spark3_2.12` pulling guava. I'd love to get rid of guava as a dependency from the upstream, but it is widely used.
   ```suggestion
   ```



##########
server/src/main/java/org/apache/cassandra/bridge/CassandraBridgeFactory.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.bridge;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import com.google.common.base.Preconditions;

Review Comment:
   we should use Sidecar's preconditions in general, but in this case it's not needed. We should use `Objects.requireNonNull`



##########
server/src/main/java/org/apache/cassandra/sidecar/config/yaml/CdcConfigurationImpl.java:
##########
@@ -35,10 +35,13 @@ public class CdcConfigurationImpl implements CdcConfiguration
     private static final Logger LOGGER = LoggerFactory.getLogger(CdcConfigurationImpl.class);
     public static final String IS_ENABLED_PROPERTY = "enabled";
     public static final String CONFIGURATION_REFRESH_TIME_PROPERTY = "config_refresh_time";
+    public static final String TABLE_SCHEMA_REFRESH_TIME_PROPERTY = "table_schema_refresh_time";

Review Comment:
   can we add this to sidecar.yaml and document it there as well?



##########
server/src/main/java/org/apache/cassandra/sidecar/cdc/SidecarCdcStats.java:
##########
@@ -0,0 +1,303 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.cdc;
+
+/**

Review Comment:
   I find the AI generated javadocs to be less useful than a concise description of what the method does. In general I'm not liking these



##########
server/src/main/java/org/apache/cassandra/sidecar/utils/ByteBufUtils.java:
##########


Review Comment:
   This class needs unit tests.



##########
server/src/main/java/org/apache/cassandra/sidecar/utils/CdcUtil.java:
##########
@@ -21,12 +21,67 @@
 import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+import com.google.common.annotations.VisibleForTesting;
+
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.jetbrains.annotations.NotNull;
 
 /**
- * Class with utility methods for CDC.
+ * Utility class providing CDC (Change Data Capture) specific operations and file handling.

Review Comment:
   these AI generated javadocs are too much



##########
server/src/main/java/org/apache/cassandra/bridge/CassandraBridgeFactory.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.bridge;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import com.google.common.base.Preconditions;
+
+import jakarta.inject.Singleton;
+import org.jetbrains.annotations.NotNull;
+
+import static org.apache.cassandra.bridge.BaseCassandraBridgeFactory.getCassandraVersion;
+
+/**
+ * Factory class for creating Cassandra bridge instances based on version-specific jar files.
+ * <p>
+ * This factory maintains a cache of CassandraBridge instances mapped by Cassandra version labels
+ * and provides methods to retrieve bridge instances for specific Cassandra versions.
+ * Each bridge is loaded from version-specific JAR resources and instantiated using reflection.
+ */
+@Singleton
+public class CassandraBridgeFactory
+{
+    // maps Cassandra version-specific jar name (e.g. 'four-zero') to matching CassandraBridge
+    private final Map<String, CassandraBridge> cassandraBridges;
+    
+    public CassandraBridgeFactory()
+    {
+        cassandraBridges = new ConcurrentHashMap<>(CassandraVersion.values().length);
+    }
+
+    @NotNull
+    public CassandraBridge get(@NotNull String version)
+    {
+        return get(getCassandraVersion(version));
+    }
+
+    @NotNull
+    public CassandraBridge get(@NotNull CassandraVersionFeatures features)
+    {
+        return get(getCassandraVersion(features));
+    }
+
+    @NotNull
+    public CassandraBridge get(@NotNull CassandraVersion version)
+    {
+        String jarBaseName = version.jarBaseName();
+        Preconditions.checkNotNull(jarBaseName, "Cassandra version " + version + " is not supported");
+        return cassandraBridges.computeIfAbsent(jarBaseName, this::create);
+    }
+
+    @NotNull
+    @SuppressWarnings("unchecked")
+    private CassandraBridge create(@NotNull String label)
+    {
+        try
+        {
+            ClassLoader loader = buildClassLoader(
+            cassandraResourceName(label),
+            bridgeResourceName(label),
+            typesResourceName(label));
+            Class<CassandraBridge> bridge = (Class<CassandraBridge>) loader.loadClass(CassandraBridge.IMPLEMENTATION_FQCN);
+            Constructor<CassandraBridge> constructor = bridge.getConstructor();
+            return constructor.newInstance();
+        }
+        catch (ClassNotFoundException | NoSuchMethodException | InstantiationException
+               | IllegalAccessException | InvocationTargetException exception)
+        {
+            throw new RuntimeException("Failed to create Cassandra bridge for label " + label, exception);
+        }
+    }
+
+    @NotNull
+    String cassandraResourceName(@NotNull String label)
+    {
+        return "/bridges/" + label + ".jar";
+    }
+
+    @NotNull
+    String bridgeResourceName(@NotNull String label)
+    {
+        return jarResourceName(label, "bridge");
+    }
+
+    @NotNull
+    String typesResourceName(@NotNull String label)
+    {
+        return jarResourceName(label, "types");
+    }
+
+    String jarResourceName(String... parts)
+    {
+        return "/bridges/" + String.join("-", parts) + ".jar";
+    }
+
+    public ClassLoader buildClassLoader(String... resourceNames)
+    {
+        URL[] urls = Arrays.stream(resourceNames)
+                           .map(BaseCassandraBridgeFactory::copyClassResourceToFile)
+                           .map(jar -> {
+                               try
+                               {
+                                   return jar.toURI().toURL();
+                               }
+                               catch (MalformedURLException e)
+                               {
+                                   throw new RuntimeException(e);
+                               }
+                           }).toArray(URL[]::new);
+
+        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>()
+        {
+            public ClassLoader run()
+            {
+                return new PostDelegationClassLoader(urls, Thread.currentThread().getContextClassLoader());
+            }
+        });
+    }

Review Comment:
   NIT:
   ```suggestion
                   return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () ->
                                                                                new PostDelegationClassLoader(urls, Thread.currentThread().getContextClassLoader()));
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/db/CdcDatabaseAccessor.java:
##########
@@ -0,0 +1,298 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.db;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.datastax.driver.core.ResultSetFuture;
+import com.datastax.driver.core.Row;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.ProvisionException;
+import com.google.inject.Singleton;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.TokenRange;
+import org.apache.cassandra.cdc.CdcKryoRegister;
+import org.apache.cassandra.cdc.state.CdcState;
+import org.apache.cassandra.sidecar.cdc.SidecarCdcStats;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.CQLSessionProvider;
+import org.apache.cassandra.sidecar.db.schema.CdcStatesSchema;
+import org.apache.cassandra.sidecar.db.schema.TableHistorySchema;
+import org.apache.cassandra.sidecar.utils.ByteBufUtils;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.sidecar.utils.TokenSplitUtil;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.apache.cassandra.spark.utils.ThrowableUtils;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Database accessor for CDC (Change Data Capture) state management operations.
+ * <p>
+ * This class provides specialized database access functionality for managing CDC state persistence
+ * and retrieval in Cassandra Sidecar. It extends {@link DatabaseAccessor} to provide CDC-specific
+ * operations including:
+ * <ul>
+ *   <li>Storing CDC state data across token range splits for distributed processing</li>
+ *   <li>Loading and merging CDC state from overlapping token ranges</li>
+ *   <li>Managing table schema history for CDC-enabled tables</li>
+ *   <li>Providing partitioner and metadata access for CDC operations</li>
+ * </ul>
+ * <p>
+ * The accessor handles token range splitting to ensure CDC state is properly distributed
+ * across multiple database partitions for scalability. It uses {@link TokenSplitUtil}
+ * to determine overlapping splits for both storage and retrieval operations.
+ * <p>
+ * Key features:
+ * <ul>
+ *   <li><strong>Token-aware storage:</strong> Automatically distributes CDC state across
+ *       appropriate token range splits</li>
+ *   <li><strong>State merging:</strong> Combines overlapping CDC state objects into
+ *       canonical views during retrieval</li>
+ *   <li><strong>Schema management:</strong> Tracks table schema versions for CDC operations</li>
+ *   <li><strong>Async operations:</strong> Provides asynchronous database operations for
+ *       better performance</li>
+ * </ul>
+ * <p>
+ * This class is thread-safe and designed as a singleton for injection into CDC components
+ * that require database access functionality.
+ *
+ * @see DatabaseAccessor
+ * @see CdcStatesSchema
+ * @see TokenSplitUtil
+ */
+@SuppressWarnings("resource")
+@Singleton
+public class CdcDatabaseAccessor extends DatabaseAccessor<CdcStatesSchema>
+{
+    private static final Logger LOGGER = LoggerFactory.getLogger(CdcDatabaseAccessor.class);
+    private final TableHistorySchema tableHistorySchema;
+    private final Provider<TokenSplitUtil> tokenSplitUtilProvider;
+    private volatile TokenSplitUtil tokenSplitUtil = null;
+    private volatile InstanceMetadataFetcher instanceMetadataFetcher;

Review Comment:
   this should not be volatile, instead we should make it final
   ```suggestion
       private final InstanceMetadataFetcher instanceMetadataFetcher;
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/db/CdcDatabaseAccessor.java:
##########
@@ -0,0 +1,298 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.db;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.datastax.driver.core.ResultSetFuture;
+import com.datastax.driver.core.Row;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.ProvisionException;
+import com.google.inject.Singleton;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.TokenRange;
+import org.apache.cassandra.cdc.CdcKryoRegister;
+import org.apache.cassandra.cdc.state.CdcState;
+import org.apache.cassandra.sidecar.cdc.SidecarCdcStats;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.CQLSessionProvider;
+import org.apache.cassandra.sidecar.db.schema.CdcStatesSchema;
+import org.apache.cassandra.sidecar.db.schema.TableHistorySchema;
+import org.apache.cassandra.sidecar.utils.ByteBufUtils;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.sidecar.utils.TokenSplitUtil;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.apache.cassandra.spark.utils.ThrowableUtils;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Database accessor for CDC (Change Data Capture) state management operations.

Review Comment:
   again this javadoc is not very useful and generally distracting



##########
server/src/main/java/org/apache/cassandra/sidecar/tasks/CassandraClusterSchema.java:
##########
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.tasks;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.google.inject.Singleton;
+import io.vertx.core.Promise;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.CdcBridge;
+import org.apache.cassandra.bridge.CdcBridgeFactory;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
+import org.apache.cassandra.sidecar.common.server.utils.SecondBoundConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.CdcDatabaseAccessor;
+import org.apache.cassandra.sidecar.utils.CdcUtil;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.spark.data.CqlTable;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.CqlUtils;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Central schema management component for Cassandra cluster schema monitoring and CDC table tracking.
+ * <p>
+ * This class provides comprehensive schema management functionality for Cassandra Sidecar, specifically
+ * focused on CDC (Change Data Capture) operations. It maintains real-time awareness of schema changes
+ * in the Cassandra cluster and manages CDC-enabled table metadata, enabling:
+ * <ul>
+ *   <li>Continuous monitoring of Cassandra cluster schema changes</li>
+ *   <li>Automatic detection and tracking of CDC-enabled tables</li>
+ *   <li>Schema change event notification to registered listeners</li>
+ *   <li>Table metadata caching and synchronization with CDC bridges</li>
+ *   <li>Periodic validation of CDC table configurations</li>
+ * </ul>
+ * <p>
+ * The class operates with two main periodic tasks:
+ * <ul>
+ *   <li><strong>Schema Refresh (60s interval):</strong> Monitors for schema changes by comparing
+ *       full schema snapshots and updates CDC table metadata when changes are detected</li>
+ *   <li><strong>Schema Monitor (49s interval):</strong> Validates that CDC-enabled tables
+ *       are properly configured in the Cassandra Schema.instance singleton</li>
+ * </ul>
+ * <p>
+ * Key functionalities include:
+ * <ul>
+ *   <li><strong>CDC Table Discovery:</strong> Automatically identifies and tracks tables with
+ *       CDC enabled from the cluster schema</li>
+ *   <li><strong>Schema Change Detection:</strong> Compares schema snapshots to detect modifications
+ *       and trigger appropriate updates to CDC subsystems</li>
+ *   <li><strong>Bridge Integration:</strong> Synchronizes schema information with Cassandra and
+ *       CDC bridges for consistent metadata handling</li>
+ *   <li><strong>Event Notification:</strong> Provides a listener mechanism for components that
+ *       need to react to schema changes</li>
+ *   <li><strong>Validation and Monitoring:</strong> Continuously validates CDC table configurations
+ *       and reports inconsistencies through metrics</li>
+ * </ul>
+ * <p>
+ * The schema refresh intervals are carefully chosen to balance responsiveness with system load:
+ * <ul>
+ *   <li>60-second refresh interval for schema change detection</li>
+ *   <li>49-second monitor interval (chosen to avoid harmonics with the 60s refresh cycle)</li>
+ * </ul>
+ * <p>
+ * This component is essential for CDC operations as it ensures that CDC consumers always have
+ * up-to-date schema information, enabling proper data serialization, deserialization, and
+ * processing across schema evolution events.
+ * <p>
+ * This class is thread-safe and designed as a singleton for dependency injection into CDC
+ * and other schema-dependent components.
+ *
+ * @see org.apache.cassandra.sidecar.db.CdcDatabaseAccessor
+ * @see org.apache.cassandra.bridge.CdcBridge
+ * @see org.apache.cassandra.spark.data.CqlTable
+ */
+@Singleton
+public class CassandraClusterSchema implements PeriodicTask

Review Comment:
   I think the name of the class should reflect the fact that this will be some background task the periodically refreshes the schema



##########
server/src/main/java/org/apache/cassandra/sidecar/tasks/CassandraClusterSchema.java:
##########
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.tasks;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.google.inject.Singleton;
+import io.vertx.core.Promise;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.CdcBridge;
+import org.apache.cassandra.bridge.CdcBridgeFactory;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
+import org.apache.cassandra.sidecar.common.server.utils.SecondBoundConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.CdcDatabaseAccessor;
+import org.apache.cassandra.sidecar.utils.CdcUtil;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.spark.data.CqlTable;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.CqlUtils;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Central schema management component for Cassandra cluster schema monitoring and CDC table tracking.
+ * <p>
+ * This class provides comprehensive schema management functionality for Cassandra Sidecar, specifically
+ * focused on CDC (Change Data Capture) operations. It maintains real-time awareness of schema changes
+ * in the Cassandra cluster and manages CDC-enabled table metadata, enabling:
+ * <ul>
+ *   <li>Continuous monitoring of Cassandra cluster schema changes</li>
+ *   <li>Automatic detection and tracking of CDC-enabled tables</li>
+ *   <li>Schema change event notification to registered listeners</li>
+ *   <li>Table metadata caching and synchronization with CDC bridges</li>
+ *   <li>Periodic validation of CDC table configurations</li>
+ * </ul>
+ * <p>
+ * The class operates with two main periodic tasks:
+ * <ul>
+ *   <li><strong>Schema Refresh (60s interval):</strong> Monitors for schema changes by comparing
+ *       full schema snapshots and updates CDC table metadata when changes are detected</li>
+ *   <li><strong>Schema Monitor (49s interval):</strong> Validates that CDC-enabled tables
+ *       are properly configured in the Cassandra Schema.instance singleton</li>
+ * </ul>
+ * <p>
+ * Key functionalities include:
+ * <ul>
+ *   <li><strong>CDC Table Discovery:</strong> Automatically identifies and tracks tables with
+ *       CDC enabled from the cluster schema</li>
+ *   <li><strong>Schema Change Detection:</strong> Compares schema snapshots to detect modifications
+ *       and trigger appropriate updates to CDC subsystems</li>
+ *   <li><strong>Bridge Integration:</strong> Synchronizes schema information with Cassandra and
+ *       CDC bridges for consistent metadata handling</li>
+ *   <li><strong>Event Notification:</strong> Provides a listener mechanism for components that
+ *       need to react to schema changes</li>
+ *   <li><strong>Validation and Monitoring:</strong> Continuously validates CDC table configurations
+ *       and reports inconsistencies through metrics</li>
+ * </ul>
+ * <p>
+ * The schema refresh intervals are carefully chosen to balance responsiveness with system load:
+ * <ul>
+ *   <li>60-second refresh interval for schema change detection</li>
+ *   <li>49-second monitor interval (chosen to avoid harmonics with the 60s refresh cycle)</li>
+ * </ul>
+ * <p>
+ * This component is essential for CDC operations as it ensures that CDC consumers always have
+ * up-to-date schema information, enabling proper data serialization, deserialization, and
+ * processing across schema evolution events.
+ * <p>
+ * This class is thread-safe and designed as a singleton for dependency injection into CDC
+ * and other schema-dependent components.
+ *
+ * @see org.apache.cassandra.sidecar.db.CdcDatabaseAccessor
+ * @see org.apache.cassandra.bridge.CdcBridge
+ * @see org.apache.cassandra.spark.data.CqlTable
+ */
+@Singleton
+public class CassandraClusterSchema implements PeriodicTask
+{
+    // 49sec least-common multiple with 60sec is 49min so offers best monitor frequency without clashing with 60sec
+    private static final Logger LOGGER = LoggerFactory.getLogger(CassandraClusterSchema.class);
+
+    private final AtomicReference<String> currSchemaText = new AtomicReference<>("");
+    private final AtomicReference<Set<CqlTable>> cdcTables = new AtomicReference<>(Collections.emptySet());
+    private final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache = new ConcurrentHashMap<>();
+    private final CdcDatabaseAccessor databaseAccessor;
+    private final CopyOnWriteArrayList<Runnable> schemaChangeListeners = new CopyOnWriteArrayList<>();
+    private final SidecarConfiguration sidecarConfiguration;
+    private final InstanceMetadataFetcher instanceFetcher;
+    private final SecondBoundConfiguration tableSchemaRefreshTime;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    public CassandraClusterSchema(InstanceMetadataFetcher instanceFetcher,
+                                  CdcDatabaseAccessor databaseAccessor,
+                                  SidecarConfiguration sidecarConfiguration,
+                                  CassandraBridgeFactory cassandraBridgeFactory)
+    {
+
+        this.instanceFetcher = instanceFetcher;
+        this.databaseAccessor = databaseAccessor;
+        this.sidecarConfiguration = sidecarConfiguration;
+        this.tableSchemaRefreshTime = sidecarConfiguration.serviceConfiguration().cdcConfiguration().tableSchemaRefreshTime();
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    public void addSchemaChangeListener(Runnable listener)
+    {
+        schemaChangeListeners.add(listener);
+    }
+
+    public void refresh()
+    {
+        NodeSettings nodeSettings = instanceFetcher.callOnFirstAvailableInstance(instance-> instance.delegate().nodeSettings());
+        CassandraBridge cassandraBridge = cassandraBridgeFactory.get(nodeSettings.releaseVersion());
+        CdcBridge cdcBridge = CdcBridgeFactory.getCdcBridge(cassandraBridge);
+
+        try
+        {
+            LOGGER.info("Checking for schema changes...");
+            String fullSchemaText = databaseAccessor.fullSchema();
+            if (!fullSchemaText.equals(currSchemaText.get()))
+            {
+                LOGGER.info("Schema change detected, refreshing CDC tables");
+                currSchemaText.set(fullSchemaText);
+                Set<CqlTable> updatedCdcTables = buildCdcTables(fullSchemaText, databaseAccessor, tableIdCache, instanceFetcher, cassandraBridgeFactory);
+                LOGGER.info("Cdc enabled tables tables='{}'", 
+                            updatedCdcTables.stream()
+                                            .map(m -> String.format("%s.%s", m.keyspace(), m.table()))
+                                            .collect(Collectors.joining(",")));
+                cdcTables.set(updatedCdcTables);
+                cdcBridge.updateCdcSchema(updatedCdcTables, databaseAccessor.partitioner(),
+                                          ((keyspace, table) -> tableIdCache.get(TableIdentifier.of(keyspace, table))));
+                schemaChangeListeners.forEach(Runnable::run);
+            }
+        }
+        catch (IllegalStateException exception)
+        {
+            LOGGER.warn("There was a problem refreshing the schema. Database Accessor may not be ready", exception);
+            throw exception;
+        }
+        catch (Throwable t)
+        {
+            LOGGER.error("Unexpected error while refreshing the schema", t);
+            throw t;
+        }
+    }
+
+    public DurationSpec delay()
+    {
+        return tableSchemaRefreshTime;

Review Comment:
   We should keep it like this for when we support dynamic configuration reloading in the future.
   ```suggestion
           return sidecarConfiguration.serviceConfiguration().cdcConfiguration().tableSchemaRefreshTime()
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/tasks/CassandraClusterSchema.java:
##########
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.tasks;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.google.inject.Singleton;
+import io.vertx.core.Promise;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.CdcBridge;
+import org.apache.cassandra.bridge.CdcBridgeFactory;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
+import org.apache.cassandra.sidecar.common.server.utils.SecondBoundConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.CdcDatabaseAccessor;
+import org.apache.cassandra.sidecar.utils.CdcUtil;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.spark.data.CqlTable;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.CqlUtils;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Central schema management component for Cassandra cluster schema monitoring and CDC table tracking.
+ * <p>
+ * This class provides comprehensive schema management functionality for Cassandra Sidecar, specifically
+ * focused on CDC (Change Data Capture) operations. It maintains real-time awareness of schema changes
+ * in the Cassandra cluster and manages CDC-enabled table metadata, enabling:
+ * <ul>
+ *   <li>Continuous monitoring of Cassandra cluster schema changes</li>
+ *   <li>Automatic detection and tracking of CDC-enabled tables</li>
+ *   <li>Schema change event notification to registered listeners</li>
+ *   <li>Table metadata caching and synchronization with CDC bridges</li>
+ *   <li>Periodic validation of CDC table configurations</li>
+ * </ul>
+ * <p>
+ * The class operates with two main periodic tasks:
+ * <ul>
+ *   <li><strong>Schema Refresh (60s interval):</strong> Monitors for schema changes by comparing
+ *       full schema snapshots and updates CDC table metadata when changes are detected</li>
+ *   <li><strong>Schema Monitor (49s interval):</strong> Validates that CDC-enabled tables
+ *       are properly configured in the Cassandra Schema.instance singleton</li>
+ * </ul>
+ * <p>
+ * Key functionalities include:
+ * <ul>
+ *   <li><strong>CDC Table Discovery:</strong> Automatically identifies and tracks tables with
+ *       CDC enabled from the cluster schema</li>
+ *   <li><strong>Schema Change Detection:</strong> Compares schema snapshots to detect modifications
+ *       and trigger appropriate updates to CDC subsystems</li>
+ *   <li><strong>Bridge Integration:</strong> Synchronizes schema information with Cassandra and
+ *       CDC bridges for consistent metadata handling</li>
+ *   <li><strong>Event Notification:</strong> Provides a listener mechanism for components that
+ *       need to react to schema changes</li>
+ *   <li><strong>Validation and Monitoring:</strong> Continuously validates CDC table configurations
+ *       and reports inconsistencies through metrics</li>
+ * </ul>
+ * <p>
+ * The schema refresh intervals are carefully chosen to balance responsiveness with system load:
+ * <ul>
+ *   <li>60-second refresh interval for schema change detection</li>
+ *   <li>49-second monitor interval (chosen to avoid harmonics with the 60s refresh cycle)</li>
+ * </ul>
+ * <p>
+ * This component is essential for CDC operations as it ensures that CDC consumers always have
+ * up-to-date schema information, enabling proper data serialization, deserialization, and
+ * processing across schema evolution events.
+ * <p>
+ * This class is thread-safe and designed as a singleton for dependency injection into CDC
+ * and other schema-dependent components.
+ *
+ * @see org.apache.cassandra.sidecar.db.CdcDatabaseAccessor
+ * @see org.apache.cassandra.bridge.CdcBridge
+ * @see org.apache.cassandra.spark.data.CqlTable
+ */
+@Singleton
+public class CassandraClusterSchema implements PeriodicTask
+{
+    // 49sec least-common multiple with 60sec is 49min so offers best monitor frequency without clashing with 60sec
+    private static final Logger LOGGER = LoggerFactory.getLogger(CassandraClusterSchema.class);
+
+    private final AtomicReference<String> currSchemaText = new AtomicReference<>("");
+    private final AtomicReference<Set<CqlTable>> cdcTables = new AtomicReference<>(Collections.emptySet());
+    private final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache = new ConcurrentHashMap<>();
+    private final CdcDatabaseAccessor databaseAccessor;
+    private final CopyOnWriteArrayList<Runnable> schemaChangeListeners = new CopyOnWriteArrayList<>();
+    private final SidecarConfiguration sidecarConfiguration;
+    private final InstanceMetadataFetcher instanceFetcher;
+    private final SecondBoundConfiguration tableSchemaRefreshTime;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    public CassandraClusterSchema(InstanceMetadataFetcher instanceFetcher,
+                                  CdcDatabaseAccessor databaseAccessor,
+                                  SidecarConfiguration sidecarConfiguration,
+                                  CassandraBridgeFactory cassandraBridgeFactory)
+    {
+
+        this.instanceFetcher = instanceFetcher;
+        this.databaseAccessor = databaseAccessor;
+        this.sidecarConfiguration = sidecarConfiguration;
+        this.tableSchemaRefreshTime = sidecarConfiguration.serviceConfiguration().cdcConfiguration().tableSchemaRefreshTime();
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    public void addSchemaChangeListener(Runnable listener)
+    {
+        schemaChangeListeners.add(listener);
+    }
+
+    public void refresh()
+    {
+        NodeSettings nodeSettings = instanceFetcher.callOnFirstAvailableInstance(instance-> instance.delegate().nodeSettings());
+        CassandraBridge cassandraBridge = cassandraBridgeFactory.get(nodeSettings.releaseVersion());
+        CdcBridge cdcBridge = CdcBridgeFactory.getCdcBridge(cassandraBridge);
+
+        try
+        {
+            LOGGER.info("Checking for schema changes...");

Review Comment:
   this at debug level?
   ```suggestion
               LOGGER.debug("Checking for schema changes...");
   ```



##########
server/src/main/java/org/apache/cassandra/bridge/CassandraBridgeFactory.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.bridge;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import com.google.common.base.Preconditions;
+
+import jakarta.inject.Singleton;
+import org.jetbrains.annotations.NotNull;
+
+import static org.apache.cassandra.bridge.BaseCassandraBridgeFactory.getCassandraVersion;
+
+/**
+ * Factory class for creating Cassandra bridge instances based on version-specific jar files.
+ * <p>
+ * This factory maintains a cache of CassandraBridge instances mapped by Cassandra version labels
+ * and provides methods to retrieve bridge instances for specific Cassandra versions.
+ * Each bridge is loaded from version-specific JAR resources and instantiated using reflection.
+ */
+@Singleton
+public class CassandraBridgeFactory
+{
+    // maps Cassandra version-specific jar name (e.g. 'four-zero') to matching CassandraBridge
+    private final Map<String, CassandraBridge> cassandraBridges;
+    
+    public CassandraBridgeFactory()
+    {
+        cassandraBridges = new ConcurrentHashMap<>(CassandraVersion.values().length);
+    }
+
+    @NotNull
+    public CassandraBridge get(@NotNull String version)
+    {
+        return get(getCassandraVersion(version));
+    }
+
+    @NotNull
+    public CassandraBridge get(@NotNull CassandraVersionFeatures features)
+    {
+        return get(getCassandraVersion(features));
+    }
+
+    @NotNull
+    public CassandraBridge get(@NotNull CassandraVersion version)
+    {
+        String jarBaseName = version.jarBaseName();
+        Preconditions.checkNotNull(jarBaseName, "Cassandra version " + version + " is not supported");

Review Comment:
   ```suggestion
           Objects.requireNonNull(jarBaseName, "Cassandra version " + version + " is not supported");
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/db/CdcDatabaseAccessor.java:
##########
@@ -0,0 +1,298 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.db;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.datastax.driver.core.ResultSetFuture;
+import com.datastax.driver.core.Row;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.ProvisionException;
+import com.google.inject.Singleton;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.TokenRange;
+import org.apache.cassandra.cdc.CdcKryoRegister;
+import org.apache.cassandra.cdc.state.CdcState;
+import org.apache.cassandra.sidecar.cdc.SidecarCdcStats;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.CQLSessionProvider;
+import org.apache.cassandra.sidecar.db.schema.CdcStatesSchema;
+import org.apache.cassandra.sidecar.db.schema.TableHistorySchema;
+import org.apache.cassandra.sidecar.utils.ByteBufUtils;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.sidecar.utils.TokenSplitUtil;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.apache.cassandra.spark.utils.ThrowableUtils;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Database accessor for CDC (Change Data Capture) state management operations.
+ * <p>
+ * This class provides specialized database access functionality for managing CDC state persistence
+ * and retrieval in Cassandra Sidecar. It extends {@link DatabaseAccessor} to provide CDC-specific
+ * operations including:
+ * <ul>
+ *   <li>Storing CDC state data across token range splits for distributed processing</li>
+ *   <li>Loading and merging CDC state from overlapping token ranges</li>
+ *   <li>Managing table schema history for CDC-enabled tables</li>
+ *   <li>Providing partitioner and metadata access for CDC operations</li>
+ * </ul>
+ * <p>
+ * The accessor handles token range splitting to ensure CDC state is properly distributed
+ * across multiple database partitions for scalability. It uses {@link TokenSplitUtil}
+ * to determine overlapping splits for both storage and retrieval operations.
+ * <p>
+ * Key features:
+ * <ul>
+ *   <li><strong>Token-aware storage:</strong> Automatically distributes CDC state across
+ *       appropriate token range splits</li>
+ *   <li><strong>State merging:</strong> Combines overlapping CDC state objects into
+ *       canonical views during retrieval</li>
+ *   <li><strong>Schema management:</strong> Tracks table schema versions for CDC operations</li>
+ *   <li><strong>Async operations:</strong> Provides asynchronous database operations for
+ *       better performance</li>
+ * </ul>
+ * <p>
+ * This class is thread-safe and designed as a singleton for injection into CDC components
+ * that require database access functionality.
+ *
+ * @see DatabaseAccessor
+ * @see CdcStatesSchema
+ * @see TokenSplitUtil
+ */
+@SuppressWarnings("resource")
+@Singleton
+public class CdcDatabaseAccessor extends DatabaseAccessor<CdcStatesSchema>
+{
+    private static final Logger LOGGER = LoggerFactory.getLogger(CdcDatabaseAccessor.class);
+    private final TableHistorySchema tableHistorySchema;
+    private final Provider<TokenSplitUtil> tokenSplitUtilProvider;
+    private volatile TokenSplitUtil tokenSplitUtil = null;
+    private volatile InstanceMetadataFetcher instanceMetadataFetcher;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    @Inject
+    public CdcDatabaseAccessor(InstanceMetadataFetcher instanceMetadataFetcher,
+                               CdcStatesSchema cdcStatesSchema,
+                               TableHistorySchema tableHistorySchema,
+                               CQLSessionProvider sessionProvider,
+                               Provider<TokenSplitUtil> tokenSplitUtilProvider,
+                               CassandraBridgeFactory cassandraBridgeFactory)
+    {
+        super(cdcStatesSchema, sessionProvider);
+        this.tableHistorySchema = tableHistorySchema;
+        this.tokenSplitUtilProvider = tokenSplitUtilProvider;
+        this.instanceMetadataFetcher = instanceMetadataFetcher;
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    @VisibleForTesting
+    public CdcDatabaseAccessor(InstanceMetadataFetcher instanceMetadataFetcher,

Review Comment:
   while this ctor is annotated with `@VisibleForTesting` I don't see it being used anywhere. Maybe you are missing tests for this class?



##########
server/src/main/java/org/apache/cassandra/sidecar/db/CdcDatabaseAccessor.java:
##########
@@ -0,0 +1,298 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.db;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.datastax.driver.core.ResultSetFuture;
+import com.datastax.driver.core.Row;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.ProvisionException;
+import com.google.inject.Singleton;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.TokenRange;
+import org.apache.cassandra.cdc.CdcKryoRegister;
+import org.apache.cassandra.cdc.state.CdcState;
+import org.apache.cassandra.sidecar.cdc.SidecarCdcStats;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.CQLSessionProvider;
+import org.apache.cassandra.sidecar.db.schema.CdcStatesSchema;
+import org.apache.cassandra.sidecar.db.schema.TableHistorySchema;
+import org.apache.cassandra.sidecar.utils.ByteBufUtils;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.sidecar.utils.TokenSplitUtil;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.apache.cassandra.spark.utils.ThrowableUtils;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Database accessor for CDC (Change Data Capture) state management operations.
+ * <p>
+ * This class provides specialized database access functionality for managing CDC state persistence
+ * and retrieval in Cassandra Sidecar. It extends {@link DatabaseAccessor} to provide CDC-specific
+ * operations including:
+ * <ul>
+ *   <li>Storing CDC state data across token range splits for distributed processing</li>
+ *   <li>Loading and merging CDC state from overlapping token ranges</li>
+ *   <li>Managing table schema history for CDC-enabled tables</li>
+ *   <li>Providing partitioner and metadata access for CDC operations</li>
+ * </ul>
+ * <p>
+ * The accessor handles token range splitting to ensure CDC state is properly distributed
+ * across multiple database partitions for scalability. It uses {@link TokenSplitUtil}
+ * to determine overlapping splits for both storage and retrieval operations.
+ * <p>
+ * Key features:
+ * <ul>
+ *   <li><strong>Token-aware storage:</strong> Automatically distributes CDC state across
+ *       appropriate token range splits</li>
+ *   <li><strong>State merging:</strong> Combines overlapping CDC state objects into
+ *       canonical views during retrieval</li>
+ *   <li><strong>Schema management:</strong> Tracks table schema versions for CDC operations</li>
+ *   <li><strong>Async operations:</strong> Provides asynchronous database operations for
+ *       better performance</li>
+ * </ul>
+ * <p>
+ * This class is thread-safe and designed as a singleton for injection into CDC components
+ * that require database access functionality.
+ *
+ * @see DatabaseAccessor
+ * @see CdcStatesSchema
+ * @see TokenSplitUtil
+ */
+@SuppressWarnings("resource")
+@Singleton
+public class CdcDatabaseAccessor extends DatabaseAccessor<CdcStatesSchema>
+{
+    private static final Logger LOGGER = LoggerFactory.getLogger(CdcDatabaseAccessor.class);
+    private final TableHistorySchema tableHistorySchema;
+    private final Provider<TokenSplitUtil> tokenSplitUtilProvider;
+    private volatile TokenSplitUtil tokenSplitUtil = null;
+    private volatile InstanceMetadataFetcher instanceMetadataFetcher;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    @Inject
+    public CdcDatabaseAccessor(InstanceMetadataFetcher instanceMetadataFetcher,
+                               CdcStatesSchema cdcStatesSchema,
+                               TableHistorySchema tableHistorySchema,
+                               CQLSessionProvider sessionProvider,
+                               Provider<TokenSplitUtil> tokenSplitUtilProvider,
+                               CassandraBridgeFactory cassandraBridgeFactory)
+    {
+        super(cdcStatesSchema, sessionProvider);
+        this.tableHistorySchema = tableHistorySchema;
+        this.tokenSplitUtilProvider = tokenSplitUtilProvider;
+        this.instanceMetadataFetcher = instanceMetadataFetcher;
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    @VisibleForTesting
+    public CdcDatabaseAccessor(InstanceMetadataFetcher instanceMetadataFetcher,
+                               CdcStatesSchema cdcStatesSchema,
+                               TableHistorySchema tableHistorySchema,
+                               CQLSessionProvider sessionProvider,
+                               TokenSplitUtil tokenSplitUtil,
+                               CassandraBridgeFactory cassandraBridgeFactory)
+    {
+        super(cdcStatesSchema, sessionProvider);
+        this.tableHistorySchema = tableHistorySchema;
+        this.tokenSplitUtilProvider = () -> tokenSplitUtil;
+        this.instanceMetadataFetcher = instanceMetadataFetcher;
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    protected TokenSplitUtil tokenSplitUtil()
+    {
+        // cql connection must be initialized before we can initialize TokenSplitUtil class
+        if (this.tokenSplitUtil == null)

Review Comment:
   do we need to worry about concurrent access to this method here?



##########
server/src/main/java/org/apache/cassandra/sidecar/tasks/CassandraClusterSchema.java:
##########
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.tasks;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.google.inject.Singleton;
+import io.vertx.core.Promise;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.CdcBridge;
+import org.apache.cassandra.bridge.CdcBridgeFactory;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
+import org.apache.cassandra.sidecar.common.server.utils.SecondBoundConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.CdcDatabaseAccessor;
+import org.apache.cassandra.sidecar.utils.CdcUtil;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.spark.data.CqlTable;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.CqlUtils;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Central schema management component for Cassandra cluster schema monitoring and CDC table tracking.
+ * <p>
+ * This class provides comprehensive schema management functionality for Cassandra Sidecar, specifically
+ * focused on CDC (Change Data Capture) operations. It maintains real-time awareness of schema changes
+ * in the Cassandra cluster and manages CDC-enabled table metadata, enabling:
+ * <ul>
+ *   <li>Continuous monitoring of Cassandra cluster schema changes</li>
+ *   <li>Automatic detection and tracking of CDC-enabled tables</li>
+ *   <li>Schema change event notification to registered listeners</li>
+ *   <li>Table metadata caching and synchronization with CDC bridges</li>
+ *   <li>Periodic validation of CDC table configurations</li>
+ * </ul>
+ * <p>
+ * The class operates with two main periodic tasks:
+ * <ul>
+ *   <li><strong>Schema Refresh (60s interval):</strong> Monitors for schema changes by comparing
+ *       full schema snapshots and updates CDC table metadata when changes are detected</li>
+ *   <li><strong>Schema Monitor (49s interval):</strong> Validates that CDC-enabled tables
+ *       are properly configured in the Cassandra Schema.instance singleton</li>
+ * </ul>
+ * <p>
+ * Key functionalities include:
+ * <ul>
+ *   <li><strong>CDC Table Discovery:</strong> Automatically identifies and tracks tables with
+ *       CDC enabled from the cluster schema</li>
+ *   <li><strong>Schema Change Detection:</strong> Compares schema snapshots to detect modifications
+ *       and trigger appropriate updates to CDC subsystems</li>
+ *   <li><strong>Bridge Integration:</strong> Synchronizes schema information with Cassandra and
+ *       CDC bridges for consistent metadata handling</li>
+ *   <li><strong>Event Notification:</strong> Provides a listener mechanism for components that
+ *       need to react to schema changes</li>
+ *   <li><strong>Validation and Monitoring:</strong> Continuously validates CDC table configurations
+ *       and reports inconsistencies through metrics</li>
+ * </ul>
+ * <p>
+ * The schema refresh intervals are carefully chosen to balance responsiveness with system load:
+ * <ul>
+ *   <li>60-second refresh interval for schema change detection</li>
+ *   <li>49-second monitor interval (chosen to avoid harmonics with the 60s refresh cycle)</li>
+ * </ul>
+ * <p>
+ * This component is essential for CDC operations as it ensures that CDC consumers always have
+ * up-to-date schema information, enabling proper data serialization, deserialization, and
+ * processing across schema evolution events.
+ * <p>
+ * This class is thread-safe and designed as a singleton for dependency injection into CDC
+ * and other schema-dependent components.
+ *
+ * @see org.apache.cassandra.sidecar.db.CdcDatabaseAccessor
+ * @see org.apache.cassandra.bridge.CdcBridge
+ * @see org.apache.cassandra.spark.data.CqlTable
+ */
+@Singleton
+public class CassandraClusterSchema implements PeriodicTask
+{
+    // 49sec least-common multiple with 60sec is 49min so offers best monitor frequency without clashing with 60sec
+    private static final Logger LOGGER = LoggerFactory.getLogger(CassandraClusterSchema.class);
+
+    private final AtomicReference<String> currSchemaText = new AtomicReference<>("");
+    private final AtomicReference<Set<CqlTable>> cdcTables = new AtomicReference<>(Collections.emptySet());
+    private final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache = new ConcurrentHashMap<>();
+    private final CdcDatabaseAccessor databaseAccessor;
+    private final CopyOnWriteArrayList<Runnable> schemaChangeListeners = new CopyOnWriteArrayList<>();
+    private final SidecarConfiguration sidecarConfiguration;
+    private final InstanceMetadataFetcher instanceFetcher;
+    private final SecondBoundConfiguration tableSchemaRefreshTime;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    public CassandraClusterSchema(InstanceMetadataFetcher instanceFetcher,
+                                  CdcDatabaseAccessor databaseAccessor,
+                                  SidecarConfiguration sidecarConfiguration,
+                                  CassandraBridgeFactory cassandraBridgeFactory)
+    {
+
+        this.instanceFetcher = instanceFetcher;
+        this.databaseAccessor = databaseAccessor;
+        this.sidecarConfiguration = sidecarConfiguration;
+        this.tableSchemaRefreshTime = sidecarConfiguration.serviceConfiguration().cdcConfiguration().tableSchemaRefreshTime();
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    public void addSchemaChangeListener(Runnable listener)
+    {
+        schemaChangeListeners.add(listener);
+    }
+
+    public void refresh()
+    {
+        NodeSettings nodeSettings = instanceFetcher.callOnFirstAvailableInstance(instance-> instance.delegate().nodeSettings());
+        CassandraBridge cassandraBridge = cassandraBridgeFactory.get(nodeSettings.releaseVersion());
+        CdcBridge cdcBridge = CdcBridgeFactory.getCdcBridge(cassandraBridge);
+
+        try
+        {
+            LOGGER.info("Checking for schema changes...");
+            String fullSchemaText = databaseAccessor.fullSchema();
+            if (!fullSchemaText.equals(currSchemaText.get()))
+            {
+                LOGGER.info("Schema change detected, refreshing CDC tables");
+                currSchemaText.set(fullSchemaText);
+                Set<CqlTable> updatedCdcTables = buildCdcTables(fullSchemaText, databaseAccessor, tableIdCache, instanceFetcher, cassandraBridgeFactory);
+                LOGGER.info("Cdc enabled tables tables='{}'", 
+                            updatedCdcTables.stream()
+                                            .map(m -> String.format("%s.%s", m.keyspace(), m.table()))
+                                            .collect(Collectors.joining(",")));
+                cdcTables.set(updatedCdcTables);
+                cdcBridge.updateCdcSchema(updatedCdcTables, databaseAccessor.partitioner(),
+                                          ((keyspace, table) -> tableIdCache.get(TableIdentifier.of(keyspace, table))));
+                schemaChangeListeners.forEach(Runnable::run);
+            }
+        }
+        catch (IllegalStateException exception)
+        {
+            LOGGER.warn("There was a problem refreshing the schema. Database Accessor may not be ready", exception);
+            throw exception;
+        }
+        catch (Throwable t)
+        {
+            LOGGER.error("Unexpected error while refreshing the schema", t);
+            throw t;
+        }
+    }
+
+    public DurationSpec delay()
+    {
+        return tableSchemaRefreshTime;
+    }
+
+    @Override
+    public void execute(Promise<Void> promise)
+    {
+        try
+        {
+            refresh();
+            promise.tryComplete();
+        }
+        catch (Throwable t)
+        {
+            promise.fail(t);
+        }
+    }
+
+    @Override
+    public ScheduleDecision scheduleDecision()
+    {
+        boolean shouldSkip = !sidecarConfiguration.serviceConfiguration().schemaKeyspaceConfiguration().isEnabled()
+                             || !sidecarConfiguration.serviceConfiguration().cdcConfiguration().isEnabled();
+        return shouldSkip ? ScheduleDecision.SKIP : ScheduleDecision.EXECUTE;

Review Comment:
   NIT: I find this way more readable
   ```suggestion
                   if (sidecarConfiguration.serviceConfiguration().schemaKeyspaceConfiguration().isEnabled() &&
               sidecarConfiguration.serviceConfiguration().cdcConfiguration().isEnabled())
           {
               return ScheduleDecision.EXECUTE;
           }
           return ScheduleDecision.SKIP;
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/utils/ByteBufUtils.java:
##########
@@ -0,0 +1,313 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.utils;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataInput;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.Buffer;
+import java.nio.ByteBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.function.Supplier;
+
+/**
+ * Utility class providing byte buffer manipulation and conversion operations for Cassandra Sidecar.
+ * <p>
+ * This class offers a comprehensive set of static utility methods for working with byte buffers,
+ * input streams, and byte arrays in the context of Cassandra data processing and CDC operations.
+ * The utilities are designed to handle common byte manipulation tasks including:
+ * <ul>
+ *   <li>ByteBuffer to byte array conversions with optimal performance</li>
+ *   <li>Hexadecimal string representation of binary data</li>
+ *   <li>Stream reading operations with full data consumption guarantees</li>
+ *   <li>Cassandra-specific composite key splitting and building</li>
+ *   <li>Length-prefixed byte buffer operations for data serialization</li>
+ *   <li>UTF-8 string encoding and decoding with error handling</li>
+ * </ul>
+ * <p>
+ * Key features include:
+ * <ul>
+ *   <li><strong>Memory efficiency:</strong> Optimized ByteBuffer handling that avoids
+ *       unnecessary copying when dealing with heap vs direct buffers</li>
+ *   <li><strong>Thread-safe string decoding:</strong> Thread-local UTF-8 decoder
+ *       instances to avoid synchronization overhead</li>
+ *   <li><strong>Cassandra compatibility:</strong> Support for Cassandra composite key
+ *       formats including static marker handling</li>
+ *   <li><strong>Robust I/O:</strong> Stream reading methods that handle partial reads
+ *       and provide complete data consumption guarantees</li>
+ *   <li><strong>Debugging support:</strong> Hexadecimal representation methods for
+ *       binary data inspection and logging</li>
+ * </ul>
+ * <p>
+ * The class is particularly important for CDC operations where efficient byte manipulation
+ * is crucial for processing large volumes of change data. It provides the low-level
+ * building blocks for serialization, deserialization, and data format conversion
+ * operations throughout the sidecar system.
+ * <p>
+ * All methods in this class are static and thread-safe unless otherwise noted.
+ * The class maintains thread-local resources (such as charset decoders) to ensure
+ * optimal performance in multi-threaded environments.
+ *
+ * @see java.nio.ByteBuffer
+ * @see java.nio.charset.CharsetDecoder
+ */
+public class ByteBufUtils

Review Comment:
   NIT, this class has a lot of final modifiers that are not necessary and do not conform with the Cassandra style guide



##########
server/src/main/java/org/apache/cassandra/sidecar/tasks/CassandraClusterSchema.java:
##########
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.tasks;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.google.inject.Singleton;
+import io.vertx.core.Promise;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.CdcBridge;
+import org.apache.cassandra.bridge.CdcBridgeFactory;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
+import org.apache.cassandra.sidecar.common.server.utils.SecondBoundConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.CdcDatabaseAccessor;
+import org.apache.cassandra.sidecar.utils.CdcUtil;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.spark.data.CqlTable;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.CqlUtils;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Central schema management component for Cassandra cluster schema monitoring and CDC table tracking.
+ * <p>
+ * This class provides comprehensive schema management functionality for Cassandra Sidecar, specifically
+ * focused on CDC (Change Data Capture) operations. It maintains real-time awareness of schema changes
+ * in the Cassandra cluster and manages CDC-enabled table metadata, enabling:
+ * <ul>
+ *   <li>Continuous monitoring of Cassandra cluster schema changes</li>
+ *   <li>Automatic detection and tracking of CDC-enabled tables</li>
+ *   <li>Schema change event notification to registered listeners</li>
+ *   <li>Table metadata caching and synchronization with CDC bridges</li>
+ *   <li>Periodic validation of CDC table configurations</li>
+ * </ul>
+ * <p>
+ * The class operates with two main periodic tasks:
+ * <ul>
+ *   <li><strong>Schema Refresh (60s interval):</strong> Monitors for schema changes by comparing
+ *       full schema snapshots and updates CDC table metadata when changes are detected</li>
+ *   <li><strong>Schema Monitor (49s interval):</strong> Validates that CDC-enabled tables
+ *       are properly configured in the Cassandra Schema.instance singleton</li>
+ * </ul>
+ * <p>
+ * Key functionalities include:
+ * <ul>
+ *   <li><strong>CDC Table Discovery:</strong> Automatically identifies and tracks tables with
+ *       CDC enabled from the cluster schema</li>
+ *   <li><strong>Schema Change Detection:</strong> Compares schema snapshots to detect modifications
+ *       and trigger appropriate updates to CDC subsystems</li>
+ *   <li><strong>Bridge Integration:</strong> Synchronizes schema information with Cassandra and
+ *       CDC bridges for consistent metadata handling</li>
+ *   <li><strong>Event Notification:</strong> Provides a listener mechanism for components that
+ *       need to react to schema changes</li>
+ *   <li><strong>Validation and Monitoring:</strong> Continuously validates CDC table configurations
+ *       and reports inconsistencies through metrics</li>
+ * </ul>
+ * <p>
+ * The schema refresh intervals are carefully chosen to balance responsiveness with system load:
+ * <ul>
+ *   <li>60-second refresh interval for schema change detection</li>
+ *   <li>49-second monitor interval (chosen to avoid harmonics with the 60s refresh cycle)</li>
+ * </ul>
+ * <p>
+ * This component is essential for CDC operations as it ensures that CDC consumers always have
+ * up-to-date schema information, enabling proper data serialization, deserialization, and
+ * processing across schema evolution events.
+ * <p>
+ * This class is thread-safe and designed as a singleton for dependency injection into CDC
+ * and other schema-dependent components.
+ *
+ * @see org.apache.cassandra.sidecar.db.CdcDatabaseAccessor
+ * @see org.apache.cassandra.bridge.CdcBridge
+ * @see org.apache.cassandra.spark.data.CqlTable
+ */
+@Singleton
+public class CassandraClusterSchema implements PeriodicTask
+{
+    // 49sec least-common multiple with 60sec is 49min so offers best monitor frequency without clashing with 60sec
+    private static final Logger LOGGER = LoggerFactory.getLogger(CassandraClusterSchema.class);
+
+    private final AtomicReference<String> currSchemaText = new AtomicReference<>("");
+    private final AtomicReference<Set<CqlTable>> cdcTables = new AtomicReference<>(Collections.emptySet());
+    private final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache = new ConcurrentHashMap<>();
+    private final CdcDatabaseAccessor databaseAccessor;
+    private final CopyOnWriteArrayList<Runnable> schemaChangeListeners = new CopyOnWriteArrayList<>();
+    private final SidecarConfiguration sidecarConfiguration;
+    private final InstanceMetadataFetcher instanceFetcher;
+    private final SecondBoundConfiguration tableSchemaRefreshTime;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    public CassandraClusterSchema(InstanceMetadataFetcher instanceFetcher,
+                                  CdcDatabaseAccessor databaseAccessor,
+                                  SidecarConfiguration sidecarConfiguration,
+                                  CassandraBridgeFactory cassandraBridgeFactory)
+    {
+
+        this.instanceFetcher = instanceFetcher;
+        this.databaseAccessor = databaseAccessor;
+        this.sidecarConfiguration = sidecarConfiguration;
+        this.tableSchemaRefreshTime = sidecarConfiguration.serviceConfiguration().cdcConfiguration().tableSchemaRefreshTime();
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    public void addSchemaChangeListener(Runnable listener)
+    {
+        schemaChangeListeners.add(listener);
+    }
+
+    public void refresh()
+    {
+        NodeSettings nodeSettings = instanceFetcher.callOnFirstAvailableInstance(instance-> instance.delegate().nodeSettings());
+        CassandraBridge cassandraBridge = cassandraBridgeFactory.get(nodeSettings.releaseVersion());
+        CdcBridge cdcBridge = CdcBridgeFactory.getCdcBridge(cassandraBridge);
+
+        try
+        {
+            LOGGER.info("Checking for schema changes...");
+            String fullSchemaText = databaseAccessor.fullSchema();
+            if (!fullSchemaText.equals(currSchemaText.get()))
+            {
+                LOGGER.info("Schema change detected, refreshing CDC tables");
+                currSchemaText.set(fullSchemaText);
+                Set<CqlTable> updatedCdcTables = buildCdcTables(fullSchemaText, databaseAccessor, tableIdCache, instanceFetcher, cassandraBridgeFactory);
+                LOGGER.info("Cdc enabled tables tables='{}'", 
+                            updatedCdcTables.stream()
+                                            .map(m -> String.format("%s.%s", m.keyspace(), m.table()))
+                                            .collect(Collectors.joining(",")));
+                cdcTables.set(updatedCdcTables);
+                cdcBridge.updateCdcSchema(updatedCdcTables, databaseAccessor.partitioner(),
+                                          ((keyspace, table) -> tableIdCache.get(TableIdentifier.of(keyspace, table))));
+                schemaChangeListeners.forEach(Runnable::run);
+            }
+        }
+        catch (IllegalStateException exception)
+        {
+            LOGGER.warn("There was a problem refreshing the schema. Database Accessor may not be ready", exception);
+            throw exception;
+        }
+        catch (Throwable t)
+        {
+            LOGGER.error("Unexpected error while refreshing the schema", t);
+            throw t;
+        }
+    }
+
+    public DurationSpec delay()

Review Comment:
   ```suggestion
       @Override
       public DurationSpec delay()
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/tasks/CassandraClusterSchema.java:
##########
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.tasks;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.google.inject.Singleton;
+import io.vertx.core.Promise;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.CdcBridge;
+import org.apache.cassandra.bridge.CdcBridgeFactory;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
+import org.apache.cassandra.sidecar.common.server.utils.SecondBoundConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.CdcDatabaseAccessor;
+import org.apache.cassandra.sidecar.utils.CdcUtil;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.spark.data.CqlTable;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.CqlUtils;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Central schema management component for Cassandra cluster schema monitoring and CDC table tracking.
+ * <p>
+ * This class provides comprehensive schema management functionality for Cassandra Sidecar, specifically
+ * focused on CDC (Change Data Capture) operations. It maintains real-time awareness of schema changes
+ * in the Cassandra cluster and manages CDC-enabled table metadata, enabling:
+ * <ul>
+ *   <li>Continuous monitoring of Cassandra cluster schema changes</li>
+ *   <li>Automatic detection and tracking of CDC-enabled tables</li>
+ *   <li>Schema change event notification to registered listeners</li>
+ *   <li>Table metadata caching and synchronization with CDC bridges</li>
+ *   <li>Periodic validation of CDC table configurations</li>
+ * </ul>
+ * <p>
+ * The class operates with two main periodic tasks:
+ * <ul>
+ *   <li><strong>Schema Refresh (60s interval):</strong> Monitors for schema changes by comparing
+ *       full schema snapshots and updates CDC table metadata when changes are detected</li>
+ *   <li><strong>Schema Monitor (49s interval):</strong> Validates that CDC-enabled tables
+ *       are properly configured in the Cassandra Schema.instance singleton</li>
+ * </ul>
+ * <p>
+ * Key functionalities include:
+ * <ul>
+ *   <li><strong>CDC Table Discovery:</strong> Automatically identifies and tracks tables with
+ *       CDC enabled from the cluster schema</li>
+ *   <li><strong>Schema Change Detection:</strong> Compares schema snapshots to detect modifications
+ *       and trigger appropriate updates to CDC subsystems</li>
+ *   <li><strong>Bridge Integration:</strong> Synchronizes schema information with Cassandra and
+ *       CDC bridges for consistent metadata handling</li>
+ *   <li><strong>Event Notification:</strong> Provides a listener mechanism for components that
+ *       need to react to schema changes</li>
+ *   <li><strong>Validation and Monitoring:</strong> Continuously validates CDC table configurations
+ *       and reports inconsistencies through metrics</li>
+ * </ul>
+ * <p>
+ * The schema refresh intervals are carefully chosen to balance responsiveness with system load:
+ * <ul>
+ *   <li>60-second refresh interval for schema change detection</li>
+ *   <li>49-second monitor interval (chosen to avoid harmonics with the 60s refresh cycle)</li>
+ * </ul>
+ * <p>
+ * This component is essential for CDC operations as it ensures that CDC consumers always have
+ * up-to-date schema information, enabling proper data serialization, deserialization, and
+ * processing across schema evolution events.
+ * <p>
+ * This class is thread-safe and designed as a singleton for dependency injection into CDC
+ * and other schema-dependent components.
+ *
+ * @see org.apache.cassandra.sidecar.db.CdcDatabaseAccessor
+ * @see org.apache.cassandra.bridge.CdcBridge
+ * @see org.apache.cassandra.spark.data.CqlTable
+ */
+@Singleton
+public class CassandraClusterSchema implements PeriodicTask
+{
+    // 49sec least-common multiple with 60sec is 49min so offers best monitor frequency without clashing with 60sec
+    private static final Logger LOGGER = LoggerFactory.getLogger(CassandraClusterSchema.class);
+
+    private final AtomicReference<String> currSchemaText = new AtomicReference<>("");
+    private final AtomicReference<Set<CqlTable>> cdcTables = new AtomicReference<>(Collections.emptySet());
+    private final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache = new ConcurrentHashMap<>();
+    private final CdcDatabaseAccessor databaseAccessor;
+    private final CopyOnWriteArrayList<Runnable> schemaChangeListeners = new CopyOnWriteArrayList<>();
+    private final SidecarConfiguration sidecarConfiguration;
+    private final InstanceMetadataFetcher instanceFetcher;
+    private final SecondBoundConfiguration tableSchemaRefreshTime;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    public CassandraClusterSchema(InstanceMetadataFetcher instanceFetcher,
+                                  CdcDatabaseAccessor databaseAccessor,
+                                  SidecarConfiguration sidecarConfiguration,
+                                  CassandraBridgeFactory cassandraBridgeFactory)
+    {
+
+        this.instanceFetcher = instanceFetcher;
+        this.databaseAccessor = databaseAccessor;
+        this.sidecarConfiguration = sidecarConfiguration;
+        this.tableSchemaRefreshTime = sidecarConfiguration.serviceConfiguration().cdcConfiguration().tableSchemaRefreshTime();
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    public void addSchemaChangeListener(Runnable listener)
+    {
+        schemaChangeListeners.add(listener);
+    }
+
+    public void refresh()
+    {
+        NodeSettings nodeSettings = instanceFetcher.callOnFirstAvailableInstance(instance-> instance.delegate().nodeSettings());
+        CassandraBridge cassandraBridge = cassandraBridgeFactory.get(nodeSettings.releaseVersion());
+        CdcBridge cdcBridge = CdcBridgeFactory.getCdcBridge(cassandraBridge);
+
+        try
+        {
+            LOGGER.info("Checking for schema changes...");
+            String fullSchemaText = databaseAccessor.fullSchema();
+            if (!fullSchemaText.equals(currSchemaText.get()))
+            {
+                LOGGER.info("Schema change detected, refreshing CDC tables");
+                currSchemaText.set(fullSchemaText);
+                Set<CqlTable> updatedCdcTables = buildCdcTables(fullSchemaText, databaseAccessor, tableIdCache, instanceFetcher, cassandraBridgeFactory);
+                LOGGER.info("Cdc enabled tables tables='{}'", 
+                            updatedCdcTables.stream()
+                                            .map(m -> String.format("%s.%s", m.keyspace(), m.table()))
+                                            .collect(Collectors.joining(",")));
+                cdcTables.set(updatedCdcTables);
+                cdcBridge.updateCdcSchema(updatedCdcTables, databaseAccessor.partitioner(),

Review Comment:
   I don't think this `databaseAccessor.partitioner()` is required at all. We already have the partitioner information as a string in `nodeSettings.partitioner()`, with the caveat that we will need to check if the string has `.` and if it does we will need to do the logic we have inside `databaseAccessor.partitioner()`
   ```suggestion
                   cdcBridge.updateCdcSchema(updatedCdcTables, Partitioner.valueOf(nodeSettings.partitioner()),
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/tasks/CassandraClusterSchema.java:
##########
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.tasks;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.google.inject.Singleton;
+import io.vertx.core.Promise;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.CdcBridge;
+import org.apache.cassandra.bridge.CdcBridgeFactory;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
+import org.apache.cassandra.sidecar.common.server.utils.SecondBoundConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.CdcDatabaseAccessor;
+import org.apache.cassandra.sidecar.utils.CdcUtil;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.spark.data.CqlTable;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.CqlUtils;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Central schema management component for Cassandra cluster schema monitoring and CDC table tracking.
+ * <p>
+ * This class provides comprehensive schema management functionality for Cassandra Sidecar, specifically
+ * focused on CDC (Change Data Capture) operations. It maintains real-time awareness of schema changes
+ * in the Cassandra cluster and manages CDC-enabled table metadata, enabling:
+ * <ul>
+ *   <li>Continuous monitoring of Cassandra cluster schema changes</li>
+ *   <li>Automatic detection and tracking of CDC-enabled tables</li>
+ *   <li>Schema change event notification to registered listeners</li>
+ *   <li>Table metadata caching and synchronization with CDC bridges</li>
+ *   <li>Periodic validation of CDC table configurations</li>
+ * </ul>
+ * <p>
+ * The class operates with two main periodic tasks:
+ * <ul>
+ *   <li><strong>Schema Refresh (60s interval):</strong> Monitors for schema changes by comparing
+ *       full schema snapshots and updates CDC table metadata when changes are detected</li>
+ *   <li><strong>Schema Monitor (49s interval):</strong> Validates that CDC-enabled tables
+ *       are properly configured in the Cassandra Schema.instance singleton</li>
+ * </ul>
+ * <p>
+ * Key functionalities include:
+ * <ul>
+ *   <li><strong>CDC Table Discovery:</strong> Automatically identifies and tracks tables with
+ *       CDC enabled from the cluster schema</li>
+ *   <li><strong>Schema Change Detection:</strong> Compares schema snapshots to detect modifications
+ *       and trigger appropriate updates to CDC subsystems</li>
+ *   <li><strong>Bridge Integration:</strong> Synchronizes schema information with Cassandra and
+ *       CDC bridges for consistent metadata handling</li>
+ *   <li><strong>Event Notification:</strong> Provides a listener mechanism for components that
+ *       need to react to schema changes</li>
+ *   <li><strong>Validation and Monitoring:</strong> Continuously validates CDC table configurations
+ *       and reports inconsistencies through metrics</li>
+ * </ul>
+ * <p>
+ * The schema refresh intervals are carefully chosen to balance responsiveness with system load:
+ * <ul>
+ *   <li>60-second refresh interval for schema change detection</li>
+ *   <li>49-second monitor interval (chosen to avoid harmonics with the 60s refresh cycle)</li>
+ * </ul>
+ * <p>
+ * This component is essential for CDC operations as it ensures that CDC consumers always have
+ * up-to-date schema information, enabling proper data serialization, deserialization, and
+ * processing across schema evolution events.
+ * <p>
+ * This class is thread-safe and designed as a singleton for dependency injection into CDC
+ * and other schema-dependent components.
+ *
+ * @see org.apache.cassandra.sidecar.db.CdcDatabaseAccessor
+ * @see org.apache.cassandra.bridge.CdcBridge
+ * @see org.apache.cassandra.spark.data.CqlTable
+ */
+@Singleton
+public class CassandraClusterSchema implements PeriodicTask
+{
+    // 49sec least-common multiple with 60sec is 49min so offers best monitor frequency without clashing with 60sec
+    private static final Logger LOGGER = LoggerFactory.getLogger(CassandraClusterSchema.class);
+
+    private final AtomicReference<String> currSchemaText = new AtomicReference<>("");
+    private final AtomicReference<Set<CqlTable>> cdcTables = new AtomicReference<>(Collections.emptySet());
+    private final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache = new ConcurrentHashMap<>();
+    private final CdcDatabaseAccessor databaseAccessor;
+    private final CopyOnWriteArrayList<Runnable> schemaChangeListeners = new CopyOnWriteArrayList<>();
+    private final SidecarConfiguration sidecarConfiguration;
+    private final InstanceMetadataFetcher instanceFetcher;
+    private final SecondBoundConfiguration tableSchemaRefreshTime;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    public CassandraClusterSchema(InstanceMetadataFetcher instanceFetcher,
+                                  CdcDatabaseAccessor databaseAccessor,
+                                  SidecarConfiguration sidecarConfiguration,
+                                  CassandraBridgeFactory cassandraBridgeFactory)
+    {
+
+        this.instanceFetcher = instanceFetcher;
+        this.databaseAccessor = databaseAccessor;
+        this.sidecarConfiguration = sidecarConfiguration;
+        this.tableSchemaRefreshTime = sidecarConfiguration.serviceConfiguration().cdcConfiguration().tableSchemaRefreshTime();
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    public void addSchemaChangeListener(Runnable listener)
+    {
+        schemaChangeListeners.add(listener);
+    }
+
+    public void refresh()
+    {
+        NodeSettings nodeSettings = instanceFetcher.callOnFirstAvailableInstance(instance-> instance.delegate().nodeSettings());
+        CassandraBridge cassandraBridge = cassandraBridgeFactory.get(nodeSettings.releaseVersion());
+        CdcBridge cdcBridge = CdcBridgeFactory.getCdcBridge(cassandraBridge);
+
+        try
+        {
+            LOGGER.info("Checking for schema changes...");
+            String fullSchemaText = databaseAccessor.fullSchema();
+            if (!fullSchemaText.equals(currSchemaText.get()))
+            {
+                LOGGER.info("Schema change detected, refreshing CDC tables");
+                currSchemaText.set(fullSchemaText);
+                Set<CqlTable> updatedCdcTables = buildCdcTables(fullSchemaText, databaseAccessor, tableIdCache, instanceFetcher, cassandraBridgeFactory);
+                LOGGER.info("Cdc enabled tables tables='{}'", 
+                            updatedCdcTables.stream()
+                                            .map(m -> String.format("%s.%s", m.keyspace(), m.table()))
+                                            .collect(Collectors.joining(",")));
+                cdcTables.set(updatedCdcTables);
+                cdcBridge.updateCdcSchema(updatedCdcTables, databaseAccessor.partitioner(),
+                                          ((keyspace, table) -> tableIdCache.get(TableIdentifier.of(keyspace, table))));
+                schemaChangeListeners.forEach(Runnable::run);
+            }
+        }
+        catch (IllegalStateException exception)
+        {
+            LOGGER.warn("There was a problem refreshing the schema. Database Accessor may not be ready", exception);
+            throw exception;
+        }
+        catch (Throwable t)
+        {
+            LOGGER.error("Unexpected error while refreshing the schema", t);
+            throw t;
+        }
+    }
+
+    public DurationSpec delay()
+    {
+        return tableSchemaRefreshTime;
+    }
+
+    @Override
+    public void execute(Promise<Void> promise)
+    {
+        try
+        {
+            refresh();
+            promise.tryComplete();
+        }
+        catch (Throwable t)
+        {
+            promise.fail(t);
+        }
+    }
+
+    @Override
+    public ScheduleDecision scheduleDecision()
+    {
+        boolean shouldSkip = !sidecarConfiguration.serviceConfiguration().schemaKeyspaceConfiguration().isEnabled()
+                             || !sidecarConfiguration.serviceConfiguration().cdcConfiguration().isEnabled();
+        return shouldSkip ? ScheduleDecision.SKIP : ScheduleDecision.EXECUTE;
+    }
+
+    @VisibleForTesting
+    static Set<CqlTable> buildCdcTables(CdcDatabaseAccessor cdcDatabaseAccessor,
+                                        ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
+                                        @NotNull InstanceMetadataFetcher instanceFetcher,
+                                        @NotNull CassandraBridgeFactory cassandraBridgeFactory)
+    {
+        return buildCdcTables(cdcDatabaseAccessor.fullSchema(),
+                              cdcDatabaseAccessor.partitioner(),
+                              tableIdCache,
+                              cdcDatabaseAccessor::getTableId,
+                              instanceFetcher,
+                              cassandraBridgeFactory);
+    }
+
+    private static Set<CqlTable> buildCdcTables(@NotNull String fullSchema,
+                                                @NotNull CdcDatabaseAccessor cdcDatabaseAccessor,
+                                                @NotNull ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
+                                                @NotNull InstanceMetadataFetcher instanceFetcher,
+                                                @NotNull CassandraBridgeFactory cassandraBridgeFactory)
+    {
+        return buildCdcTables(fullSchema,
+                              cdcDatabaseAccessor.partitioner(),
+                              tableIdCache,
+                              cdcDatabaseAccessor::getTableId,
+                              instanceFetcher,
+                              cassandraBridgeFactory);
+    }
+
+    private static Set<CqlTable> buildCdcTables(@NotNull final String fullSchema,
+                                                @NotNull final Partitioner partitioner,
+                                                @NotNull final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
+                                                @NotNull final Function<TableIdentifier, UUID> tableIdLoaderFunction,
+                                                @NotNull final InstanceMetadataFetcher instanceFetcher,
+                                                @NotNull final CassandraBridgeFactory cassandraBridgeFactory)
+    {
+        Map<TableIdentifier, String> createStmts = CdcUtil.extractCdcTables(fullSchema);
+        Map<String, Set<String>> udtsPerKeyspace = createStmts.keySet()
+                                                              .stream()
+                                                              .map(TableIdentifier::keyspace)
+                                                              .distinct() // remove duplicated keyspace strings
+                                                              .collect(Collectors.toMap(Function.identity(),
+                                                                                        keyspace -> CqlUtils.extractUdts(fullSchema, keyspace)));
+
+        Map<TableIdentifier, UUID> tableIds = createStmts.keySet()
+                                                         .stream()
+                                                         .collect(Collectors.toMap(Function.identity(),
+                                                                                   id -> tableIdCache.computeIfAbsent(id, tableIdLoaderFunction)));
+
+        NodeSettings nodeSettings = instanceFetcher.callOnFirstAvailableInstance(instance-> instance.delegate().nodeSettings());

Review Comment:
   We already have the nodeSettings in the callsite for this method, let's just use that



##########
server/src/main/java/org/apache/cassandra/sidecar/tasks/CassandraClusterSchema.java:
##########
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.tasks;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.google.inject.Singleton;
+import io.vertx.core.Promise;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.CdcBridge;
+import org.apache.cassandra.bridge.CdcBridgeFactory;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
+import org.apache.cassandra.sidecar.common.server.utils.SecondBoundConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.CdcDatabaseAccessor;
+import org.apache.cassandra.sidecar.utils.CdcUtil;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.spark.data.CqlTable;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.CqlUtils;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Central schema management component for Cassandra cluster schema monitoring and CDC table tracking.
+ * <p>
+ * This class provides comprehensive schema management functionality for Cassandra Sidecar, specifically
+ * focused on CDC (Change Data Capture) operations. It maintains real-time awareness of schema changes
+ * in the Cassandra cluster and manages CDC-enabled table metadata, enabling:
+ * <ul>
+ *   <li>Continuous monitoring of Cassandra cluster schema changes</li>
+ *   <li>Automatic detection and tracking of CDC-enabled tables</li>
+ *   <li>Schema change event notification to registered listeners</li>
+ *   <li>Table metadata caching and synchronization with CDC bridges</li>
+ *   <li>Periodic validation of CDC table configurations</li>
+ * </ul>
+ * <p>
+ * The class operates with two main periodic tasks:
+ * <ul>
+ *   <li><strong>Schema Refresh (60s interval):</strong> Monitors for schema changes by comparing
+ *       full schema snapshots and updates CDC table metadata when changes are detected</li>
+ *   <li><strong>Schema Monitor (49s interval):</strong> Validates that CDC-enabled tables
+ *       are properly configured in the Cassandra Schema.instance singleton</li>
+ * </ul>
+ * <p>
+ * Key functionalities include:
+ * <ul>
+ *   <li><strong>CDC Table Discovery:</strong> Automatically identifies and tracks tables with
+ *       CDC enabled from the cluster schema</li>
+ *   <li><strong>Schema Change Detection:</strong> Compares schema snapshots to detect modifications
+ *       and trigger appropriate updates to CDC subsystems</li>
+ *   <li><strong>Bridge Integration:</strong> Synchronizes schema information with Cassandra and
+ *       CDC bridges for consistent metadata handling</li>
+ *   <li><strong>Event Notification:</strong> Provides a listener mechanism for components that
+ *       need to react to schema changes</li>
+ *   <li><strong>Validation and Monitoring:</strong> Continuously validates CDC table configurations
+ *       and reports inconsistencies through metrics</li>
+ * </ul>
+ * <p>
+ * The schema refresh intervals are carefully chosen to balance responsiveness with system load:
+ * <ul>
+ *   <li>60-second refresh interval for schema change detection</li>
+ *   <li>49-second monitor interval (chosen to avoid harmonics with the 60s refresh cycle)</li>
+ * </ul>
+ * <p>
+ * This component is essential for CDC operations as it ensures that CDC consumers always have
+ * up-to-date schema information, enabling proper data serialization, deserialization, and
+ * processing across schema evolution events.
+ * <p>
+ * This class is thread-safe and designed as a singleton for dependency injection into CDC
+ * and other schema-dependent components.
+ *
+ * @see org.apache.cassandra.sidecar.db.CdcDatabaseAccessor
+ * @see org.apache.cassandra.bridge.CdcBridge
+ * @see org.apache.cassandra.spark.data.CqlTable
+ */
+@Singleton
+public class CassandraClusterSchema implements PeriodicTask
+{
+    // 49sec least-common multiple with 60sec is 49min so offers best monitor frequency without clashing with 60sec
+    private static final Logger LOGGER = LoggerFactory.getLogger(CassandraClusterSchema.class);
+
+    private final AtomicReference<String> currSchemaText = new AtomicReference<>("");
+    private final AtomicReference<Set<CqlTable>> cdcTables = new AtomicReference<>(Collections.emptySet());
+    private final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache = new ConcurrentHashMap<>();
+    private final CdcDatabaseAccessor databaseAccessor;
+    private final CopyOnWriteArrayList<Runnable> schemaChangeListeners = new CopyOnWriteArrayList<>();
+    private final SidecarConfiguration sidecarConfiguration;
+    private final InstanceMetadataFetcher instanceFetcher;
+    private final SecondBoundConfiguration tableSchemaRefreshTime;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    public CassandraClusterSchema(InstanceMetadataFetcher instanceFetcher,
+                                  CdcDatabaseAccessor databaseAccessor,
+                                  SidecarConfiguration sidecarConfiguration,
+                                  CassandraBridgeFactory cassandraBridgeFactory)
+    {
+
+        this.instanceFetcher = instanceFetcher;
+        this.databaseAccessor = databaseAccessor;
+        this.sidecarConfiguration = sidecarConfiguration;
+        this.tableSchemaRefreshTime = sidecarConfiguration.serviceConfiguration().cdcConfiguration().tableSchemaRefreshTime();
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    public void addSchemaChangeListener(Runnable listener)
+    {
+        schemaChangeListeners.add(listener);
+    }
+
+    public void refresh()
+    {
+        NodeSettings nodeSettings = instanceFetcher.callOnFirstAvailableInstance(instance-> instance.delegate().nodeSettings());
+        CassandraBridge cassandraBridge = cassandraBridgeFactory.get(nodeSettings.releaseVersion());
+        CdcBridge cdcBridge = CdcBridgeFactory.getCdcBridge(cassandraBridge);
+
+        try
+        {
+            LOGGER.info("Checking for schema changes...");
+            String fullSchemaText = databaseAccessor.fullSchema();
+            if (!fullSchemaText.equals(currSchemaText.get()))
+            {
+                LOGGER.info("Schema change detected, refreshing CDC tables");
+                currSchemaText.set(fullSchemaText);
+                Set<CqlTable> updatedCdcTables = buildCdcTables(fullSchemaText, databaseAccessor, tableIdCache, instanceFetcher, cassandraBridgeFactory);
+                LOGGER.info("Cdc enabled tables tables='{}'", 
+                            updatedCdcTables.stream()
+                                            .map(m -> String.format("%s.%s", m.keyspace(), m.table()))
+                                            .collect(Collectors.joining(",")));
+                cdcTables.set(updatedCdcTables);
+                cdcBridge.updateCdcSchema(updatedCdcTables, databaseAccessor.partitioner(),

Review Comment:
   and of course Partitioner is in spark, so we wouldn't be able to change it here. So we'll need to do the check before calling valueOF



##########
server/src/main/java/org/apache/cassandra/sidecar/tasks/CassandraClusterSchema.java:
##########
@@ -0,0 +1,273 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.tasks;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.google.inject.Singleton;
+import io.vertx.core.Promise;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.CdcBridge;
+import org.apache.cassandra.bridge.CdcBridgeFactory;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
+import org.apache.cassandra.sidecar.common.server.utils.SecondBoundConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.CdcDatabaseAccessor;
+import org.apache.cassandra.sidecar.utils.CdcUtil;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.spark.data.CqlTable;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.CqlUtils;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Central schema management component for Cassandra cluster schema monitoring and CDC table tracking.
+ * <p>
+ * This class provides comprehensive schema management functionality for Cassandra Sidecar, specifically
+ * focused on CDC (Change Data Capture) operations. It maintains real-time awareness of schema changes
+ * in the Cassandra cluster and manages CDC-enabled table metadata, enabling:
+ * <ul>
+ *   <li>Continuous monitoring of Cassandra cluster schema changes</li>
+ *   <li>Automatic detection and tracking of CDC-enabled tables</li>
+ *   <li>Schema change event notification to registered listeners</li>
+ *   <li>Table metadata caching and synchronization with CDC bridges</li>
+ *   <li>Periodic validation of CDC table configurations</li>
+ * </ul>
+ * <p>
+ * The class operates with two main periodic tasks:
+ * <ul>
+ *   <li><strong>Schema Refresh (60s interval):</strong> Monitors for schema changes by comparing
+ *       full schema snapshots and updates CDC table metadata when changes are detected</li>
+ *   <li><strong>Schema Monitor (49s interval):</strong> Validates that CDC-enabled tables
+ *       are properly configured in the Cassandra Schema.instance singleton</li>
+ * </ul>
+ * <p>
+ * Key functionalities include:
+ * <ul>
+ *   <li><strong>CDC Table Discovery:</strong> Automatically identifies and tracks tables with
+ *       CDC enabled from the cluster schema</li>
+ *   <li><strong>Schema Change Detection:</strong> Compares schema snapshots to detect modifications
+ *       and trigger appropriate updates to CDC subsystems</li>
+ *   <li><strong>Bridge Integration:</strong> Synchronizes schema information with Cassandra and
+ *       CDC bridges for consistent metadata handling</li>
+ *   <li><strong>Event Notification:</strong> Provides a listener mechanism for components that
+ *       need to react to schema changes</li>
+ *   <li><strong>Validation and Monitoring:</strong> Continuously validates CDC table configurations
+ *       and reports inconsistencies through metrics</li>
+ * </ul>
+ * <p>
+ * The schema refresh intervals are carefully chosen to balance responsiveness with system load:
+ * <ul>
+ *   <li>60-second refresh interval for schema change detection</li>
+ *   <li>49-second monitor interval (chosen to avoid harmonics with the 60s refresh cycle)</li>
+ * </ul>
+ * <p>
+ * This component is essential for CDC operations as it ensures that CDC consumers always have
+ * up-to-date schema information, enabling proper data serialization, deserialization, and
+ * processing across schema evolution events.
+ * <p>
+ * This class is thread-safe and designed as a singleton for dependency injection into CDC
+ * and other schema-dependent components.
+ *
+ * @see org.apache.cassandra.sidecar.db.CdcDatabaseAccessor
+ * @see org.apache.cassandra.bridge.CdcBridge
+ * @see org.apache.cassandra.spark.data.CqlTable
+ */
+@Singleton
+public class CassandraClusterSchema implements PeriodicTask
+{
+    // 49sec least-common multiple with 60sec is 49min so offers best monitor frequency without clashing with 60sec
+    private static final Logger LOGGER = LoggerFactory.getLogger(CassandraClusterSchema.class);
+
+    private final AtomicReference<String> currSchemaText = new AtomicReference<>("");
+    private final AtomicReference<Set<CqlTable>> cdcTables = new AtomicReference<>(Collections.emptySet());
+    private final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache = new ConcurrentHashMap<>();
+    private final CdcDatabaseAccessor databaseAccessor;
+    private final CopyOnWriteArrayList<Runnable> schemaChangeListeners = new CopyOnWriteArrayList<>();
+    private final SidecarConfiguration sidecarConfiguration;
+    private final InstanceMetadataFetcher instanceFetcher;
+    private final SecondBoundConfiguration tableSchemaRefreshTime;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    public CassandraClusterSchema(InstanceMetadataFetcher instanceFetcher,
+                                  CdcDatabaseAccessor databaseAccessor,
+                                  SidecarConfiguration sidecarConfiguration,
+                                  CassandraBridgeFactory cassandraBridgeFactory)
+    {
+
+        this.instanceFetcher = instanceFetcher;
+        this.databaseAccessor = databaseAccessor;
+        this.sidecarConfiguration = sidecarConfiguration;
+        this.tableSchemaRefreshTime = sidecarConfiguration.serviceConfiguration().cdcConfiguration().tableSchemaRefreshTime();
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    public void addSchemaChangeListener(Runnable listener)
+    {
+        schemaChangeListeners.add(listener);
+    }
+
+    public void refresh()
+    {
+        NodeSettings nodeSettings = instanceFetcher.callOnFirstAvailableInstance(instance-> instance.delegate().nodeSettings());
+        CassandraBridge cassandraBridge = cassandraBridgeFactory.get(nodeSettings.releaseVersion());
+        CdcBridge cdcBridge = CdcBridgeFactory.getCdcBridge(cassandraBridge);
+
+        try
+        {
+            LOGGER.info("Checking for schema changes...");
+            String fullSchemaText = databaseAccessor.fullSchema();
+            if (!fullSchemaText.equals(currSchemaText.get()))
+            {
+                LOGGER.info("Schema change detected, refreshing CDC tables");
+                currSchemaText.set(fullSchemaText);
+                Set<CqlTable> updatedCdcTables = buildCdcTables(fullSchemaText, databaseAccessor, tableIdCache, instanceFetcher, cassandraBridgeFactory);
+                LOGGER.info("Cdc enabled tables tables='{}'", 
+                            updatedCdcTables.stream()
+                                            .map(m -> String.format("%s.%s", m.keyspace(), m.table()))
+                                            .collect(Collectors.joining(",")));
+                cdcTables.set(updatedCdcTables);
+                cdcBridge.updateCdcSchema(updatedCdcTables, databaseAccessor.partitioner(),
+                                          ((keyspace, table) -> tableIdCache.get(TableIdentifier.of(keyspace, table))));
+                schemaChangeListeners.forEach(Runnable::run);
+            }
+        }
+        catch (IllegalStateException exception)
+        {
+            LOGGER.warn("There was a problem refreshing the schema. Database Accessor may not be ready", exception);
+            throw exception;
+        }
+        catch (Throwable t)
+        {
+            LOGGER.error("Unexpected error while refreshing the schema", t);
+            throw t;
+        }
+    }
+
+    public DurationSpec delay()
+    {
+        return tableSchemaRefreshTime;
+    }
+
+    @Override
+    public void execute(Promise<Void> promise)
+    {
+        try
+        {
+            refresh();
+            promise.tryComplete();
+        }
+        catch (Throwable t)
+        {
+            promise.fail(t);
+        }
+    }
+
+    @Override
+    public ScheduleDecision scheduleDecision()
+    {
+        boolean shouldSkip = !sidecarConfiguration.serviceConfiguration().schemaKeyspaceConfiguration().isEnabled()
+                             || !sidecarConfiguration.serviceConfiguration().cdcConfiguration().isEnabled();
+        return shouldSkip ? ScheduleDecision.SKIP : ScheduleDecision.EXECUTE;
+    }
+
+    @VisibleForTesting
+    static Set<CqlTable> buildCdcTables(CdcDatabaseAccessor cdcDatabaseAccessor,
+                                        ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
+                                        @NotNull InstanceMetadataFetcher instanceFetcher,
+                                        @NotNull CassandraBridgeFactory cassandraBridgeFactory)
+    {
+        return buildCdcTables(cdcDatabaseAccessor.fullSchema(),
+                              cdcDatabaseAccessor.partitioner(),
+                              tableIdCache,
+                              cdcDatabaseAccessor::getTableId,
+                              instanceFetcher,
+                              cassandraBridgeFactory);
+    }
+
+    private static Set<CqlTable> buildCdcTables(@NotNull String fullSchema,
+                                                @NotNull CdcDatabaseAccessor cdcDatabaseAccessor,
+                                                @NotNull ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
+                                                @NotNull InstanceMetadataFetcher instanceFetcher,
+                                                @NotNull CassandraBridgeFactory cassandraBridgeFactory)
+    {
+        return buildCdcTables(fullSchema,
+                              cdcDatabaseAccessor.partitioner(),
+                              tableIdCache,
+                              cdcDatabaseAccessor::getTableId,
+                              instanceFetcher,
+                              cassandraBridgeFactory);
+    }
+
+    private static Set<CqlTable> buildCdcTables(@NotNull final String fullSchema,
+                                                @NotNull final Partitioner partitioner,
+                                                @NotNull final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
+                                                @NotNull final Function<TableIdentifier, UUID> tableIdLoaderFunction,
+                                                @NotNull final InstanceMetadataFetcher instanceFetcher,
+                                                @NotNull final CassandraBridgeFactory cassandraBridgeFactory)
+    {
+        Map<TableIdentifier, String> createStmts = CdcUtil.extractCdcTables(fullSchema);
+        Map<String, Set<String>> udtsPerKeyspace = createStmts.keySet()
+                                                              .stream()
+                                                              .map(TableIdentifier::keyspace)
+                                                              .distinct() // remove duplicated keyspace strings
+                                                              .collect(Collectors.toMap(Function.identity(),
+                                                                                        keyspace -> CqlUtils.extractUdts(fullSchema, keyspace)));
+
+        Map<TableIdentifier, UUID> tableIds = createStmts.keySet()
+                                                         .stream()
+                                                         .collect(Collectors.toMap(Function.identity(),
+                                                                                   id -> tableIdCache.computeIfAbsent(id, tableIdLoaderFunction)));
+
+        NodeSettings nodeSettings = instanceFetcher.callOnFirstAvailableInstance(instance-> instance.delegate().nodeSettings());

Review Comment:
   as a matter of fact, we have the bridge, we should just pass the bridge



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org


Re: [PR] CASSSIDECAR-245: Implementation of CassandraClusterSchema [cassandra-sidecar]

Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #251:
URL: https://github.com/apache/cassandra-sidecar/pull/251#discussion_r2331570652


##########
server/src/main/java/org/apache/cassandra/sidecar/db/schema/TableHistorySchema.java:
##########
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.db.schema;
+
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.PreparedStatement;
+import com.datastax.driver.core.Session;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import org.apache.cassandra.sidecar.config.SchemaKeyspaceConfiguration;
+import org.apache.cassandra.sidecar.config.ServiceConfiguration;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Schema definition and management for tracking table schema evolution history.
+ * <p>
+ * This class extends {@link TableSchema} to provide specialized schema management for storing
+ * historical versions of table schemas in Cassandra Sidecar. The table schema history tracking
+ * is essential for CDC operations and data consistency, enabling:
+ * <ul>
+ *   <li>Schema version tracking for CDC-enabled tables across time</li>
+ *   <li>Historical schema retrieval for data processing and compatibility checks</li>
+ *   <li>Schema evolution auditing and change management</li>
+ *   <li>Version-aware data processing in CDC pipelines</li>
+ * </ul>
+ * <p>
+ * The table schema is designed with the following characteristics:
+ * <ul>
+ *   <li><strong>Partitioning:</strong> Data is partitioned by keyspace ({@code ks}) and 
+ *       table name ({@code tb}) to organize schemas by table identity</li>
+ *   <li><strong>Clustering:</strong> Ordered by schema version ({@code version}) to enable
+ *       chronological access to schema changes</li>
+ *   <li><strong>Versioning:</strong> Uses UUID-based versioning for unique schema identification</li>
+ *   <li><strong>Timestamping:</strong> Automatic creation timestamp tracking with {@code created_at}</li>
+ * </ul>
+ * <p>
+ * The table structure includes:
+ * <pre>{@code
+ * CREATE TABLE table_schema_history (
+ *   ks text,                    -- Keyspace name
+ *   tb text,                    -- Table name
+ *   version uuid,               -- Schema version identifier
+ *   created_at timeuuid,        -- Schema creation timestamp
+ *   table_schema text,          -- Complete table schema DDL
+ *   PRIMARY KEY ((ks, tb), version)
+ * )
+ * }</pre>
+ * <p>
+ * This schema supports CDC operations by maintaining a complete history of table schemas,
+ * allowing CDC consumers to process data with the correct schema version that was active
+ * when the data was written. This is crucial for maintaining data integrity across schema
+ * evolution in long-running CDC pipelines.
+ * <p>
+ * This class is thread-safe and designed as a singleton for dependency injection into
+ * components that require table schema history access.
+ *
+ * @see TableSchema
+ * @see org.apache.cassandra.sidecar.db.CdcDatabaseAccessor
+ */
+@Singleton
+public class TableHistorySchema extends TableSchema

Review Comment:
   This schema should only be initialized on the lease holder
   ```suggestion
   public class TableHistorySchema extends TableSchema implements ExecuteOnClusterLeaseholderOnly
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/tasks/CassandraClusterSchemaMonitor.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.tasks;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.google.inject.Singleton;
+import io.vertx.core.Promise;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.CdcBridge;
+import org.apache.cassandra.bridge.CdcBridgeFactory;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.CdcDatabaseAccessor;
+import org.apache.cassandra.sidecar.utils.CdcUtil;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.spark.data.CqlTable;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.CqlUtils;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Central schema management component for Cassandra cluster schema monitoring and CDC table tracking.
+ * This class provides comprehensive schema management functionality for Cassandra Sidecar, specifically
+ * focused on CDC (Change Data Capture) operations. It maintains real-time awareness of schema changes
+ * in the Cassandra cluster and manages CDC-enabled table metadata.
+ */
+@Singleton
+public class CassandraClusterSchemaMonitor implements PeriodicTask
+{
+    // 49sec least-common multiple with 60sec is 49min so offers best monitor frequency without clashing with 60sec
+    private static final Logger LOGGER = LoggerFactory.getLogger(CassandraClusterSchemaMonitor.class);
+
+    private final AtomicReference<String> currSchemaText = new AtomicReference<>("");
+    private final AtomicReference<Set<CqlTable>> cdcTables = new AtomicReference<>(Collections.emptySet());
+    private final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache = new ConcurrentHashMap<>();
+    private final CdcDatabaseAccessor databaseAccessor;
+    private final CopyOnWriteArrayList<Runnable> schemaChangeListeners = new CopyOnWriteArrayList<>();
+    private final SidecarConfiguration sidecarConfiguration;
+    private final InstanceMetadataFetcher instanceFetcher;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    public CassandraClusterSchemaMonitor(InstanceMetadataFetcher instanceFetcher,
+                                         CdcDatabaseAccessor databaseAccessor,
+                                         SidecarConfiguration sidecarConfiguration,
+                                         CassandraBridgeFactory cassandraBridgeFactory)
+    {
+
+        this.instanceFetcher = instanceFetcher;
+        this.databaseAccessor = databaseAccessor;
+        this.sidecarConfiguration = sidecarConfiguration;
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    public void addSchemaChangeListener(Runnable listener)
+    {
+        schemaChangeListeners.add(listener);
+    }
+
+    public void refresh()
+    {
+        NodeSettings nodeSettings = instanceFetcher.callOnFirstAvailableInstance(instance-> instance.delegate().nodeSettings());
+        CassandraBridge cassandraBridge = cassandraBridgeFactory.get(nodeSettings.releaseVersion());
+        CdcBridge cdcBridge = CdcBridgeFactory.getCdcBridge(cassandraBridge);
+
+        try
+        {
+            LOGGER.debug("Checking for schema changes...");
+            String fullSchemaText = databaseAccessor.fullSchema();
+            if (!fullSchemaText.equals(currSchemaText.get()))
+            {
+                LOGGER.info("Schema change detected, refreshing CDC tables");
+                currSchemaText.set(fullSchemaText);
+                Set<CqlTable> updatedCdcTables = buildCdcTables(fullSchemaText, databaseAccessor, tableIdCache, instanceFetcher, cassandraBridge);
+                LOGGER.info("Cdc enabled tables tables='{}'", 
+                            updatedCdcTables.stream()
+                                            .map(m -> String.format("%s.%s", m.keyspace(), m.table()))
+                                            .collect(Collectors.joining(",")));
+                cdcTables.set(updatedCdcTables);
+
+                cdcBridge.updateCdcSchema(updatedCdcTables, getPartitioner(nodeSettings),
+                                          ((keyspace, table) -> tableIdCache.get(TableIdentifier.of(keyspace, table))));
+                schemaChangeListeners.forEach(Runnable::run);
+            }
+        }
+        catch (IllegalStateException exception)
+        {
+            LOGGER.warn("There was a problem refreshing the schema. Database Accessor may not be ready", exception);
+            throw exception;
+        }
+        catch (Throwable t)
+        {
+            LOGGER.error("Unexpected error while refreshing the schema", t);
+            throw t;
+        }
+    }
+
+    private Partitioner getPartitioner(NodeSettings nodeSettings)
+    {
+        if (nodeSettings.partitioner().contains("."))
+        {
+            String[] splitPartitionerName = nodeSettings.partitioner().split("\\.");
+            return Partitioner.valueOf(splitPartitionerName[splitPartitionerName.length - 1]);
+        }
+        return Partitioner.valueOf(nodeSettings.partitioner());
+    }
+
+    @Override
+    public DurationSpec delay()
+    {
+        return sidecarConfiguration.serviceConfiguration().cdcConfiguration().tableSchemaRefreshTime();
+    }
+
+    @Override
+    public void execute(Promise<Void> promise)
+    {
+        try
+        {
+            refresh();
+            promise.tryComplete();
+        }
+        catch (Throwable t)
+        {
+            promise.fail(t);
+        }
+    }
+
+    @Override
+    public ScheduleDecision scheduleDecision()
+    {
+        if (sidecarConfiguration.serviceConfiguration().schemaKeyspaceConfiguration().isEnabled() &&
+            sidecarConfiguration.serviceConfiguration().cdcConfiguration().isEnabled())
+        {
+            return ScheduleDecision.EXECUTE;
+        }
+        return ScheduleDecision.SKIP;
+    }
+
+    @VisibleForTesting
+    static Set<CqlTable> buildCdcTables(CdcDatabaseAccessor cdcDatabaseAccessor,
+                                        ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
+                                        @NotNull InstanceMetadataFetcher instanceFetcher,
+                                        @NotNull final CassandraBridge cassandraBridge)
+    {
+        return buildCdcTables(cdcDatabaseAccessor.fullSchema(),
+                              cdcDatabaseAccessor.partitioner(),
+                              tableIdCache,
+                              cdcDatabaseAccessor::getTableId,
+                              instanceFetcher,
+                              cassandraBridge);
+    }
+
+    private static Set<CqlTable> buildCdcTables(@NotNull String fullSchema,
+                                                @NotNull CdcDatabaseAccessor cdcDatabaseAccessor,
+                                                @NotNull ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
+                                                @NotNull InstanceMetadataFetcher instanceFetcher,
+                                                @NotNull final CassandraBridge cassandraBridge)

Review Comment:
   instanceFetcher is no longer needed
   ```suggestion
       private static Set<CqlTable> buildCdcTables(@NotNull String fullSchema,
                                                   @NotNull CdcDatabaseAccessor cdcDatabaseAccessor,
                                                   @NotNull ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
                                                   @NotNull CassandraBridge cassandraBridge)
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/tasks/CassandraClusterSchemaMonitor.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.tasks;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.google.inject.Singleton;
+import io.vertx.core.Promise;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.CdcBridge;
+import org.apache.cassandra.bridge.CdcBridgeFactory;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.CdcDatabaseAccessor;
+import org.apache.cassandra.sidecar.utils.CdcUtil;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.spark.data.CqlTable;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.CqlUtils;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Central schema management component for Cassandra cluster schema monitoring and CDC table tracking.
+ * This class provides comprehensive schema management functionality for Cassandra Sidecar, specifically
+ * focused on CDC (Change Data Capture) operations. It maintains real-time awareness of schema changes
+ * in the Cassandra cluster and manages CDC-enabled table metadata.
+ */
+@Singleton
+public class CassandraClusterSchemaMonitor implements PeriodicTask
+{
+    // 49sec least-common multiple with 60sec is 49min so offers best monitor frequency without clashing with 60sec
+    private static final Logger LOGGER = LoggerFactory.getLogger(CassandraClusterSchemaMonitor.class);
+
+    private final AtomicReference<String> currSchemaText = new AtomicReference<>("");
+    private final AtomicReference<Set<CqlTable>> cdcTables = new AtomicReference<>(Collections.emptySet());
+    private final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache = new ConcurrentHashMap<>();
+    private final CdcDatabaseAccessor databaseAccessor;
+    private final CopyOnWriteArrayList<Runnable> schemaChangeListeners = new CopyOnWriteArrayList<>();
+    private final SidecarConfiguration sidecarConfiguration;
+    private final InstanceMetadataFetcher instanceFetcher;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    public CassandraClusterSchemaMonitor(InstanceMetadataFetcher instanceFetcher,
+                                         CdcDatabaseAccessor databaseAccessor,
+                                         SidecarConfiguration sidecarConfiguration,
+                                         CassandraBridgeFactory cassandraBridgeFactory)
+    {
+
+        this.instanceFetcher = instanceFetcher;
+        this.databaseAccessor = databaseAccessor;
+        this.sidecarConfiguration = sidecarConfiguration;
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    public void addSchemaChangeListener(Runnable listener)
+    {
+        schemaChangeListeners.add(listener);
+    }
+
+    public void refresh()
+    {
+        NodeSettings nodeSettings = instanceFetcher.callOnFirstAvailableInstance(instance-> instance.delegate().nodeSettings());
+        CassandraBridge cassandraBridge = cassandraBridgeFactory.get(nodeSettings.releaseVersion());
+        CdcBridge cdcBridge = CdcBridgeFactory.getCdcBridge(cassandraBridge);
+
+        try
+        {
+            LOGGER.debug("Checking for schema changes...");
+            String fullSchemaText = databaseAccessor.fullSchema();
+            if (!fullSchemaText.equals(currSchemaText.get()))
+            {
+                LOGGER.info("Schema change detected, refreshing CDC tables");
+                currSchemaText.set(fullSchemaText);
+                Set<CqlTable> updatedCdcTables = buildCdcTables(fullSchemaText, databaseAccessor, tableIdCache, instanceFetcher, cassandraBridge);
+                LOGGER.info("Cdc enabled tables tables='{}'", 
+                            updatedCdcTables.stream()
+                                            .map(m -> String.format("%s.%s", m.keyspace(), m.table()))
+                                            .collect(Collectors.joining(",")));
+                cdcTables.set(updatedCdcTables);
+
+                cdcBridge.updateCdcSchema(updatedCdcTables, getPartitioner(nodeSettings),
+                                          ((keyspace, table) -> tableIdCache.get(TableIdentifier.of(keyspace, table))));
+                schemaChangeListeners.forEach(Runnable::run);
+            }
+        }
+        catch (IllegalStateException exception)
+        {
+            LOGGER.warn("There was a problem refreshing the schema. Database Accessor may not be ready", exception);
+            throw exception;
+        }
+        catch (Throwable t)
+        {
+            LOGGER.error("Unexpected error while refreshing the schema", t);
+            throw t;
+        }
+    }
+
+    private Partitioner getPartitioner(NodeSettings nodeSettings)
+    {
+        if (nodeSettings.partitioner().contains("."))
+        {
+            String[] splitPartitionerName = nodeSettings.partitioner().split("\\.");
+            return Partitioner.valueOf(splitPartitionerName[splitPartitionerName.length - 1]);
+        }
+        return Partitioner.valueOf(nodeSettings.partitioner());
+    }
+
+    @Override
+    public DurationSpec delay()
+    {
+        return sidecarConfiguration.serviceConfiguration().cdcConfiguration().tableSchemaRefreshTime();
+    }
+
+    @Override
+    public void execute(Promise<Void> promise)
+    {
+        try
+        {
+            refresh();
+            promise.tryComplete();
+        }
+        catch (Throwable t)
+        {
+            promise.fail(t);
+        }
+    }
+
+    @Override
+    public ScheduleDecision scheduleDecision()
+    {
+        if (sidecarConfiguration.serviceConfiguration().schemaKeyspaceConfiguration().isEnabled() &&
+            sidecarConfiguration.serviceConfiguration().cdcConfiguration().isEnabled())
+        {
+            return ScheduleDecision.EXECUTE;
+        }
+        return ScheduleDecision.SKIP;
+    }
+
+    @VisibleForTesting
+    static Set<CqlTable> buildCdcTables(CdcDatabaseAccessor cdcDatabaseAccessor,
+                                        ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
+                                        @NotNull InstanceMetadataFetcher instanceFetcher,
+                                        @NotNull final CassandraBridge cassandraBridge)

Review Comment:
   instanceFetcher is no longer needed
   ```suggestion
       static Set<CqlTable> buildCdcTables(CdcDatabaseAccessor cdcDatabaseAccessor,
                                           ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
                                           @NotNull CassandraBridge cassandraBridge)
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/db/schema/CdcStatesSchema.java:
##########
@@ -0,0 +1,169 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.db.schema;
+
+import java.util.concurrent.TimeUnit;
+
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.PreparedStatement;
+import com.datastax.driver.core.Session;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import org.apache.cassandra.sidecar.config.SchemaKeyspaceConfiguration;
+import org.apache.cassandra.sidecar.config.ServiceConfiguration;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Schema definition and management for the CDC (Change Data Capture) state persistence table.
+ * <p>
+ * This class extends {@link TableSchema} to provide specialized schema management for storing
+ * and retrieving CDC state data in Cassandra Sidecar. The CDC state table is used to persist
+ * the current processing state of CDC consumers across token ranges, enabling:
+ * <ul>
+ *   <li>State persistence for fault tolerance and resumption after restarts</li>
+ *   <li>Distributed processing coordination across multiple CDC consumers</li>
+ *   <li>Token range-aware state storage for scalable CDC operations</li>
+ *   <li>Time-based data retention through TTL configuration</li>
+ * </ul>
+ * <p>
+ * The table schema is designed with the following key characteristics:
+ * <ul>
+ *   <li><strong>Partitioning:</strong> Data is partitioned by {@code job_id} and {@code split}
+ *       to distribute CDC state across multiple partitions for scalability</li>
+ *   <li><strong>Clustering:</strong> Ordered by token range boundaries ({@code start}, {@code end})
+ *       to enable efficient range queries</li>
+ *   <li><strong>TTL:</strong> Configurable time-to-live (default 30 days) for automatic cleanup
+ *       of old CDC state data</li>
+ *   <li><strong>Compaction:</strong> Uses TimeWindowCompactionStrategy optimized for time-series
+ *       data patterns</li>
+ * </ul>
+ * <p>
+ * The table structure includes:
+ * <pre>{@code
+ * CREATE TABLE cdc_state_v2 (
+ *   job_id text,           -- CDC job identifier
+ *   split smallint,        -- Token range split identifier
+ *   start varint,          -- Token range start boundary
+ *   end varint,            -- Token range end boundary
+ *   state blob,            -- Serialized CDC state data
+ *   PRIMARY KEY ((job_id, split), start, end)
+ * )
+ * }</pre>
+ * <p>
+ * This class is thread-safe and designed as a singleton for dependency injection into
+ * components that require CDC state table access.
+ *
+ * @see TableSchema
+ * @see org.apache.cassandra.sidecar.db.CdcDatabaseAccessor
+ */
+@Singleton
+public class CdcStatesSchema extends TableSchema

Review Comment:
   should only be initialized in the cluster lease holder
   ```suggestion
   public class CdcStatesSchema extends TableSchema implements ExecuteOnClusterLeaseholderOnly
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/db/schema/TableHistorySchema.java:
##########
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.db.schema;
+
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.PreparedStatement;
+import com.datastax.driver.core.Session;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import org.apache.cassandra.sidecar.config.SchemaKeyspaceConfiguration;
+import org.apache.cassandra.sidecar.config.ServiceConfiguration;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Schema definition and management for tracking table schema evolution history.
+ * <p>
+ * This class extends {@link TableSchema} to provide specialized schema management for storing
+ * historical versions of table schemas in Cassandra Sidecar. The table schema history tracking
+ * is essential for CDC operations and data consistency, enabling:
+ * <ul>
+ *   <li>Schema version tracking for CDC-enabled tables across time</li>
+ *   <li>Historical schema retrieval for data processing and compatibility checks</li>
+ *   <li>Schema evolution auditing and change management</li>
+ *   <li>Version-aware data processing in CDC pipelines</li>
+ * </ul>
+ * <p>
+ * The table schema is designed with the following characteristics:
+ * <ul>
+ *   <li><strong>Partitioning:</strong> Data is partitioned by keyspace ({@code ks}) and 
+ *       table name ({@code tb}) to organize schemas by table identity</li>
+ *   <li><strong>Clustering:</strong> Ordered by schema version ({@code version}) to enable
+ *       chronological access to schema changes</li>
+ *   <li><strong>Versioning:</strong> Uses UUID-based versioning for unique schema identification</li>
+ *   <li><strong>Timestamping:</strong> Automatic creation timestamp tracking with {@code created_at}</li>
+ * </ul>
+ * <p>
+ * The table structure includes:
+ * <pre>{@code
+ * CREATE TABLE table_schema_history (
+ *   ks text,                    -- Keyspace name
+ *   tb text,                    -- Table name
+ *   version uuid,               -- Schema version identifier
+ *   created_at timeuuid,        -- Schema creation timestamp
+ *   table_schema text,          -- Complete table schema DDL
+ *   PRIMARY KEY ((ks, tb), version)
+ * )
+ * }</pre>
+ * <p>
+ * This schema supports CDC operations by maintaining a complete history of table schemas,
+ * allowing CDC consumers to process data with the correct schema version that was active
+ * when the data was written. This is crucial for maintaining data integrity across schema
+ * evolution in long-running CDC pipelines.
+ * <p>
+ * This class is thread-safe and designed as a singleton for dependency injection into
+ * components that require table schema history access.
+ *
+ * @see TableSchema
+ * @see org.apache.cassandra.sidecar.db.CdcDatabaseAccessor
+ */
+@Singleton
+public class TableHistorySchema extends TableSchema
+{
+    private static final String TABLE_SCHEMA_HISTORY = "table_schema_history";
+
+    private final SchemaKeyspaceConfiguration keyspaceConfig;
+
+    // prepared statements
+    private PreparedStatement insertTableSchema;
+    private PreparedStatement selectVersionTableSchema;
+
+    @Inject
+    public TableHistorySchema(ServiceConfiguration configuration)
+    {
+        this.keyspaceConfig = configuration.schemaKeyspaceConfiguration();
+    }
+
+    @Override
+    protected void prepareStatements(@NotNull Session session)
+    {
+        insertTableSchema = prepare(insertTableSchema, session, CqlLiterals.insertTableSchema(keyspaceConfig));
+        selectVersionTableSchema = prepare(selectVersionTableSchema, session, CqlLiterals.selectVersionTableSchema(keyspaceConfig));
+    }
+
+    @Override
+    protected String keyspaceName()
+    {
+        return keyspaceConfig.keyspace();
+    }
+
+    @Override
+    protected String tableName()
+    {
+        return TABLE_SCHEMA_HISTORY;
+    }
+
+    @Override
+    protected boolean exists(@NotNull Metadata metadata)
+    {
+        KeyspaceMetadata ksMetadata = metadata.getKeyspace(keyspaceConfig.keyspace());
+        if (ksMetadata == null)
+        {
+            return false;
+        }
+
+        return ksMetadata.getTable(TABLE_SCHEMA_HISTORY) != null;
+    }
+
+    @Override
+    protected String createSchemaStatement()
+    {
+        return String.format("CREATE TABLE IF NOT EXISTS %s.%s (" +
+                             "  ks text," +
+                             "  tb text," +

Review Comment:
   NIT: to maintain consistency with Cassandra column naming
   ```suggestion
                                "  keyspace_name text," +
                                "  table_name text," +
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/modules/CdcModule.java:
##########
@@ -85,6 +97,42 @@ PeriodicTask cdcRawDirectorySpaceCleanercPeriodicTask(CdcRawDirectorySpaceCleane
         return cleanerTask;
     }
 
+    @ProvidesIntoMap
+    @KeyClassMapKey(PeriodicTaskMapKeys.CassandraClusterSchemaTaskKey.class)
+    PeriodicTask cassandraClusterSchema(InstanceMetadataFetcher instanceMetadataFetcher,

Review Comment:
   ```suggestion
       PeriodicTask cassandraClusterSchemaMonitor(InstanceMetadataFetcher instanceMetadataFetcher,
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/tasks/CassandraClusterSchemaMonitor.java:
##########
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cassandra.sidecar.tasks;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import com.google.inject.Singleton;
+import io.vertx.core.Promise;
+import org.apache.cassandra.bridge.CassandraBridge;
+import org.apache.cassandra.bridge.CassandraBridgeFactory;
+import org.apache.cassandra.bridge.CdcBridge;
+import org.apache.cassandra.bridge.CdcBridgeFactory;
+import org.apache.cassandra.sidecar.common.response.NodeSettings;
+import org.apache.cassandra.sidecar.common.server.utils.DurationSpec;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.CdcDatabaseAccessor;
+import org.apache.cassandra.sidecar.utils.CdcUtil;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.apache.cassandra.spark.data.CqlTable;
+import org.apache.cassandra.spark.data.ReplicationFactor;
+import org.apache.cassandra.spark.data.partitioner.Partitioner;
+import org.apache.cassandra.spark.utils.CqlUtils;
+import org.apache.cassandra.spark.utils.TableIdentifier;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Central schema management component for Cassandra cluster schema monitoring and CDC table tracking.
+ * This class provides comprehensive schema management functionality for Cassandra Sidecar, specifically
+ * focused on CDC (Change Data Capture) operations. It maintains real-time awareness of schema changes
+ * in the Cassandra cluster and manages CDC-enabled table metadata.
+ */
+@Singleton
+public class CassandraClusterSchemaMonitor implements PeriodicTask
+{
+    // 49sec least-common multiple with 60sec is 49min so offers best monitor frequency without clashing with 60sec
+    private static final Logger LOGGER = LoggerFactory.getLogger(CassandraClusterSchemaMonitor.class);
+
+    private final AtomicReference<String> currSchemaText = new AtomicReference<>("");
+    private final AtomicReference<Set<CqlTable>> cdcTables = new AtomicReference<>(Collections.emptySet());
+    private final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache = new ConcurrentHashMap<>();
+    private final CdcDatabaseAccessor databaseAccessor;
+    private final CopyOnWriteArrayList<Runnable> schemaChangeListeners = new CopyOnWriteArrayList<>();
+    private final SidecarConfiguration sidecarConfiguration;
+    private final InstanceMetadataFetcher instanceFetcher;
+    private final CassandraBridgeFactory cassandraBridgeFactory;
+
+    public CassandraClusterSchemaMonitor(InstanceMetadataFetcher instanceFetcher,
+                                         CdcDatabaseAccessor databaseAccessor,
+                                         SidecarConfiguration sidecarConfiguration,
+                                         CassandraBridgeFactory cassandraBridgeFactory)
+    {
+
+        this.instanceFetcher = instanceFetcher;
+        this.databaseAccessor = databaseAccessor;
+        this.sidecarConfiguration = sidecarConfiguration;
+        this.cassandraBridgeFactory = cassandraBridgeFactory;
+    }
+
+    public void addSchemaChangeListener(Runnable listener)
+    {
+        schemaChangeListeners.add(listener);
+    }
+
+    public void refresh()
+    {
+        NodeSettings nodeSettings = instanceFetcher.callOnFirstAvailableInstance(instance-> instance.delegate().nodeSettings());
+        CassandraBridge cassandraBridge = cassandraBridgeFactory.get(nodeSettings.releaseVersion());
+        CdcBridge cdcBridge = CdcBridgeFactory.getCdcBridge(cassandraBridge);
+
+        try
+        {
+            LOGGER.debug("Checking for schema changes...");
+            String fullSchemaText = databaseAccessor.fullSchema();
+            if (!fullSchemaText.equals(currSchemaText.get()))
+            {
+                LOGGER.info("Schema change detected, refreshing CDC tables");
+                currSchemaText.set(fullSchemaText);
+                Set<CqlTable> updatedCdcTables = buildCdcTables(fullSchemaText, databaseAccessor, tableIdCache, instanceFetcher, cassandraBridge);
+                LOGGER.info("Cdc enabled tables tables='{}'", 
+                            updatedCdcTables.stream()
+                                            .map(m -> String.format("%s.%s", m.keyspace(), m.table()))
+                                            .collect(Collectors.joining(",")));
+                cdcTables.set(updatedCdcTables);
+
+                cdcBridge.updateCdcSchema(updatedCdcTables, getPartitioner(nodeSettings),
+                                          ((keyspace, table) -> tableIdCache.get(TableIdentifier.of(keyspace, table))));
+                schemaChangeListeners.forEach(Runnable::run);
+            }
+        }
+        catch (IllegalStateException exception)
+        {
+            LOGGER.warn("There was a problem refreshing the schema. Database Accessor may not be ready", exception);
+            throw exception;
+        }
+        catch (Throwable t)
+        {
+            LOGGER.error("Unexpected error while refreshing the schema", t);
+            throw t;
+        }
+    }
+
+    private Partitioner getPartitioner(NodeSettings nodeSettings)
+    {
+        if (nodeSettings.partitioner().contains("."))
+        {
+            String[] splitPartitionerName = nodeSettings.partitioner().split("\\.");
+            return Partitioner.valueOf(splitPartitionerName[splitPartitionerName.length - 1]);
+        }
+        return Partitioner.valueOf(nodeSettings.partitioner());
+    }
+
+    @Override
+    public DurationSpec delay()
+    {
+        return sidecarConfiguration.serviceConfiguration().cdcConfiguration().tableSchemaRefreshTime();
+    }
+
+    @Override
+    public void execute(Promise<Void> promise)
+    {
+        try
+        {
+            refresh();
+            promise.tryComplete();
+        }
+        catch (Throwable t)
+        {
+            promise.fail(t);
+        }
+    }
+
+    @Override
+    public ScheduleDecision scheduleDecision()
+    {
+        if (sidecarConfiguration.serviceConfiguration().schemaKeyspaceConfiguration().isEnabled() &&
+            sidecarConfiguration.serviceConfiguration().cdcConfiguration().isEnabled())
+        {
+            return ScheduleDecision.EXECUTE;
+        }
+        return ScheduleDecision.SKIP;
+    }
+
+    @VisibleForTesting
+    static Set<CqlTable> buildCdcTables(CdcDatabaseAccessor cdcDatabaseAccessor,
+                                        ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
+                                        @NotNull InstanceMetadataFetcher instanceFetcher,
+                                        @NotNull final CassandraBridge cassandraBridge)
+    {
+        return buildCdcTables(cdcDatabaseAccessor.fullSchema(),
+                              cdcDatabaseAccessor.partitioner(),
+                              tableIdCache,
+                              cdcDatabaseAccessor::getTableId,
+                              instanceFetcher,
+                              cassandraBridge);
+    }
+
+    private static Set<CqlTable> buildCdcTables(@NotNull String fullSchema,
+                                                @NotNull CdcDatabaseAccessor cdcDatabaseAccessor,
+                                                @NotNull ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
+                                                @NotNull InstanceMetadataFetcher instanceFetcher,
+                                                @NotNull final CassandraBridge cassandraBridge)
+    {
+        return buildCdcTables(fullSchema,
+                              cdcDatabaseAccessor.partitioner(),
+                              tableIdCache,
+                              cdcDatabaseAccessor::getTableId,
+                              instanceFetcher,
+                              cassandraBridge);
+    }
+
+    private static Set<CqlTable> buildCdcTables(@NotNull final String fullSchema,
+                                                @NotNull final Partitioner partitioner,
+                                                @NotNull final ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
+                                                @NotNull final Function<TableIdentifier, UUID> tableIdLoaderFunction,
+                                                @NotNull final InstanceMetadataFetcher instanceFetcher,
+                                                @NotNull final CassandraBridge cassandraBridge)

Review Comment:
   we can omit final, and instanceFetcher is no longer needed
   ```suggestion
       private static Set<CqlTable> buildCdcTables(@NotNull String fullSchema,
                                                   @NotNull Partitioner partitioner,
                                                   @NotNull ConcurrentHashMap<TableIdentifier, UUID> tableIdCache,
                                                   @NotNull Function<TableIdentifier, UUID> tableIdLoaderFunction,
                                                   @NotNull CassandraBridge cassandraBridge)
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org