If the engine has sludge in it to the point of needing to be replaced after only 2 years and 30K miles, I believe it is safe to assume it was never serviced. What kind of condition is the transmission in, has it ever been serviced? What about the brake fluid and engine coolant? Did it run hot and burn the oil to cause the sludge and the valve cover leak? Are the radiator, water pump and thermostat okay? Does it have any evidence of flood damage? Bottom-line, sludge build up in a 2017 with only 30K miles is not normal at all!
You may be fine with an engine replacement, you may not. The vehicle should have 2 years and 30K remaining on the factory bumper to bumper warranty. If you keep it, consider purchasing an extended warranty to cover you after the bumper to bumper expires until you pay it off -- I'd ask CarMax pay for the extended warranty to compensate you for you having to replace the engine...within 7 days of buying it. If they don't, I'd give it back to them and walk away. Then again, I wouldn't purchase a used vehicle unless it was factory CPO for fear of going through what your going through.