The criteria by which a delayed subgoal is marked for execution or for further delay in flrdelay_support.P must be expanded. It is possible that the delayed subgoal has no variables aliased to head (in extract_triggers_and_execute/2, get_var_triggers/3), but thedelay condition might still be satisfied by further delay because of other delayed subgoals.
For instance,
q(?X,?R) :- wish(nonvar(?X))^(sum{?A|p(?A,?X)} =?L), ?R is ?L+1.
s(?X,?R) :- q(?X,?R), r(?X).
Here both sum{...} and is/2 are delayed (is/2 is delayed implicitly, by definition). According to the current delay criteria, ?R is ?L+1 won't be delayed past the first rule because ?L is not aliased to head. But since sum{...} is delayed, ?L can still be bound once ?X is bound in the second rule.
Anonymous
Once delay is fixed, aggregates should be delayed automatically on nonvat(?X) for every non-grouping, non-aggregate variable in the aggregate body. That is,
in the above,
q(?X,?R) :- sum{?A|p(?A,?X)} =?L, ?R is ?L+1.
s(?X,?R) :- q(?X,?R), r(?X).
should just work without explicit delay quantifiers.