[RLM_ERR_WRONG_ TRANSACTION_STATE]: Must be in a write transaction

I am Simply Maintaing Search History

Class

class SearchHistoryRo : RealmObject {
	
	@PrimaryKey
	var _id: ObjectId = BsonObjectId()
	
	@Index
	var historyId: String = ""
	var historyOf: String = ""
	var historyText: String = ""
	var userId: String = ""
	var timestamp: Long = 0L
	
	constructor()
	constructor(_id: ObjectId, historyId: String, historyOf: String, historyText: String, userId: String, timestamp: Long) {
		this._id = _id
		this.historyId = historyId
		this.historyOf = historyOf
		this.historyText = historyText
		this.userId = userId
		this.timestamp = timestamp
	}
	
	constructor(historyId: String, historyOf: String, historyText: String, userId: String, timestamp: Long) {
		this.historyId = historyId
		this.historyOf = historyOf
		this.historyText = historyText
		this.userId = userId
		this.timestamp = timestamp
	}
}

My Service Implementation

override suspend fun upsertSearchHistory(searchHistoryRo: SearchHistoryRo) {
	realm.write { 
		val history = query(SearchHistoryRo::class, query = "historyId == $0", searchHistoryRo.historyId).find()
		if (history.isEmpty()) copyToRealm(instance = searchHistoryRo, updatePolicy = UpdatePolicy.ALL)
		else searchHistoryRo.apply { 
			val historyToUpsert = SearchHistoryRo(
				_id = history.first()._id,
				historyId = historyId,
				historyOf = historyOf,
				historyText = historyText,
				userId = userId,
				timestamp = timestamp
			)
			copyToRealm(instance = historyToUpsert, updatePolicy = UpdatePolicy.ALL)
		}
	}
}

Calling this causes “upsertSearchHistory Exception: [RLM_ERR_WRONG_TRANSACTION_STATE]: Must be in a write transaction” I cannot see why and how to fix it!