the question needs to be rephrased. a plan fails the test, so $x due to deferrals needs to be returned. can't change that fact. but what you are really asking is "when calculating the amount of gains, due you treat the $x of deferrals as being first in or first out?" 1.401(k)-2(b)(2)(iv)(B) says "A plan may use any reasonable method for computing the income allocable to excess contributions... 1.401(k)-2(b)(2)(iv)© provides the safe harbor method for calculating gains, e.g. numerator = excess amt, denominator = (beg balance + total contributions)
I think, at least the software I am familiar with, an adjustment is made for other things like possible distributions taken during the year, which falls within the "any reasonable method"
would it be reasonable to say "It is only the last defer that caused the plan fail so it should only be gains on that paycheck", but that really isn't quite true as the plan is tested over the whole year.
so you have 2 HCEs, one deferred 10,000 on Jan 1 and the other deferred 10,000 on Dec 31. plan fails and refund is required, arguably it is not the first one HCE that caused the plan to fail only the second HCE and that at the moment he deferred, not before then - then how would you calculate gains on the first HCE.