Search in sources :

Example 31 with BetaMemory

use of org.drools.core.reteoo.BetaMemory in project drools by kiegroup.

the class LinkingTest method testNestedSubNetworkMasks.

@Test
public void testNestedSubNetworkMasks() throws Exception {
    String str = "";
    str += "package org.kie \n";
    str += "import " + A.class.getCanonicalName() + "\n";
    str += "import " + B.class.getCanonicalName() + "\n";
    str += "import " + C.class.getCanonicalName() + "\n";
    str += "import " + D.class.getCanonicalName() + "\n";
    str += "import " + E.class.getCanonicalName() + "\n";
    str += "import " + F.class.getCanonicalName() + "\n";
    str += "import " + G.class.getCanonicalName() + "\n";
    str += "global java.util.List list \n";
    str += "rule rule1 when \n";
    str += "   A() \n";
    str += "   B() \n";
    str += "   exists( C() and D() and exists( E() and F() ) ) \n";
    str += "   G() \n";
    str += "then \n";
    str += "end \n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    assertFalse(kbuilder.getErrors().toString(), kbuilder.hasErrors());
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    ObjectTypeNode node = getObjectTypeNode(kbase, A.class);
    InternalWorkingMemory wm = ((StatefulKnowledgeSessionImpl) kbase.newKieSession());
    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) node.getObjectSinkPropagator().getSinks()[0];
    JoinNode bNode = (JoinNode) liaNode.getSinkPropagator().getSinks()[0];
    ExistsNode exists1n = (ExistsNode) bNode.getSinkPropagator().getSinks()[1];
    JoinNode cNode = (JoinNode) bNode.getSinkPropagator().getSinks()[0];
    JoinNode dNode = (JoinNode) cNode.getSinkPropagator().getSinks()[0];
    ExistsNode exists2n = (ExistsNode) dNode.getSinkPropagator().getSinks()[1];
    JoinNode eNode = (JoinNode) dNode.getSinkPropagator().getSinks()[0];
    JoinNode fNode = (JoinNode) eNode.getSinkPropagator().getSinks()[0];
    RightInputAdapterNode riaNode2 = (RightInputAdapterNode) fNode.getSinkPropagator().getSinks()[0];
    RightInputAdapterNode riaNode1 = (RightInputAdapterNode) exists2n.getSinkPropagator().getSinks()[0];
    JoinNode gNode = (JoinNode) exists1n.getSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn = (RuleTerminalNode) gNode.getSinkPropagator().getSinks()[0];
    wm.insert(new A());
    wm.insert(new B());
    wm.insert(new C());
    wm.insert(new D());
    wm.insert(new G());
    wm.flushPropagations();
    LiaNodeMemory liaMem = (LiaNodeMemory) wm.getNodeMemory(liaNode);
    BetaMemory bMem = (BetaMemory) wm.getNodeMemory(bNode);
    BetaMemory exists1Mem = (BetaMemory) wm.getNodeMemory(exists1n);
    BetaMemory cMem = (BetaMemory) wm.getNodeMemory(cNode);
    BetaMemory dMem = (BetaMemory) wm.getNodeMemory(dNode);
    BetaMemory exists2Mem = (BetaMemory) wm.getNodeMemory(exists2n);
    BetaMemory eMem = (BetaMemory) wm.getNodeMemory(eNode);
    BetaMemory fMem = (BetaMemory) wm.getNodeMemory(fNode);
    BetaMemory gMem = (BetaMemory) wm.getNodeMemory(gNode);
    RightInputAdapterNode.RiaNodeMemory riaMem1 = (RightInputAdapterNode.RiaNodeMemory) wm.getNodeMemory(riaNode1);
    RightInputAdapterNode.RiaNodeMemory riaMem2 = (RightInputAdapterNode.RiaNodeMemory) wm.getNodeMemory(riaNode2);
    PathMemory rs = (PathMemory) wm.getNodeMemory(rtn);
    // E and F are not inserted yet, so rule is unlinked
    assertFalse(rs.isRuleLinked());
    // ---
    // assert a and b in same segment
    assertSame(liaMem.getSegmentMemory(), bMem.getSegmentMemory());
    // exists1 and b not in same segment
    assertNotSame(bMem.getSegmentMemory(), exists1Mem.getSegmentMemory());
    // exists1 and b are in same segment
    assertSame(exists1Mem.getSegmentMemory(), gMem.getSegmentMemory());
    // check segment masks
    assertEquals(2, rs.getSegmentMemories().length);
    assertEquals(3, rs.getAllLinkedMaskTest());
    assertEquals(1, rs.getLinkedSegmentMask());
    assertEquals(3, liaMem.getSegmentMemory().getAllLinkedMaskTest());
    assertEquals(1, liaMem.getNodePosMaskBit());
    assertEquals(2, bMem.getNodePosMaskBit());
    assertEquals(3, exists1Mem.getSegmentMemory().getAllLinkedMaskTest());
    assertEquals(1, exists1Mem.getNodePosMaskBit());
    assertEquals(2, gMem.getNodePosMaskBit());
    // assert c, d are in the same segment, and that this is the only segment in ria1 memory
    assertSame(dMem.getSegmentMemory(), cMem.getSegmentMemory());
    // assert d and exists are not in the same segment
    assertNotSame(exists2Mem.getSegmentMemory(), dMem.getSegmentMemory());
    assertEquals(3, riaMem1.getRiaPathMemory().getSegmentMemories().length);
    // only needs to know about segments in the subnetwork
    assertEquals(null, riaMem1.getRiaPathMemory().getSegmentMemories()[0]);
    assertEquals(dMem.getSegmentMemory(), riaMem1.getRiaPathMemory().getSegmentMemories()[1]);
    assertEquals(1, dMem.getSegmentMemory().getPathMemories().size());
    assertSame(riaMem1.getRiaPathMemory(), cMem.getSegmentMemory().getPathMemories().get(0));
    assertEquals(3, cMem.getSegmentMemory().getAllLinkedMaskTest());
    // E and F is not yet inserted, so bit is not set
    assertEquals(3, cMem.getSegmentMemory().getLinkedNodeMask());
    assertEquals(1, cMem.getNodePosMaskBit());
    assertEquals(2, dMem.getNodePosMaskBit());
    assertEquals(0, exists2Mem.getNodePosMaskBit());
    // insert to lazy initialize exists2Mem segment
    FactHandle fhE1 = wm.insert(new E());
    FactHandle fhF1 = wm.insert(new F());
    wm.flushPropagations();
    assertEquals(1, exists2Mem.getNodePosMaskBit());
    // only cares that the segment for c, E and exists1 are set, ignores the outer first segment
    assertEquals(6, riaMem1.getRiaPathMemory().getAllLinkedMaskTest());
    // E and F are inerted, so 6
    assertEquals(6, riaMem1.getRiaPathMemory().getLinkedSegmentMask());
    wm.delete(fhE1);
    wm.delete(fhF1);
    wm.flushPropagations();
    // E deleted
    assertEquals(2, riaMem1.getRiaPathMemory().getLinkedSegmentMask());
    // assert e, f are in the same segment, and that this is the only segment in ria2 memory
    // subnetworks are recursively created, so segment already exists
    assertNotNull(null, eMem.getSegmentMemory());
    assertSame(fMem.getSegmentMemory(), eMem.getSegmentMemory());
    assertEquals(3, riaMem2.getRiaPathMemory().getSegmentMemories().length);
    // only needs to know about segments in the subnetwork
    assertEquals(null, riaMem2.getRiaPathMemory().getSegmentMemories()[0]);
    // only needs to know about segments in the subnetwork
    assertEquals(null, riaMem2.getRiaPathMemory().getSegmentMemories()[1]);
    assertEquals(fMem.getSegmentMemory(), riaMem2.getRiaPathMemory().getSegmentMemories()[2]);
    assertSame(riaMem2.getRiaPathMemory(), eMem.getSegmentMemory().getPathMemories().get(0));
    assertEquals(3, eMem.getSegmentMemory().getAllLinkedMaskTest());
    assertEquals(0, eMem.getSegmentMemory().getLinkedNodeMask());
    // only cares that the segment for e and f set, ignores the outer two segment
    assertEquals(4, riaMem2.getRiaPathMemory().getAllLinkedMaskTest());
    // E and F is not yet inserted, so bit is not set
    assertEquals(0, riaMem2.getRiaPathMemory().getLinkedSegmentMask());
    fhE1 = wm.insert(new E());
    wm.insert(new F());
    wm.flushPropagations();
    // E and F are now inserted yet, so rule is linked
    assertTrue(rs.isRuleLinked());
    assertEquals(3, rs.getAllLinkedMaskTest());
    assertEquals(3, rs.getLinkedSegmentMask());
    // retest bits
    assertEquals(3, cMem.getSegmentMemory().getAllLinkedMaskTest());
    assertEquals(3, cMem.getSegmentMemory().getLinkedNodeMask());
    assertEquals(6, riaMem1.getRiaPathMemory().getAllLinkedMaskTest());
    assertEquals(6, riaMem1.getRiaPathMemory().getLinkedSegmentMask());
    assertEquals(3, eMem.getSegmentMemory().getAllLinkedMaskTest());
    assertEquals(3, eMem.getSegmentMemory().getLinkedNodeMask());
    assertEquals(4, riaMem2.getRiaPathMemory().getAllLinkedMaskTest());
    assertEquals(4, riaMem2.getRiaPathMemory().getLinkedSegmentMask());
    wm.delete(fhE1);
    wm.flushPropagations();
    // retest bits
    assertFalse(rs.isRuleLinked());
    assertEquals(3, cMem.getSegmentMemory().getLinkedNodeMask());
    assertEquals(2, riaMem1.getRiaPathMemory().getLinkedSegmentMask());
    assertEquals(2, eMem.getSegmentMemory().getLinkedNodeMask());
    assertEquals(0, riaMem2.getRiaPathMemory().getLinkedSegmentMask());
}
Also used : FactHandle(org.kie.api.runtime.rule.FactHandle) JoinNode(org.drools.core.reteoo.JoinNode) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) BetaMemory(org.drools.core.reteoo.BetaMemory) ExistsNode(org.drools.core.reteoo.ExistsNode) LiaNodeMemory(org.drools.core.reteoo.LeftInputAdapterNode.LiaNodeMemory) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) RightInputAdapterNode(org.drools.core.reteoo.RightInputAdapterNode) LeftInputAdapterNode(org.drools.core.reteoo.LeftInputAdapterNode) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) PathMemory(org.drools.core.reteoo.PathMemory) Test(org.junit.Test)

