def batch_insert_ground_truth(
        self, ground_truths: List[groundtruth_schema.GroundTruth]
    ) -> List[types_schema.GroundTruthID]:
        """See [DB.batch_insert_ground_truth][trulens.core.database.base.DB.batch_insert_ground_truth]."""
        with self.session.begin() as session:
            ground_truth_ids = [gt.ground_truth_id for gt in ground_truths]

            # Fetch existing GroundTruth records that match these ids in one query
            existing_ground_truths = (
                session.query(self.orm.GroundTruth)
                .filter(
                    self.orm.GroundTruth.ground_truth_id.in_(ground_truth_ids)
                )
                .all()
            )

            existing_ground_truth_dict = {
                gt.ground_truth_id: gt for gt in existing_ground_truths
            }

            ground_truths_to_insert = []
            for ground_truth in ground_truths:
                if ground_truth.ground_truth_id in existing_ground_truth_dict:
                    existing_record = existing_ground_truth_dict[
                        ground_truth.ground_truth_id
                    ]
                    # Update the existing record for idempotency
                    existing_record.ground_truth_json = (
                        ground_truth.model_dump_json()
                    )
                else:
                    new_ground_truth = self.orm.GroundTruth.parse(
                        ground_truth, redact_keys=self.redact_keys
                    )
                    ground_truths_to_insert.append(new_ground_truth)

            session.add_all(ground_truths_to_insert)
            return [gt.ground_truth_id for gt in ground_truths]
See [DB.batch_insert_ground_truth][trulens.core.database.base.DB.batch_insert_ground_truth].
src/core/trulens/core/database/sqlalchemy.py