In reply to niravshah:
Please use code tags making your code easier to read. I have added them for you.
Two problems with your code involving a user defined function.
Random variables used by functions have their values chosen before calling the function. Once the function gets called, the output return value becomes a state variable. The constraint solver does not try to repeatedly call the function with new random inputs and fails if the remaining constraints cannot be met.
The other problem is your function has no inputs; it accesses the array a which is outside the scope of the function. That might be considered a side-effect. However, making the array an input will not get around the first problem.
The built-in sum() method is considered an iterative constraint and gets unrolled into a single expression for the constraint solver.