Example 32 with BetaMemory

use of org.drools.core.reteoo.BetaMemory in project drools by kiegroup.

the class BackwardChainingTest method testSubNetworksAndQueries.

@Test(timeout = 10000)
public void testSubNetworksAndQueries() throws Exception {
    String str = "" + "package org.drools.compiler.test  \n" + "import java.util.List\n" + "import java.util.ArrayList\n" + "import java.util.Map\n" + "import java.util.HashMap\n" + "global List list\n" + "dialect \"mvel\"\n" + "\n" + "declare Location\n" + "    thing : String \n" + "    location : String \n" + "end" + "\n" + "declare Edible\n" + "   thing : String\n" + "end" + "\n" + "query whereFood( String x, String y ) \n" + "    Location(x, y;) Edible(x;) \n" + "end\n" + "\n" + "query look(String place, List food ) \n" + "    $s : String() // just here to give a OTN lookup point\n" + "    food := List() from accumulate( whereFood(thing, place;) ," + "                                    collectList( thing ) )\n" + "    exists( whereFood(thing, place;) )\n" + "    not( whereFood(thing, place;) and\n " + "         String( this == $s ) from thing )\n" + "end\n" + "\n" + "rule init when\n" + "then\n" + "        \n" + "        insert( new Location(\"apple\", \"kitchen\") );\n" + "        insert( new Location(\"crackers\", \"kitchen\") );\n" + "        insert( new Location(\"broccoli\", \"kitchen\") );\n" + "        insert( new Location(\"computer\", \"office\") );\n" + "        insert( new Edible(\"apple\") );\n" + "        insert( new Edible(\"crackers\") );\n" + "end\n" + "";
    logger.debug(str);
    KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBaseFromString(str));
    // Get the accumulate node, so we can test it's memory later
    // now check beta memory was correctly cleared
    List<ObjectTypeNode> nodes = ((KnowledgeBaseImpl) kbase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for (ObjectTypeNode n : nodes) {
        if (((ClassObjectType) n.getObjectType()).getClassType() == String.class) {
            node = n;
            break;
        }
    }
    BetaNode stringBetaNode = (BetaNode) node.getObjectSinkPropagator().getSinks()[0];
    QueryElementNode queryElementNode1 = (QueryElementNode) stringBetaNode.getSinkPropagator().getSinks()[0];
    RightInputAdapterNode riaNode1 = (RightInputAdapterNode) queryElementNode1.getSinkPropagator().getSinks()[0];
    AccumulateNode accNode = (AccumulateNode) riaNode1.getObjectSinkPropagator().getSinks()[0];
    QueryElementNode queryElementNode2 = (QueryElementNode) accNode.getSinkPropagator().getSinks()[0];
    RightInputAdapterNode riaNode2 = (RightInputAdapterNode) queryElementNode2.getSinkPropagator().getSinks()[0];
    ExistsNode existsNode = (ExistsNode) riaNode2.getObjectSinkPropagator().getSinks()[0];
    QueryElementNode queryElementNode3 = (QueryElementNode) existsNode.getSinkPropagator().getSinks()[0];
    FromNode fromNode = (FromNode) queryElementNode3.getSinkPropagator().getSinks()[0];
    RightInputAdapterNode riaNode3 = (RightInputAdapterNode) fromNode.getSinkPropagator().getSinks()[0];
    NotNode notNode = (NotNode) riaNode3.getObjectSinkPropagator().getSinks()[0];
    KieSession ksession = createKnowledgeSession(kbase);
    InternalWorkingMemory wm = ((StatefulKnowledgeSessionImpl) ksession);
    AccumulateMemory accMemory = (AccumulateMemory) wm.getNodeMemory(accNode);
    BetaMemory existsMemory = (BetaMemory) wm.getNodeMemory(existsNode);
    FromMemory fromMemory = (FromMemory) wm.getNodeMemory(fromNode);
    BetaMemory notMemory = (BetaMemory) wm.getNodeMemory(notNode);
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    ksession.setGlobal("list", list);
    FactHandle fh = ksession.insert("bread");
    ksession.fireAllRules();
    final List food = new ArrayList();
    QueryResults results = null;
    // Execute normal query and check no subnetwork tuples are left behind
    results = ksession.getQueryResults("look", new Object[] { "kitchen", Variable.v });
    assertEquals(1, results.size());
    for (org.kie.api.runtime.rule.QueryResultsRow row : results) {
        food.addAll((Collection) row.get("food"));
        logger.debug(row.get("food").toString());
    }
    assertEquals(2, food.size());
    assertContains(new String[] { "crackers", "apple" }, food);
    assertEquals(0, accMemory.getBetaMemory().getRightTupleMemory().size());
    assertEquals(0, existsMemory.getRightTupleMemory().size());
    assertEquals(0, fromMemory.getBetaMemory().getLeftTupleMemory().size());
    assertEquals(0, notMemory.getRightTupleMemory().size());
    // Now execute an open query and ensure the memory is left populated
    food.clear();
    final List foodUpdated = new ArrayList();
    LiveQuery query = ksession.openLiveQuery("look", new Object[] { "kitchen", Variable.v }, new ViewChangedEventListener() {

        public void rowUpdated(Row row) {
            foodUpdated.addAll((Collection) row.get("food"));
        }

        public void rowDeleted(Row row) {
        }

        public void rowInserted(Row row) {
            food.addAll((Collection) row.get("food"));
        }
    });
    assertEquals(2, food.size());
    assertContains(new String[] { "crackers", "apple" }, food);
    assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
    assertEquals(2, existsMemory.getRightTupleMemory().size());
    assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
    assertEquals(0, notMemory.getRightTupleMemory().size());
    food.clear();
    // Now try again, make sure it only delete's it's own tuples
    results = ksession.getQueryResults("look", new Object[] { "kitchen", Variable.v });
    assertEquals(1, results.size());
    for (org.kie.api.runtime.rule.QueryResultsRow row : results) {
        food.addAll((Collection) row.get("food"));
        logger.debug(row.get("food").toString());
    }
    assertEquals(2, food.size());
    assertContains(new String[] { "crackers", "apple" }, food);
    assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
    assertEquals(2, existsMemory.getRightTupleMemory().size());
    assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
    assertEquals(0, notMemory.getRightTupleMemory().size());
    food.clear();
    // do an update and check it's  still memory size 2
    // however this time the food should be empty, as 'crackers' now blocks the not.
    ksession.update(fh, "crackers");
    ksession.fireAllRules();
    assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
    assertEquals(2, existsMemory.getRightTupleMemory().size());
    assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
    assertEquals(1, notMemory.getRightTupleMemory().size());
    assertEquals(0, foodUpdated.size());
    // do an update and check it's  still memory size 2
    // this time
    ksession.update(fh, "oranges");
    ksession.fireAllRules();
    assertEquals(2, accMemory.getBetaMemory().getRightTupleMemory().size());
    assertEquals(2, existsMemory.getRightTupleMemory().size());
    assertEquals(2, fromMemory.getBetaMemory().getLeftTupleMemory().size());
    assertEquals(0, notMemory.getRightTupleMemory().size());
    assertEquals(2, food.size());
    assertContains(new String[] { "crackers", "apple" }, food);
    // Close the open
    query.close();
    assertEquals(0, accMemory.getBetaMemory().getRightTupleMemory().size());
    assertEquals(0, existsMemory.getRightTupleMemory().size());
    assertEquals(0, fromMemory.getBetaMemory().getLeftTupleMemory().size());
    assertEquals(0, notMemory.getRightTupleMemory().size());
}
Also used : AccumulateMemory(org.drools.core.reteoo.AccumulateNode.AccumulateMemory) NotNode(org.drools.core.reteoo.NotNode) QueryResultsRow(org.kie.api.runtime.rule.QueryResultsRow) InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) AccumulateNode(org.drools.core.reteoo.AccumulateNode) QueryElementNode(org.drools.core.reteoo.QueryElementNode) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) ArrayList(java.util.ArrayList) FromNode(org.drools.core.reteoo.FromNode) ExistsNode(org.drools.core.reteoo.ExistsNode) LiveQuery(org.kie.api.runtime.rule.LiveQuery) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) KieBase(org.kie.api.KieBase) KieSession(org.kie.api.runtime.KieSession) List(java.util.List) ArrayList(java.util.ArrayList) RightInputAdapterNode(org.drools.core.reteoo.RightInputAdapterNode) BetaNode(org.drools.core.reteoo.BetaNode) BetaMemory(org.drools.core.reteoo.BetaMemory) QueryResults(org.kie.api.runtime.rule.QueryResults) FromMemory(org.drools.core.reteoo.FromNode.FromMemory) ViewChangedEventListener(org.kie.api.runtime.rule.ViewChangedEventListener) Collection(java.util.Collection) Row(org.kie.api.runtime.rule.Row) QueryResultsRow(org.kie.api.runtime.rule.QueryResultsRow) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.Test)

