he realized that his pen had been lying on the desk the entire time.

After John had searched for almost thirty minutes, he realized that his pen had been lying on the desk the entire time.

had been lying - is an error according to my book, so it should be: has been lying, because it still lasts?

on the other hand, after: realized (past tense), we should change : has been lying to :had been lying,

Thank You very much.

No, I don’t see that at all. If ‘had searched’ is used, then the most natural choice is ‘was lying’, since that is the later of the two past events.

Which the two past events do you mean Sir?: had searched and realized?

You must use your common sense as a native speaker does: which happened earlier, the searching or the lying?

I think I may have misunderstood your question. Let us try again:

After John had searched for almost thirty minutes, he realized that his pen had been lying on the desk the entire time.

had been lying - is an error according to my book, so it should be: has been lying, because it still lasts?– No. Since ‘realized’ is past tense and ‘lying’ precedes realization, the present perfect is inappropriate. However, since the order of events is logically clear, '‘had been lying’ is unnecessary; ‘was lying’ will serve.

So, did Sir mean two past events: realized and lying, or searching and lying?
So it takes place the following change:
,…he realizes that his pen is lying on the desk the entire time. to:

,…he realized that his pen was lying on the desk the entire time.???

Hey if you cannot imagine what sentence comes afterwards let me fill the gap. “IN BLINDING RAGE, John smashed his pen to pieces.”

So it takes place the following change:
,…he realizes that his pen is lying on the desk the entire time. to:
,…he realized that his pen was lying on the desk the entire time.

Yes.