In Saxon-SA, an expression of the form EXP/a/b/c[d='foo'], where EXP has type document-node(), may be rewritten by the optimizer as a call on the (XSLT) key() function: key('kk:nnnnn', 'foo', EXP).
This can cause a failure if the cardinality of EXP is anything other than exactly-one, for example if EXP returns an empty sequence or if it returns a sequence of document nodes. In the first case the symptom is a NullPointerException within the module net.sf.saxon.functions.KeyFn
A patch has been produced; it is in code that is Saxon-SA only (module OptimizerSA) and will be incorporated into any future maintenance release. Meanwhile the workaround is to rewrite the expression as
for $doc in EXP return $doc/a/b/c[d='foo']