예제 #1
0
 private static TupleSets<LeftTuple> getTargetStagedLeftTuples(
     NetworkNode node, InternalWorkingMemory wm, SegmentMemory smem) {
   if (node == smem.getTipNode()) {
     // we are about to process the segment tip, allow it to merge insert/update/delete clashes
     if (smem.isEmpty()) {
       SegmentUtilities.createChildSegments(
           wm, smem, ((LeftTupleSource) node).getSinkPropagator());
     }
     return smem.getFirst().getStagedLeftTuples().takeAll();
   } else {
     return null;
   }
 }
예제 #2
0
  @Test
  public void testPopulatedSingleRuleNoSharingWithSubnetworkAtStart() throws Exception {
    KieBaseConfiguration kconf =
        (KieBaseConfiguration) KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption(RuleEngineOption.PHREAK);

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kconf);
    InternalWorkingMemory wm = ((InternalWorkingMemory) kbase.newStatefulKnowledgeSession());

    wm.insert(new A(1));
    wm.insert(new A(2));
    wm.insert(new D(1));
    wm.insert(new E(1));

    wm.insert(new C(2));
    wm.fireAllRules();

    kbase.addKnowledgePackages(buildKnowledgePackage("r1", "   A() not( B() and C() ) D() E()\n"));
    List list = new ArrayList();
    wm.setGlobal("list", list);

    ObjectTypeNode aotn = getObjectTypeNode(kbase, A.class);
    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getSinkPropagator().getSinks()[0];

    LiaNodeMemory lm = (LiaNodeMemory) wm.getNodeMemory(liaNode);
    SegmentMemory sm = lm.getSegmentMemory();
    assertNull(sm.getStagedLeftTuples().getInsertFirst());

    SegmentMemory subSm = sm.getFirst();
    SegmentMemory mainSm = subSm.getNext();

    assertNotNull(subSm.getStagedLeftTuples().getInsertFirst());
    assertNotNull(subSm.getStagedLeftTuples().getInsertFirst().getStagedNext());
    assertNull(subSm.getStagedLeftTuples().getInsertFirst().getStagedNext().getStagedNext());
    assertNotNull(mainSm.getStagedLeftTuples().getInsertFirst());
    assertNotNull(mainSm.getStagedLeftTuples().getInsertFirst().getStagedNext());
    assertNull(mainSm.getStagedLeftTuples().getInsertFirst().getStagedNext().getStagedNext());

    wm.fireAllRules();
    assertNull(subSm.getStagedLeftTuples().getInsertFirst());
    assertNull(mainSm.getStagedLeftTuples().getInsertFirst());
    assertEquals(2, list.size());

    assertEquals("r1", ((Match) list.get(0)).getRule().getName());
  }