Example 33 with BetaMemory

use of org.drools.core.reteoo.BetaMemory in project drools by kiegroup.

the class SegmentCreationTest method testBranchCEMultipleSegments.

@Test
public void testBranchCEMultipleSegments() throws Exception {
    KieBase kbase = buildKnowledgeBase(// r1
    "   $a : A() \n", "   $a : A() \n" + "   if ( $a != null ) do[t1] \n" + // r2
    "   B() \n", "   $a : A() \n" + "   if ( $a != null ) do[t1] \n" + "   B() \n" + // r3
    "   C() \n");
    InternalWorkingMemory wm = ((InternalWorkingMemory) kbase.newKieSession());
    ObjectTypeNode aotn = getObjectTypeNode(kbase, LinkingTest.A.class);
    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getObjectSinkPropagator().getSinks()[0];
    ConditionalBranchNode cen1Node = (ConditionalBranchNode) liaNode.getSinkPropagator().getSinks()[1];
    JoinNode bNode = (JoinNode) cen1Node.getSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn2 = (RuleTerminalNode) bNode.getSinkPropagator().getSinks()[0];
    JoinNode cNode = (JoinNode) bNode.getSinkPropagator().getSinks()[1];
    RuleTerminalNode rtn3 = (RuleTerminalNode) cNode.getSinkPropagator().getSinks()[0];
    FactHandle bFh = wm.insert(new LinkingTest.B());
    FactHandle cFh = wm.insert(new LinkingTest.C());
    wm.flushPropagations();
    BetaMemory bNodeBm = (BetaMemory) wm.getNodeMemory(bNode);
    SegmentMemory bNodeSmem = bNodeBm.getSegmentMemory();
    // no beta nodes before branch CE, so never unlinks
    assertEquals(0, bNodeSmem.getAllLinkedMaskTest());
    assertEquals(2, bNodeSmem.getLinkedNodeMask());
    PathMemory pmemr2 = (PathMemory) wm.getNodeMemory(rtn2);
    assertEquals(1, pmemr2.getAllLinkedMaskTest());
    assertEquals(2, pmemr2.getLinkedSegmentMask());
    assertEquals(3, pmemr2.getSegmentMemories().length);
    assertFalse(pmemr2.isRuleLinked());
    PathMemory pmemr3 = (PathMemory) wm.getNodeMemory(rtn3);
    // notice only the first segment links
    assertEquals(1, pmemr3.getAllLinkedMaskTest());
    assertEquals(3, pmemr3.getSegmentMemories().length);
    assertFalse(pmemr3.isRuleLinked());
    BetaMemory cNodeBm = (BetaMemory) wm.getNodeMemory(cNode);
    SegmentMemory cNodeSmem = cNodeBm.getSegmentMemory();
    assertEquals(1, cNodeSmem.getAllLinkedMaskTest());
    assertEquals(1, cNodeSmem.getLinkedNodeMask());
    wm.insert(new LinkingTest.A());
    wm.flushPropagations();
    assertTrue(pmemr2.isRuleLinked());
    assertTrue(pmemr3.isRuleLinked());
    // retract B does not unlink the rule
    wm.delete(bFh);
    // retract C does not unlink the rule
    wm.delete(cFh);
    wm.flushPropagations();
    // b segment never unlinks, as it has no impact on path unlinking anyway
    assertEquals(3, pmemr2.getLinkedSegmentMask());
    assertTrue(pmemr2.isRuleLinked());
    // b segment never unlinks, as it has no impact on path unlinking anyway
    assertEquals(3, pmemr3.getLinkedSegmentMask());
    assertTrue(pmemr3.isRuleLinked());
}
Also used : SegmentMemory(org.drools.core.reteoo.SegmentMemory) FactHandle(org.kie.api.runtime.rule.FactHandle) JoinNode(org.drools.core.reteoo.JoinNode) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) ConditionalBranchNode(org.drools.core.reteoo.ConditionalBranchNode) BetaMemory(org.drools.core.reteoo.BetaMemory) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) KieBase(org.kie.api.KieBase) LeftInputAdapterNode(org.drools.core.reteoo.LeftInputAdapterNode) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) PathMemory(org.drools.core.reteoo.PathMemory) Test(org.junit.Test)

