'Drools infinite loop

I am new to Drools. Can someone tell why this rule is running into infinite loop despite not clause ?

declare InvalidPersonalInfoRequest
    request: PersonalInfo
    msg: String
end

rule "validate first name"
  dialect "java"
  when
    $r: PersonalInfo( firstName == null || firstName == '')
    not ( InvalidPersonalInfoRequest( this.request == $r) )
  then
    String msg = "invalid  name";
    System.out.println( msg );
    insertLogical( new InvalidPersonalInfoRequest($r, msg) );
end


Solution 1:[1]

It's because you're using insertLogical instead of insert.

From the Drools documentation:

The Drools engine inserts facts using either stated or logical insertions:

  • Stated insertions: Defined with insert(). After stated insertions, facts are generally retracted explicitly. (The term insertion, when used generically, refers to stated insertion.)

  • Logical insertions: Defined with insertLogical(). After logical insertions, the facts that were inserted are automatically retracted when the conditions in the rules that inserted the facts are no longer true. The facts are retracted when no condition supports the logical insertion. A fact that is logically inserted is considered to be justified by the Drools engine.

When you use insertLogical, the inserted object is removed from memory when the triggering condition stops being true. Since your insertion immediately negates the condition, it's immediately removed from memory.

Swap over to insert to work as you expect.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roddy of the Frozen Peas