예제 #3
0
  @Test
  public void testPopulatedRuleWithEvals() throws Exception {
    KnowledgeBase kbase1 = buildKnowledgeBase("r1", "   a:A() B() eval(1==1) eval(1==1) C(1;) \n");
    InternalWorkingMemory wm = ((InternalWorkingMemory) kbase1.newStatefulKnowledgeSession());
    List list = new ArrayList();
    wm.setGlobal("list", list);

    wm.insert(new A(1));
    wm.insert(new A(2));
    wm.insert(new A(3));
    wm.insert(new B(1));
    wm.insert(new C(1));
    wm.insert(new C(2));

    wm.fireAllRules();
    assertEquals(3, list.size());

    kbase1.addKnowledgePackages(
        buildKnowledgePackage("r2", "   a:A() B() eval(1==1) eval(1==1) C(2;) \n"));

    ObjectTypeNode aotn = getObjectTypeNode(kbase1, A.class);
    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getSinkPropagator().getSinks()[0];
    JoinNode bNode = (JoinNode) liaNode.getSinkPropagator().getFirstLeftTupleSink();

    EvalConditionNode e1 = (EvalConditionNode) bNode.getSinkPropagator().getFirstLeftTupleSink();
    EvalConditionNode e2 = (EvalConditionNode) e1.getSinkPropagator().getFirstLeftTupleSink();

    JoinNode c1Node = (JoinNode) e2.getSinkPropagator().getFirstLeftTupleSink();
    JoinNode c2Node = (JoinNode) e2.getSinkPropagator().getLastLeftTupleSink();

    LiaNodeMemory lm = (LiaNodeMemory) wm.getNodeMemory(liaNode);
    SegmentMemory sm = lm.getSegmentMemory();

    BetaMemory c1Mem = (BetaMemory) wm.getNodeMemory(c1Node);
    assertSame(sm.getFirst(), c1Mem.getSegmentMemory());
    assertEquals(3, c1Mem.getLeftTupleMemory().size());
    assertEquals(1, c1Mem.getRightTupleMemory().size());

    BetaMemory c2Mem = (BetaMemory) wm.getNodeMemory(c2Node);
    SegmentMemory c2Smem = sm.getFirst().getNext();
    assertSame(c2Smem, c2Mem.getSegmentMemory());
    assertEquals(0, c2Mem.getLeftTupleMemory().size());
    assertEquals(0, c2Mem.getRightTupleMemory().size());
    assertNotNull(c2Smem.getStagedLeftTuples().getInsertFirst());
    assertNotNull(c2Smem.getStagedLeftTuples().getInsertFirst().getStagedNext());
    assertNotNull(c2Smem.getStagedLeftTuples().getInsertFirst().getStagedNext().getStagedNext());
    assertNull(
        c2Smem
            .getStagedLeftTuples()
            .getInsertFirst()
            .getStagedNext()
            .getStagedNext()
            .getStagedNext());

    wm.fireAllRules();
    assertEquals(3, c2Mem.getLeftTupleMemory().size());
    assertEquals(1, c2Mem.getRightTupleMemory().size());
    assertNull(c2Smem.getStagedLeftTuples().getInsertFirst());
    assertEquals(6, list.size());

    assertEquals("r1", ((Match) list.get(0)).getRule().getName());
    assertEquals("r1", ((Match) list.get(1)).getRule().getName());
    assertEquals("r1", ((Match) list.get(2)).getRule().getName());
    assertEquals("r2", ((Match) list.get(3)).getRule().getName());
    assertEquals(3, ((A) ((Match) list.get(3)).getDeclarationValue("a")).getObject());
    assertEquals("r2", ((Match) list.get(4)).getRule().getName());
    assertEquals(2, ((A) ((Match) list.get(4)).getDeclarationValue("a")).getObject());
    assertEquals("r2", ((Match) list.get(5)).getRule().getName());
    assertEquals(1, ((A) ((Match) list.get(5)).getDeclarationValue("a")).getObject());
  }
