Copilot commented on code in PR #166: URL: https://github.com/apache/hbase-connectors/pull/166#discussion_r4047675666
########## spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseBatchWrite.scala: ########## @@ -0,0 +1,108 @@ +/* + * 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.hadoop.hbase.spark.datasources + +import org.apache.hadoop.fs.Path +import org.apache.hadoop.hbase.{HBaseConfiguration, TableName} +import org.apache.hadoop.hbase.client.{ColumnFamilyDescriptorBuilder, TableDescriptorBuilder} +import org.apache.hadoop.hbase.spark.{HBaseConnectionCache, Logging} +import org.apache.hadoop.hbase.util.Bytes +import org.apache.spark.sql.SparkSession +import org.apache.spark.sql.connector.write.{BatchWrite, DataWriterFactory, PhysicalWriteInfo, + WriterCommitMessage} +import org.apache.spark.sql.types.StructType +import org.apache.yetus.audience.InterfaceAudience + +/** + * This is a new class in the spark4 module. Implements BatchWrite for the DS V2 write path. + * Runs on the driver. Optionally creates the HBase table (when the "newtable" option is set), + * then produces an HBaseDataWriterFactory that is serialized to executors. + * + * In the spark 3 DS V1 model, table creation was in HBaseRelation.createTable() and the write + * was driven by InsertableRelation.insert() using saveAsHadoopDataset with TableOutputFormat. + * + * @param schema + * @param properties + */ [email protected] +class HBaseBatchWrite(schema: StructType, properties: Map[String, String]) + extends BatchWrite + with Logging { + + private val catalog = HBaseTableCatalog(properties) + + createTableIfNeeded() + + override def createBatchWriterFactory(info: PhysicalWriteInfo): DataWriterFactory = { + val hadoopConf = SparkSession.active.sparkContext.hadoopConfiguration + val hbaseConf = HBaseConfiguration.create(hadoopConf) + properties.get(HBaseSparkConf.HBASE_CONFIG_LOCATION) + .foreach(_.split(",").foreach(r => hbaseConf.addResource(new Path(r)))) + val wrappedConf = new SerializableConfiguration(hbaseConf) + + new HBaseDataWriterFactory(schema, properties, catalog, wrappedConf) + } + + override def useCommitCoordinator(): Boolean = false + + override def commit(messages: Array[WriterCommitMessage]): Unit = {} + + override def abort(messages: Array[WriterCommitMessage]): Unit = {} Review Comment: Task writers send puts to HBase before the batch commit callback, but both `commit` and `abort` are no-ops. If a later task fails, or a task fails after a flush, Spark can report a failed write while already-written rows remain in HBase; retries can also leave partial output. This needs a staging/cleanup or explicitly idempotent write strategy before exposing this as a V2 batch sink. ########## spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseDataWriter.scala: ########## @@ -0,0 +1,146 @@ +/* + * 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.hadoop.hbase.spark.datasources + +import java.util.ArrayList +import org.apache.hadoop.hbase.TableName +import org.apache.hadoop.hbase.client.{Put, Table} +import org.apache.hadoop.hbase.spark.{HBaseConnectionCache, Logging, SmartConnection} +import org.apache.hadoop.hbase.util.Bytes +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.connector.write.{DataWriter, WriterCommitMessage} +import org.apache.spark.sql.types._ +import org.apache.yetus.audience.InterfaceAudience + +/** + * This is a new class in the spark4 module. Implements DataWriter[InternalRow] for the DS V2 write path. + * Each instance handles one Spark partition on an executor. Converts InternalRow to HBase Put operations + * and writes them via BufferedMutator for efficient client-side batching. + * + * In the spark 3 DS V1 model, this logic was inside DefaultSource.insert() which used + * rdd.map(convertToPut).saveAsHadoopDataset() with the old mapred TableOutputFormat. + * + * @param schema + * @param properties + * @param catalog + * @param wrappedConf + */ [email protected] +class HBaseDataWriter( + schema: StructType, + properties: Map[String, String], + catalog: HBaseTableCatalog, + wrappedConf: SerializableConfiguration) + extends DataWriter[InternalRow] + with Logging { + + private val conf = wrappedConf.value + private val connection: SmartConnection = HBaseConnectionCache.getConnection(conf) + private val tableName = TableName.valueOf(s"${catalog.namespace}:${catalog.name}") + private val table: Table = connection.getTable(tableName) + + private val timestamp = properties.get(HBaseSparkConf.TIMESTAMP).map(_.toLong) + + private val rkFields = catalog.getRowKey + private val rkIdxedFields = rkFields.map { f => + (schema.fieldIndex(f.colName), f) + } + private val colIdxedFields = schema.fieldNames + .filter(name => !rkFields.map(_.colName).contains(name)) + .map(name => (schema.fieldIndex(name), catalog.sMap.getField(name))) + + private val batchSize = properties + .get(HBaseSparkConf.BULKGET_SIZE) + .map(_.toInt) + .getOrElse(HBaseSparkConf.DEFAULT_BULKGET_SIZE) + + private val putBuffer = new ArrayList[Put](batchSize) + + override def write(record: InternalRow): Unit = { + val rowKeyBytes = buildRowKey(record) + val put = timestamp.fold(new Put(rowKeyBytes))(new Put(rowKeyBytes, _)) + + colIdxedFields.foreach { case (idx, field) => + if (!record.isNullAt(idx)) { + val valueBytes = getValueBytes(record, idx, field) + put.addColumn(field.cfBytes, field.colBytes, valueBytes) + } + } + + putBuffer.add(put) + if (putBuffer.size() >= batchSize) { + flushPuts() + } + } + + override def commit(): WriterCommitMessage = { + flushPuts() + table.close() + connection.close() + HBaseWriterCommitMessage() + } + + override def abort(): Unit = { + table.close() + connection.close() + } + + override def close(): Unit = {} + + private def flushPuts(): Unit = { + if (!putBuffer.isEmpty) { + table.put(putBuffer) + putBuffer.clear() + } + } + + private def buildRowKey(record: InternalRow): Array[Byte] = { + val rowBytes = rkIdxedFields.map { case (idx, field) => + getValueBytes(record, idx, field) + } Review Comment: This concatenates composite row-key components without the delimiter that the reader expects for variable-length string fields (see `HBasePartitionReader.parseRowKey`). A catalog such as `key1:key2` with an unbounded string `key1` cannot be read back reliably after this write; the first component consumes the remaining bytes or a zero byte inside the next component. Add the delimiter between non-final variable-length string components, matching the read-side encoding. ########## spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseDataWriter.scala: ########## @@ -0,0 +1,146 @@ +/* + * 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.hadoop.hbase.spark.datasources + +import java.util.ArrayList +import org.apache.hadoop.hbase.TableName +import org.apache.hadoop.hbase.client.{Put, Table} +import org.apache.hadoop.hbase.spark.{HBaseConnectionCache, Logging, SmartConnection} +import org.apache.hadoop.hbase.util.Bytes +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.connector.write.{DataWriter, WriterCommitMessage} +import org.apache.spark.sql.types._ +import org.apache.yetus.audience.InterfaceAudience + +/** + * This is a new class in the spark4 module. Implements DataWriter[InternalRow] for the DS V2 write path. + * Each instance handles one Spark partition on an executor. Converts InternalRow to HBase Put operations + * and writes them via BufferedMutator for efficient client-side batching. + * + * In the spark 3 DS V1 model, this logic was inside DefaultSource.insert() which used + * rdd.map(convertToPut).saveAsHadoopDataset() with the old mapred TableOutputFormat. + * + * @param schema + * @param properties + * @param catalog + * @param wrappedConf + */ [email protected] +class HBaseDataWriter( + schema: StructType, + properties: Map[String, String], + catalog: HBaseTableCatalog, + wrappedConf: SerializableConfiguration) + extends DataWriter[InternalRow] + with Logging { + + private val conf = wrappedConf.value + private val connection: SmartConnection = HBaseConnectionCache.getConnection(conf) + private val tableName = TableName.valueOf(s"${catalog.namespace}:${catalog.name}") + private val table: Table = connection.getTable(tableName) + + private val timestamp = properties.get(HBaseSparkConf.TIMESTAMP).map(_.toLong) + + private val rkFields = catalog.getRowKey + private val rkIdxedFields = rkFields.map { f => + (schema.fieldIndex(f.colName), f) + } + private val colIdxedFields = schema.fieldNames + .filter(name => !rkFields.map(_.colName).contains(name)) + .map(name => (schema.fieldIndex(name), catalog.sMap.getField(name))) + + private val batchSize = properties + .get(HBaseSparkConf.BULKGET_SIZE) + .map(_.toInt) + .getOrElse(HBaseSparkConf.DEFAULT_BULKGET_SIZE) + + private val putBuffer = new ArrayList[Put](batchSize) + + override def write(record: InternalRow): Unit = { + val rowKeyBytes = buildRowKey(record) + val put = timestamp.fold(new Put(rowKeyBytes))(new Put(rowKeyBytes, _)) + + colIdxedFields.foreach { case (idx, field) => + if (!record.isNullAt(idx)) { + val valueBytes = getValueBytes(record, idx, field) + put.addColumn(field.cfBytes, field.colBytes, valueBytes) + } + } + + putBuffer.add(put) + if (putBuffer.size() >= batchSize) { + flushPuts() + } + } + + override def commit(): WriterCommitMessage = { + flushPuts() + table.close() + connection.close() + HBaseWriterCommitMessage() + } + + override def abort(): Unit = { + table.close() + connection.close() + } + + override def close(): Unit = {} + + private def flushPuts(): Unit = { + if (!putBuffer.isEmpty) { + table.put(putBuffer) + putBuffer.clear() + } + } + + private def buildRowKey(record: InternalRow): Array[Byte] = { + val rowBytes = rkIdxedFields.map { case (idx, field) => + getValueBytes(record, idx, field) + } + val totalLen = rowBytes.foldLeft(0)(_ + _.length) + val result = new Array[Byte](totalLen) + var offset = 0 + rowBytes.foreach { bytes => + System.arraycopy(bytes, 0, result, offset, bytes.length) + offset += bytes.length + } + result + } + + private val MILLIS_PER_DAY = 86400000L + + private def getValueBytes(row: InternalRow, idx: Int, field: Field): Array[Byte] = { + field.dt match { + case BooleanType => Bytes.toBytes(row.getBoolean(idx)) Review Comment: This conversion path never handles catalog fields with an Avro schema. Such fields are represented by a `StructType`, so they fall through to the unsupported-type exception, whereas the existing V1 writer serializes them with `Utils.toBytes`; any V2 write containing an Avro column will therefore fail. ########## spark4/hbase-spark4/src/main/scala/org/apache/hadoop/hbase/spark/datasources/HBaseDataWriterFactory.scala: ########## @@ -0,0 +1,49 @@ +/* + * 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.hadoop.hbase.spark.datasources + +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.connector.write.{DataWriter, DataWriterFactory} +import org.apache.spark.sql.types.StructType +import org.apache.yetus.audience.InterfaceAudience + +/** + * This is a new class in the spark4 module. Implements DataWriterFactory for the DS V2 write path. + * Serialized to executors. Creates one HBaseDataWriter per Spark partition. + * + * In the spark 3 DS V1 model, there was no factory. The RDD.saveAsHadoopDataset() call used + * TableOutputFormat to write Puts directly. + * + * @param schema + * @param properties + * @param catalog + * @param wrappedConf + */ [email protected] +class HBaseDataWriterFactory( + schema: StructType, + properties: Map[String, String], + catalog: HBaseTableCatalog, + wrappedConf: SerializableConfiguration) + extends DataWriterFactory + with Serializable { + + override def createWriter(partitionId: Int, taskId: Long): DataWriter[InternalRow] = { Review Comment: Spark 4's `DataWriterFactory` contract requires `createWriter(partitionId, taskId, epochId)`. This two-argument override does not implement the interface, so the module will fail to compile (or the factory remains abstract). Add the epoch argument, even though batch writes do not use 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