Example 34 with BetaMemory

use of org.drools.core.reteoo.BetaMemory in project drools by kiegroup.

the class MemoryLeakTest method testBetaMemoryLeakOnFactDelete.

@Test
public void testBetaMemoryLeakOnFactDelete() {
    // DROOLS-913
    String drl = "rule R1 when\n" + "    $a : Integer(this == 1)\n" + "    $b : String()\n" + "    $c : Integer(this == 2)\n" + "then \n" + "end\n" + "rule R2 when\n" + "    $a : Integer(this == 1)\n" + "    $b : String()\n" + "    $c : Integer(this == 3)\n" + "then \n" + "end\n";
    KieSession ksession = new KieHelper().addContent(drl, ResourceType.DRL).build().newKieSession();
    FactHandle fh1 = ksession.insert(1);
    FactHandle fh2 = ksession.insert(3);
    FactHandle fh3 = ksession.insert("test");
    ksession.fireAllRules();
    ksession.delete(fh1);
    ksession.delete(fh2);
    ksession.delete(fh3);
    ksession.fireAllRules();
    NodeMemories nodeMemories = ((InternalWorkingMemory) ksession).getNodeMemories();
    for (int i = 0; i < nodeMemories.length(); i++) {
        Memory memory = nodeMemories.peekNodeMemory(i);
        if (memory != null && memory.getSegmentMemory() != null) {
            SegmentMemory segmentMemory = memory.getSegmentMemory();
            System.out.println(memory);
            LeftTuple deleteFirst = memory.getSegmentMemory().getStagedLeftTuples().getDeleteFirst();
            if (segmentMemory.getRootNode() instanceof JoinNode) {
                BetaMemory bm = (BetaMemory) segmentMemory.getNodeMemories().getFirst();
                assertEquals(0, bm.getLeftTupleMemory().size());
            }
            System.out.println(deleteFirst);
            assertNull(deleteFirst);
        }
    }
}
Also used : InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) SegmentMemory(org.drools.core.reteoo.SegmentMemory) FactHandle(org.kie.api.runtime.rule.FactHandle) Memory(org.drools.core.common.Memory) BetaMemory(org.drools.core.reteoo.BetaMemory) SegmentMemory(org.drools.core.reteoo.SegmentMemory) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) JoinNode(org.drools.core.reteoo.JoinNode) KieHelper(org.kie.internal.utils.KieHelper) KieSession(org.kie.api.runtime.KieSession) NodeMemories(org.drools.core.common.NodeMemories) BetaMemory(org.drools.core.reteoo.BetaMemory) LeftTuple(org.drools.core.reteoo.LeftTuple) Test(org.junit.Test)