예제 #4
0
  public void innerEval(
      LeftInputAdapterNode liaNode,
      PathMemory pmem,
      NetworkNode node,
      long bit,
      Memory nodeMem,
      SegmentMemory[] smems,
      int smemIndex,
      TupleSets<LeftTuple> trgTuples,
      InternalWorkingMemory wm,
      LinkedList<StackEntry> stack,
      boolean processRian,
      RuleExecutor executor) {
    TupleSets<LeftTuple> srcTuples;
    SegmentMemory smem = smems[smemIndex];
    TupleSets<LeftTuple> stagedLeftTuples = null;
    while (true) {
      srcTuples = trgTuples; // previous target, is now the source
      if (log.isTraceEnabled()) {
        int offset = getOffset(node);
        log.trace(
            "{} {} {} {}", indent(offset), ++cycle, node.toString(), srcTuples.toStringSizes());
      }

      boolean emptySrcTuples = srcTuples.isEmpty();
      if (!(NodeTypeEnums.isBetaNode(node) && ((BetaNode) node).isRightInputIsRiaNode())) {
        // The engine cannot skip a ria node, as the dirty might be several levels deep
        if (emptySrcTuples && smem.getDirtyNodeMask() == 0) {
          // empty sources and segment is not dirty, skip to non empty src tuples or dirty segment.
          boolean foundDirty = false;
          for (int i = ++smemIndex, length = smems.length; i < length; i++) {
            if (log.isTraceEnabled()) {
              int offset = getOffset(node);
              log.trace("{} Skip Segment {}", indent(offset), i - 1);
            }

            // this is needed for subnetworks that feed into a parent network that has no right
            // inputs,
            // and may not yet be initialized
            if (smem.isEmpty() && !NodeTypeEnums.isTerminalNode(smem.getTipNode())) {
              SegmentUtilities.createChildSegments(
                  wm, smem, ((LeftTupleSource) smem.getTipNode()).getSinkPropagator());
            }

            smem = smems[i];
            bit = 1;
            srcTuples = smem.getStagedLeftTuples().takeAll();
            emptySrcTuples = srcTuples.isEmpty();
            node = smem.getRootNode();
            nodeMem = smem.getNodeMemories().getFirst();
            if (!emptySrcTuples
                || smem.getDirtyNodeMask() != 0
                || (NodeTypeEnums.isBetaNode(node) && ((BetaNode) node).isRightInputIsRiaNode())) {
              // break if dirty or if we reach a subnetwork. It must break for subnetworks, so they
              // can be searched.
              foundDirty = true;
              smemIndex = i;
              break;
            }
          }
          if (!foundDirty) {
            break;
          }
        }
        if (log.isTraceEnabled()) {
          int offset = getOffset(node);
          log.trace("{} Segment {}", indent(offset), smemIndex);
          log.trace(
              "{} {} {} {}", indent(offset), cycle, node.toString(), srcTuples.toStringSizes());
        }
      }

      long dirtyMask = smem.getDirtyNodeMask();
      if (emptySrcTuples) {
        while ((dirtyMask & bit) == 0
            && node != smem.getTipNode()
            && !(NodeTypeEnums.isBetaNode(node) && ((BetaNode) node).isRightInputIsRiaNode())) {
          if (log.isTraceEnabled()) {
            int offset = getOffset(node);
            log.trace("{} Skip Node {}", indent(offset), node);
          }
          bit = bit << 1; // shift to check the next node
          node = ((LeftTupleSource) node).getSinkPropagator().getFirstLeftTupleSink();
          nodeMem = nodeMem.getNext();
        }
      }

      if (NodeTypeEnums.isTerminalNode(node)) {
        TerminalNode rtn = (TerminalNode) node;
        if (node.getType() == NodeTypeEnums.QueryTerminalNode) {
          pQtNode.doNode((QueryTerminalNode) rtn, wm, srcTuples, stack);
        } else {
          pRtNode.doNode(rtn, wm, srcTuples, executor);
        }
        break;
      } else if (NodeTypeEnums.RightInputAdaterNode == node.getType()) {
        doRiaNode2(wm, srcTuples, (RightInputAdapterNode) node);
        break;
      }

      stagedLeftTuples = getTargetStagedLeftTuples(node, wm, smem);
      LeftTupleSinkNode sink = ((LeftTupleSource) node).getSinkPropagator().getFirstLeftTupleSink();

      trgTuples =
          evalNode(
              liaNode,
              pmem,
              node,
              bit,
              nodeMem,
              smems,
              smemIndex,
              wm,
              stack,
              processRian,
              executor,
              srcTuples,
              smem,
              stagedLeftTuples,
              sink);
      if (trgTuples == null) {
        break; // Queries exists and has been placed StackEntry, and there are no current trgTuples
        // to process
      }

      if (node != smem.getTipNode()) {
        // get next node and node memory in the segment
        node = sink;
        nodeMem = nodeMem.getNext();
        bit = bit << 1;
      } else {
        // Reached end of segment, start on new segment.
        smem.getFirst().getStagedLeftTuples().addAll(stagedLeftTuples); // must put back all the LTs
        // end of SegmentMemory, so we know that stagedLeftTuples is not null
        SegmentPropagator.propagate(smem, trgTuples, wm);
        bit = 1;
        smem = smems[++smemIndex];
        trgTuples = smem.getStagedLeftTuples().takeAll();

        if (log.isTraceEnabled()) {
          int offset = getOffset(node);
          log.trace("{} Segment {}", indent(offset), smemIndex);
        }
        node = smem.getRootNode();
        nodeMem = smem.getNodeMemories().getFirst();
      }
      processRian = true; //  make sure it's reset, so ria nodes are processed
    }

    if (stagedLeftTuples != null && !stagedLeftTuples.isEmpty()) {
      smem.getFirst().getStagedLeftTuples().addAll(stagedLeftTuples); // must put back all the LTs
    }
  }
