Inverting a floored ratio
A caller who needs a recipient to end up with exactly N has to invert the fee function. The obvious formula is off by one for most N, and everyone who gets it wrong either overpays or reverts.

The fee itself is the easy part. Floor of the amount times the rate, capped, withheld. Flooring rounds in the sender's favour, and the sender is the party who did not choose to pay a fee. That is one line and there is nothing to argue about.
Going backwards is the hard part. A payroll contract needs an employee to receive exactly their salary. A router needs the pool to receive exactly the number it quoted against. Both have to solve for the input that produces a given output, and the formula everyone reaches for first does not work.
Where the obvious formula breaks
Write b for the rate, D for the denominator and k for D minus b. What the recipient receives is the amount minus the floored fee, which is the ceiling of the amount times k over D. Dividing the target by that ratio and rounding is off by one for most targets, because you are inverting a ceiling with a floor.
Done properly, the condition that the net equals the target holds exactly on a half-open interval, and the answer is the smallest integer inside it.
// net(x) = x - floor(x*b/D) = ceil(x*k/D)
//
// net(x) == out holds for (out-1)*D/k < x <= out*D/k
// so the smallest such integer is:
uint256 amountIn = Math.mulDiv(out - 1, D, k) + 1;And then the cap moves the answer
Where the absolute cap binds, the fee no longer depends on the amount, so the net is simply the amount minus the cap and the answer is the target plus the cap. Which branch applies is decided by evaluating the fee at the uncapped candidate. Because the net never gains more than one per step, the two branches cannot both miss, and they agree exactly on the boundary where the uncapped fee equals the cap.
The intermediate product is carried in five hundred and twelve bits, so the only inputs that revert are the ones whose answer genuinely does not fit in a word — not the ones where a multiplication overflowed on the way to an answer that would have fit.
Why this belongs inside the token
None of the above is difficult. It is fiddly, it is easy to get subtly wrong, and being subtly wrong costs a rounding error per transfer in one direction or a revert in the other. Solved once inside the token, it is a single call. Left to integrators, it is the same derivation performed independently by everyone who touches the token, with the ones who got it wrong finding out in production.
The suite fuzzes both directions. For any amount, the computed fee equals what left the sender minus what reached the recipient in the same transaction. And the exact-output input is not merely sufficient — it is minimal, which is the part a hand-rolled inversion tends to miss.