Example 35 with BetaMemory

use of org.drools.core.reteoo.BetaMemory in project drools by kiegroup.

the class LeftTupleIterator method getFirstLeftTuple.

public LeftTuple getFirstLeftTuple(LeftTupleSource source, LeftTupleSink sink, InternalWorkingMemory wm) {
    if (source instanceof AccumulateNode) {
        AccumulateMemory accmem = (AccumulateMemory) wm.getNodeMemory((MemoryFactory) source);
        BetaMemory memory = accmem.getBetaMemory();
        FastIterator localIt = memory.getLeftTupleMemory().fullFastIterator();
        Tuple leftTuple = BetaNode.getFirstTuple(memory.getLeftTupleMemory(), localIt);
        if (leftTuple != null) {
            AccumulateContext accctx = (AccumulateContext) leftTuple.getContextObject();
            return accctx.getResultLeftTuple();
        }
        return null;
    }
    if (source instanceof JoinNode || source instanceof NotNode || source instanceof FromNode || source instanceof AccumulateNode) {
        BetaMemory memory;
        FastIterator localIt;
        if (source instanceof FromNode) {
            memory = ((FromMemory) wm.getNodeMemory((MemoryFactory) source)).getBetaMemory();
        } else if (source instanceof AccumulateNode) {
            memory = ((AccumulateMemory) wm.getNodeMemory((MemoryFactory) source)).getBetaMemory();
        } else {
            memory = (BetaMemory) wm.getNodeMemory((MemoryFactory) source);
        }
        localIt = memory.getLeftTupleMemory().fullFastIterator();
        Tuple leftTuple = BetaNode.getFirstTuple(memory.getLeftTupleMemory(), localIt);
        while (leftTuple != null) {
            for (LeftTuple childleftTuple = leftTuple.getFirstChild(); childleftTuple != null; childleftTuple = childleftTuple.getHandleNext()) {
                if (childleftTuple.getTupleSink() == sink) {
                    return childleftTuple;
                }
            }
            leftTuple = (LeftTuple) localIt.next(leftTuple);
        }
    }
    if (source instanceof ExistsNode) {
        BetaMemory memory = (BetaMemory) wm.getNodeMemory((MemoryFactory) source);
        FastIterator localIt = memory.getRightTupleMemory().fullFastIterator();
        RightTuple rightTuple = (RightTuple) BetaNode.getFirstTuple(memory.getRightTupleMemory(), localIt);
        while (rightTuple != null) {
            if (rightTuple.getBlocked() != null) {
                for (LeftTuple leftTuple = rightTuple.getBlocked(); leftTuple != null; leftTuple = leftTuple.getBlockedNext()) {
                    for (LeftTuple childleftTuple = leftTuple.getFirstChild(); childleftTuple != null; childleftTuple = childleftTuple.getHandleNext()) {
                        if (childleftTuple.getTupleSink() == sink) {
                            return childleftTuple;
                        }
                    }
                }
            }
            rightTuple = (RightTuple) localIt.next(rightTuple);
        }
    } else if (source instanceof LeftInputAdapterNode) {
        ObjectSource os = ((LeftInputAdapterNode) source).getParentObjectSource();
        while (!(os instanceof ObjectTypeNode)) {
            os = os.getParentObjectSource();
        }
        ObjectTypeNode otn = (ObjectTypeNode) os;
        otnIterator = wm.getNodeMemory(otn).iterator();
        while (otnIterator.hasNext()) {
            InternalFactHandle handle = otnIterator.next();
            LeftTuple leftTuple = handle.findFirstLeftTuple(lt -> lt.getTupleSink() == sink);
            if (leftTuple != null) {
                return leftTuple;
            }
        }
    } else if (source instanceof EvalConditionNode || source instanceof QueryElementNode) {
        LeftTuple parentLeftTuple = getFirstLeftTuple(source.getLeftTupleSource(), (LeftTupleSink) source, wm);
        while (parentLeftTuple != null) {
            for (LeftTuple leftTuple = parentLeftTuple.getFirstChild(); leftTuple != null; leftTuple = leftTuple.getHandleNext()) {
                if (leftTuple.getTupleSink() == sink) {
                    return leftTuple;
                }
            }
            parentLeftTuple = getNextLeftTuple(source.getLeftTupleSource(), (LeftTupleSink) source, parentLeftTuple, wm);
        }
    }
    return null;
}
Also used : NotNode(org.drools.core.reteoo.NotNode) ExistsNode(org.drools.core.reteoo.ExistsNode) EvalConditionNode(org.drools.core.reteoo.EvalConditionNode) FastIterator(org.drools.core.util.FastIterator) AccumulateNode(org.drools.core.reteoo.AccumulateNode) AccumulateContext(org.drools.core.reteoo.AccumulateNode.AccumulateContext) BetaMemory(org.drools.core.reteoo.BetaMemory) JoinNode(org.drools.core.reteoo.JoinNode) FromNode(org.drools.core.reteoo.FromNode) LeftTuple(org.drools.core.reteoo.LeftTuple) RightTuple(org.drools.core.reteoo.RightTuple) LeftInputAdapterNode(org.drools.core.reteoo.LeftInputAdapterNode) QueryElementNode(org.drools.core.reteoo.QueryElementNode) Tuple(org.drools.core.spi.Tuple) BetaNode(org.drools.core.reteoo.BetaNode) AccumulateMemory(org.drools.core.reteoo.AccumulateNode.AccumulateMemory) FromMemory(org.drools.core.reteoo.FromNode.FromMemory) ObjectSource(org.drools.core.reteoo.ObjectSource) LeftTupleSink(org.drools.core.reteoo.LeftTupleSink) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) Iterator(org.drools.core.util.Iterator) LeftTupleSource(org.drools.core.reteoo.LeftTupleSource) AccumulateMemory(org.drools.core.reteoo.AccumulateNode.AccumulateMemory) NotNode(org.drools.core.reteoo.NotNode) EvalConditionNode(org.drools.core.reteoo.EvalConditionNode) AccumulateNode(org.drools.core.reteoo.AccumulateNode) JoinNode(org.drools.core.reteoo.JoinNode) QueryElementNode(org.drools.core.reteoo.QueryElementNode) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) LeftTupleSink(org.drools.core.reteoo.LeftTupleSink) BetaMemory(org.drools.core.reteoo.BetaMemory) FromNode(org.drools.core.reteoo.FromNode) LeftTuple(org.drools.core.reteoo.LeftTuple) ExistsNode(org.drools.core.reteoo.ExistsNode) RightTuple(org.drools.core.reteoo.RightTuple) ObjectSource(org.drools.core.reteoo.ObjectSource) FastIterator(org.drools.core.util.FastIterator) LeftTuple(org.drools.core.reteoo.LeftTuple) RightTuple(org.drools.core.reteoo.RightTuple) Tuple(org.drools.core.spi.Tuple) AccumulateContext(org.drools.core.reteoo.AccumulateNode.AccumulateContext) LeftInputAdapterNode(org.drools.core.reteoo.LeftInputAdapterNode)

Aggregations

BetaMemory (org.drools.core.reteoo.BetaMemory)49 ObjectTypeNode (org.drools.core.reteoo.ObjectTypeNode)25 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)24 Test (org.junit.Test)24 LeftInputAdapterNode (org.drools.core.reteoo.LeftInputAdapterNode)23 RightTuple (org.drools.core.reteoo.RightTuple)20 JoinNode (org.drools.core.reteoo.JoinNode)19 LeftTuple (org.drools.core.reteoo.LeftTuple)19 ArrayList (java.util.ArrayList)16 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)14 SegmentMemory (org.drools.core.reteoo.SegmentMemory)13 TupleMemory (org.drools.core.reteoo.TupleMemory)13 BetaNode (org.drools.core.reteoo.BetaNode)12 List (java.util.List)11 FastIterator (org.drools.core.util.FastIterator)11 LiaNodeMemory (org.drools.core.reteoo.LeftInputAdapterNode.LiaNodeMemory)10 KieBase (org.kie.api.KieBase)10 InternalFactHandle (org.drools.core.common.InternalFactHandle)9 AccumulateMemory (org.drools.core.reteoo.AccumulateNode.AccumulateMemory)9 BetaConstraints (org.drools.core.common.BetaConstraints)8