Expose and improve key inference.

Update logic so that the longest name component is always preferred.