As Dinoguy said, this is properly a really hard problem. References are a really complicated feature, kind of using variables as internal counter as well, and being evaluated at a different time during parsing. This leads to many features of stock MediaWiki already to behave weird when used together with references – especially advanced syntax features offered by extensions.
What is properly happening here that the references are not populated at the (quite early) point during parsing when variables are evaluated in this logic. I do not know exactly what is happening, but trying to get the references at multiple points, at different parsing stages, is quite typical for problems related to references.
Hence, your references var is always empty for parser functions. On the other hand, variables not encapsulated into the template tree can properly evaluated properly.