# Automatic Realtime Cycle Detection of function calls

I am running into a wall mentally when trying to think of a way to solve this problem. At my work we process customer data through some complex reasoning logic. Sometimes this logic will cause infinite looping. We actually know how to just remove some of the logic that will cause this but for political reasons we aren't allowed to touch the logic.... sigh

Anyway, I decided to open my big mouth and suggest there must be some way to detect cycles in the logic calls, so here I am tasked with figuring out a way to detect cycles in the logic and then move past the loop if one happens.

I have come up with a rough plan but I wanted to see if any of the smart people here had some input.

To begin, I already have access to every function call and its inputs via our logging so my plan was as follows:

1. find a way to hash the function call/inputs combinations
2. map the above combos to a call ID
3. keep a list of all calls made so far
4. use the map from 2 and the list from 3 to create a potentially cyclical representation of the calls
5. Run Brent's cycle detection algorithm on this list to see if a cycle has happened.

I feel like this is fairly convoluted. I was wondering if others had some input.

The programming language for this is Java, and the logic is in Drools. With Event listeners I can see exactly what rules activate and the facts that activate them. Sometimes no rules actually fire just ruleflow groups get activated. My thinking was that by keeping a list of all pervious activations I can rebuild the call order into something akin to a linked list and apply some cycle detection algorithm. Then after every activation I need to check if this activation has started a loop.

• What language? Also keep in mind that some cycles might be valid recursive calls. The key is determining if there is an end condition that eventually prevents future recursion, i.e. stopping an infinite cycle.
– user22815
Commented Jan 24, 2017 at 18:50
• Language is Java, the logic is in Drools. We have event listeners that capture all rules that fire and these have access to the facts that were associated with the rules firing Commented Jan 24, 2017 at 20:18
• Is there a reason you can't keep track of the stack depth and abort after it goes deep enough? Commented Jan 24, 2017 at 21:35
• @Doval do you mean the actual Java stack or the number of calls to rules? When a loop occurs, it usually occurs with some set of rules firing repeatedly without ever hitting a Java stack limit, in those cases we will just time out. But we want to be able to detect the loops before we time out since timing out can take a long time. Commented Jan 24, 2017 at 22:45
• This type of cycle detection or avoidance should be built into the rules environment. It has all the information needed to detect cycles internally. Commented Jan 26, 2017 at 5:52