예제 #5
0
  public void eval2(
      LeftInputAdapterNode liaNode,
      PathMemory rmem,
      NetworkNode node,
      Memory nodeMem,
      SegmentMemory[] smems,
      int smemIndex,
      LeftTupleSets trgTuples,
      InternalWorkingMemory wm,
      LinkedList<StackEntry> stack,
      Set<String> visitedRules,
      boolean processRian,
      RuleExecutor executor) {
    LeftTupleSets srcTuples;
    SegmentMemory smem = smems[smemIndex];
    while (true) {
      srcTuples = trgTuples; // previous target, is now the source
      if (log.isTraceEnabled()) {
        int offset = getOffset(node);
        log.trace(
            "{} {} {} {}", indent(offset), ++cycle, node.toString(), srcTuples.toStringSizes());
      }

      if (NodeTypeEnums.isTerminalNode(node)) {
        TerminalNode rtn = (TerminalNode) node;
        if (node.getType() == NodeTypeEnums.QueryTerminalNode) {
          pQtNode.doNode((QueryTerminalNode) rtn, wm, srcTuples, stack);
        } else {
          pRtNode.doNode(rtn, wm, srcTuples, executor);
        }
        return;
      } else if (NodeTypeEnums.RightInputAdaterNode == node.getType()) {
        doRiaNode2(wm, srcTuples, (RightInputAdapterNode) node, stack);
        return;
      }

      LeftTupleSets stagedLeftTuples;
      if (node == smem.getTipNode() && smem.getFirst() != null) {
        // we are about to process the segment tip, allow it to merge insert/update/delete clashes
        // Can happen if the next segments have not yet been initialized
        stagedLeftTuples = smem.getFirst().getStagedLeftTuples();
      } else {
        stagedLeftTuples = null;
      }

      LeftTupleSinkNode sink = ((LeftTupleSource) node).getSinkPropagator().getFirstLeftTupleSink();

      trgTuples = new LeftTupleSets();

      if (NodeTypeEnums.isBetaNode(node)) {
        BetaNode betaNode = (BetaNode) node;

        BetaMemory bm = null;
        AccumulateMemory am = null;
        if (NodeTypeEnums.AccumulateNode == node.getType()) {
          am = (AccumulateMemory) nodeMem;
          bm = am.getBetaMemory();
        } else {
          bm = (BetaMemory) nodeMem;
        }

        if (processRian && betaNode.isRightInputIsRiaNode()) {
          // if the subnetwork is nested in this segment, it will create srcTuples containing
          // peer LeftTuples, suitable for the node in the main path.
          doRiaNode(
              wm,
              liaNode,
              rmem,
              srcTuples,
              betaNode,
              sink,
              smems,
              smemIndex,
              nodeMem,
              bm,
              stack,
              visitedRules,
              executor);
          return; // return here is doRiaNode queues the evaluation on the stack, which is necessary
          // to handled nested query nodes
        }

        if (!bm.getDequeu().isEmpty()) {
          // If there are no staged RightTuples, then process the Dequeue, popping entries, until
          // another insert/expiration clash
          RightTupleSets rightTuples = bm.getStagedRightTuples();
          if (rightTuples.isEmpty()) {
            // nothing staged, so now process the Dequeu
            Deque<RightTuple> que = bm.getDequeu();
            while (!que.isEmpty()) {
              RightTuple rightTuple = que.peekFirst();
              if (rightTuple.getPropagationContext().getType() == PropagationContext.EXPIRATION
                  &&
                  // Cannot pop an expired fact, if the insert/update has not yet been evaluated.
                  rightTuple.getStagedType() != LeftTuple.NONE) {
                break;
              }

              switch (rightTuple.getPropagationContext().getType()) {
                case PropagationContext.INSERTION:
                case PropagationContext.RULE_ADDITION:
                  rightTuples.addInsert(rightTuple);
                  break;
                case PropagationContext.MODIFICATION:
                  rightTuples.addUpdate(rightTuple);
                  break;
                case PropagationContext.DELETION:
                case PropagationContext.EXPIRATION:
                case PropagationContext.RULE_REMOVAL:
                  rightTuples.addDelete(rightTuple);
                  break;
              }
              que.removeFirst();
            }
          }

          if (!bm.getDequeu().isEmpty()) {
            // The DeQue is not empty, add StackEntry for reprocessing.
            StackEntry stackEntry =
                new StackEntry(
                    liaNode,
                    node,
                    sink,
                    rmem,
                    nodeMem,
                    smems,
                    smemIndex,
                    trgTuples,
                    visitedRules,
                    false);
            stack.add(stackEntry);
          }
        }

        switch (node.getType()) {
          case NodeTypeEnums.JoinNode:
            {
              pJoinNode.doNode(
                  (JoinNode) node, sink, bm, wm, srcTuples, trgTuples, stagedLeftTuples);
              break;
            }
          case NodeTypeEnums.NotNode:
            {
              pNotNode.doNode((NotNode) node, sink, bm, wm, srcTuples, trgTuples, stagedLeftTuples);
              break;
            }
          case NodeTypeEnums.ExistsNode:
            {
              pExistsNode.doNode(
                  (ExistsNode) node, sink, bm, wm, srcTuples, trgTuples, stagedLeftTuples);
              break;
            }
          case NodeTypeEnums.AccumulateNode:
            {
              pAccNode.doNode(
                  (AccumulateNode) node, sink, am, wm, srcTuples, trgTuples, stagedLeftTuples);
              break;
            }
        }
      } else {
        switch (node.getType()) {
          case NodeTypeEnums.EvalConditionNode:
            {
              pEvalNode.doNode(
                  (EvalConditionNode) node,
                  (EvalMemory) nodeMem,
                  sink,
                  wm,
                  srcTuples,
                  trgTuples,
                  stagedLeftTuples);
              break;
            }
          case NodeTypeEnums.FromNode:
            {
              pFromNode.doNode(
                  (FromNode) node,
                  (FromMemory) nodeMem,
                  sink,
                  wm,
                  srcTuples,
                  trgTuples,
                  stagedLeftTuples);
              break;
            }
          case NodeTypeEnums.QueryElementNode:
            {
              QueryElementNodeMemory qmem = (QueryElementNodeMemory) nodeMem;

              if (srcTuples.isEmpty() && qmem.getResultLeftTuples().isEmpty()) {
                // no point in evaluating query element, and setting up stack, if there is nothing
                // to process
                break;
              }

              QueryElementNode qnode = (QueryElementNode) node;
              if (visitedRules == Collections.<String>emptySet()) {
                visitedRules = new HashSet<String>();
              }
              visitedRules.add(qnode.getQueryElement().getQueryName());

              // result tuples can happen when reactivity occurs inside of the query, prior to
              // evaluation
              // we will need special behaviour to add the results again, when this query result
              // resumes
              trgTuples.addAll(qmem.getResultLeftTuples());

              if (!srcTuples.isEmpty()) {
                // only process the Query Node if there are src tuples
                StackEntry stackEntry =
                    new StackEntry(
                        liaNode,
                        node,
                        sink,
                        rmem,
                        nodeMem,
                        smems,
                        smemIndex,
                        trgTuples,
                        visitedRules,
                        true);

                stack.add(stackEntry);

                pQueryNode.doNode(
                    qnode, (QueryElementNodeMemory) nodeMem, stackEntry, sink, wm, srcTuples);

                SegmentMemory qsmem = ((QueryElementNodeMemory) nodeMem).getQuerySegmentMemory();
                List<PathMemory> qrmems = qsmem.getPathMemories();

                // Build the evaluation information for each 'or' branch
                // Exception fo the last, place each entry on the stack, the last one evaluate now.
                for (int i = qrmems.size() - 1; i >= 0; i--) {
                  PathMemory qrmem = qrmems.get(i);

                  rmem = qrmem;
                  smems = qrmem.getSegmentMemories();
                  smemIndex = 0;
                  smem = smems[smemIndex]; // 0
                  liaNode = (LeftInputAdapterNode) smem.getRootNode();

                  if (liaNode == smem.getTipNode()) {
                    // segment only has liaNode in it
                    // nothing is staged in the liaNode, so skip to next segment
                    smem = smems[++smemIndex]; // 1
                    node = smem.getRootNode();
                    nodeMem = smem.getNodeMemories().getFirst();
                  } else {
                    // lia is in shared segment, so point to next node
                    node = liaNode.getSinkPropagator().getFirstLeftTupleSink();
                    nodeMem =
                        smem.getNodeMemories().getFirst().getNext(); // skip the liaNode memory
                  }

                  trgTuples = smem.getStagedLeftTuples();

                  if (i != 0 && !trgTuples.isEmpty()) {
                    // All entries except the last should be placed on the stack for evaluation
                    // later.
                    stackEntry =
                        new StackEntry(
                            liaNode,
                            node,
                            null,
                            rmem,
                            nodeMem,
                            smems,
                            smemIndex,
                            trgTuples,
                            visitedRules,
                            false);
                    if (log.isTraceEnabled()) {
                      int offset = getOffset(stackEntry.getNode());
                      log.trace(
                          "{} ORQueue branch={} {} {}",
                          indent(offset),
                          i,
                          stackEntry.getNode().toString(),
                          trgTuples.toStringSizes());
                    }
                    stack.add(stackEntry);
                  }
                }
                processRian = true; //  make sure it's reset, so ria nodes are processed
                continue;
              }
              break;
            }
          case NodeTypeEnums.ConditionalBranchNode:
            {
              pBranchNode.doNode(
                  (ConditionalBranchNode) node,
                  (ConditionalBranchMemory) nodeMem,
                  sink,
                  wm,
                  srcTuples,
                  trgTuples,
                  stagedLeftTuples,
                  executor);
              break;
            }
        }
      }

      if (node != smem.getTipNode()) {
        // get next node and node memory in the segment
        node = sink;
        nodeMem = nodeMem.getNext();
      } else {
        // Reached end of segment, start on new segment.
        SegmentPropagator.propagate(smem, trgTuples, wm);
        smem = smems[++smemIndex];
        trgTuples = smem.getStagedLeftTuples();
        if (log.isTraceEnabled()) {
          log.trace("Segment {}", smemIndex);
        }
        node = (LeftTupleSink) smem.getRootNode();
        nodeMem = smem.getNodeMemories().getFirst();
      }
      processRian = true; //  make sure it's reset, so ria nodes are processed
    }
  }