Is there ever a situation where a lens that fits perfectly on a Canon 5d won't fit on a Canon 40d?
No, not unless the lens or one of the mounts is damaged (or out of spec) in some way. Both should have identical EF series lens mounts and anything that mounts on a 5D should mount on a 40D.
The reverse isn't true since the 40D will accept EF-S mount lenses but the 5D won't.
However all "L" lenses have the standard EF series mount and so will mount on any "in spec" EOS DSLR