Copilot commented on code in PR #6909:
URL: https://github.com/apache/incubator-kie/pull/6909#discussion_r3895317148


##########
drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/RuleContext.java:
##########
@@ -136,6 +138,17 @@ void addDeclaration( Variable variable, Declaration 
declaration ) {
         declarations.put( variable, declaration );
     }
 
+    void addSequenceVarIndex( Variable variable, int filterIndex ) {
+        if (sequenceVarIndexes == null) {
+            sequenceVarIndexes = new HashMap<>();
+        }
+        sequenceVarIndexes.put( variable, filterIndex );

Review Comment:
   This map stores only a filter index, but filter indexes restart at zero for 
every `sequence()` in a rule. `SequencerFactSupplier` also finds only the 
nearest `SequencerMemory`, so a consequence referencing variables from two 
sequences resolves both indexes against that same sequence and can return the 
wrong type or fail. Include the owning sequence/node identity in this metadata 
and use it when locating the matching memory.



##########
drools-base/src/main/java/org/drools/base/reteoo/sequencing/signalprocessors/Gates.java:
##########
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.drools.base.reteoo.sequencing.signalprocessors;
+
+public class Gates {
+    public static boolean and(long a, long b) {return a == b;}
+
+    public static boolean or(long a, long b)  {return (a & b) > 0;}

Review Comment:
   When the 64th input is the matching OR branch, `(a & b)` has only the sign 
bit set and is negative, so `> 0` incorrectly reports no match. Test for 
nonzero instead.



##########
drools-model/drools-canonical-model/src/main/java/org/drools/model/PatternDSL.java:
##########
@@ -1887,6 +1906,29 @@ public static ConditionalConsequenceBuilder when() {
 
     // -- rule --
 
+    public static SequenceViewItem sequence(SequenceStep... steps) {
+        return new SequenceViewItem(steps);
+    }

Review Comment:
   `sequence()` accepts zero steps, but activation unconditionally accesses 
`steps[0]` in `SequenceController.start`, causing an opaque 
`ArrayIndexOutOfBoundsException` at runtime. Either reject an empty sequence 
here with a descriptive argument error or define empty-sequence matching 
semantics.



##########
drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/SequenceReviewProbeTest.java:
##########
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.drools.modelcompiler;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.drools.model.Model;
+import org.drools.model.Rule;
+import org.drools.model.Variable;
+import org.drools.model.impl.ModelImpl;
+import org.drools.modelcompiler.domain.Person;
+import org.drools.modelcompiler.domain.Toy;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.kie.api.KieBase;
+import org.kie.api.runtime.KieSession;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.drools.model.DSL.declarationOf;
+import static org.drools.model.DSL.execute;
+import static org.drools.model.PatternDSL.pattern;
+import static org.drools.model.PatternDSL.rule;
+import static org.drools.model.PatternDSL.sequence;
+
+public class SequenceReviewProbeTest {
+
+    private final List<String> results = new ArrayList<>();
+    private KieSession ksession;
+
+    @AfterEach
+    public void tearDown() {
+        results.clear();
+        if (ksession != null) {
+            ksession.dispose();
+        }
+    }
+
+    @Test
+    public void plainRuleAndSequenceRuleShareAnEventType() {
+        Variable<Toy> toy = declarationOf(Toy.class);
+        Variable<Person> person = declarationOf(Person.class);
+
+        Rule plainRule = rule("plain-rule").build(
+                pattern(toy).expr("is-ball", t -> t.getName().equals("ball")),
+                execute(() -> results.add("plain:ball"))
+        );
+
+        Rule seqRule = rule("seq-rule").build(
+                pattern(person),
+                sequence(
+                        pattern(toy).expr("seq-is-ball", t -> 
t.getName().equals("ball"))
+                ),
+                execute(() -> results.add("seq:ball"))
+        );
+
+        Model model = new ModelImpl().addRule(plainRule).addRule(seqRule);
+        KieBase kieBase = KieBaseBuilder.createKieBaseFromModel(model);
+        ksession = kieBase.newKieSession();
+
+        ksession.insert(new Person("anchor"));
+        ksession.fireAllRules();
+
+        ksession.insert(new Toy("ball"));
+        ksession.fireAllRules();
+
+        // Both the plain rule and the sequence rule must fire.
+        assertThat(results).contains("plain:ball");

Review Comment:
   The comment says both rules must fire, but this assertion only checks the 
plain rule; the test passes if sequence dispatch is completely broken for a 
type shared with a normal alpha network. Assert both expected results.



##########
drools-base/src/main/java/org/drools/base/reteoo/sequencing/Sequence.java:
##########
@@ -0,0 +1,327 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.drools.base.reteoo.sequencing;
+
+import org.drools.base.base.ValueResolver;
+import org.drools.base.reteoo.DynamicFilter;
+import org.drools.base.reteoo.sequencing.signalprocessors.LogicGate;
+import org.drools.base.reteoo.sequencing.steps.LogicCircuitStep;
+import org.drools.base.reteoo.sequencing.steps.Step;
+import org.drools.base.reteoo.sequencing.steps.Step.StepFactory;
+import org.drools.base.rule.Declaration;
+import org.drools.base.rule.Pattern;
+import org.drools.base.rule.RuleConditionElement;
+import org.drools.base.reteoo.SignalAdapter;
+import org.drools.base.util.CircularArrayList;
+import org.kie.api.runtime.rule.FactHandle;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+public class Sequence implements RuleConditionElement {
+    private final int sequenceIndex;
+
+    private Pattern[] filters;
+
+    private Step[] steps;
+
+    private LogicGate[] gates;
+
+    private SequenceController controller;
+
+    public Sequence(int sequenceIndex, StepFactory... stepFactories) {
+        this.steps = new Step[stepFactories.length];
+        this.sequenceIndex = sequenceIndex;
+        this.controller = DefaultController.getInstance();
+
+        for ( int i = 0; i < steps.length; i++ ) {
+            steps[i] = stepFactories[i].createStep(this);
+        }
+        populateLogicGates();
+    }
+
+    public Pattern[] getFilters() {
+        return filters;
+    }
+
+    public void setFilters(Pattern[] filters) {
+        this.filters = filters;
+    }
+
+    public void populateLogicGates() {
+        List<LogicGate> list = new ArrayList<>();
+        for (Step step : getSteps()) {
+            if (step instanceof LogicCircuitStep) {
+                LogicGate[] circuitGates = ((LogicCircuitStep) 
step).getCircuit().getGates();
+                for (int i = 0; i < circuitGates.length; i++) {
+                    list.add(circuitGates[i]);
+                }
+            }
+        }
+        gates = list.toArray(new LogicGate[0]);
+    }
+
+    public int getSequenceIndex() {
+        return sequenceIndex;
+    }
+
+    public Step[] getSteps() {
+        return steps;
+    }
+
+    public void setSteps(Step[] steps) {
+        this.steps = steps;
+    }
+
+    public LogicGate[] getGates() {
+        return gates;
+    }
+
+    @Override
+    public Map<String, Declaration> getInnerDeclarations() {
+        return Map.of();
+    }
+
+    @Override
+    public Map<String, Declaration> getOuterDeclarations() {
+        return Map.of();
+    }
+
+    @Override
+    public Declaration resolveDeclaration(String identifier) {
+        return null;
+    }
+
+    @Override
+    public RuleConditionElement clone() {
+        throw new UnsupportedOperationException("Sequence does not support 
clone()");
+    }

Review Comment:
   `RuleConditionElement.clone()` is part of the interface contract, and 
`LogicTransformer.processNamedConsequences` clones every preceding condition 
when expanding an intermediate named consequence. If a `sequence()` precedes 
such a consequence, rule compilation reaches this method and fails. Return an 
independent clone of the sequence, filters, steps, and gate wiring.
   
   This issue also appears on line 131 of the same file.



##########
drools-base/src/main/java/org/drools/base/reteoo/SignalAdapter.java:
##########
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.drools.base.reteoo;
+
+import org.drools.base.base.ValueResolver;
+import org.drools.base.reteoo.sequencing.Sequence.SequenceMemory;
+import org.drools.base.reteoo.sequencing.signalprocessors.SignalProcessor;
+import org.drools.base.util.AbstractLinkedListNode;
+import org.kie.api.runtime.rule.FactHandle;
+
+public class SignalAdapter extends AbstractLinkedListNode<SignalAdapter> {
+    private SignalProcessor output;
+    private int             signalBitIndex;
+    private SequenceMemory  memory;
+
+    public SignalAdapter(SignalProcessor output, int signalBitIndex, 
SequenceMemory memory) {
+        this.output         = output;
+        this.signalBitIndex = signalBitIndex;
+        this.memory         = memory;
+    }
+
+    public void receive(ValueResolver reteEvaluator, FactHandle factHandle) {
+        memory.addData(factHandle);
+        output.consume(signalBitIndex, memory, reteEvaluator);

Review Comment:
   Matched facts are appended chronologically, but consequences retrieve them 
by the pattern's `filterIndex`. Those positions diverge when an OR branch skips 
an earlier filter, AND children arrive in a different order, duplicates are 
received, or the sequence is restarted without clearing the buffer; the 
consequence can then read the wrong handle or throw 
`IndexOutOfBoundsException`. Store each handle in a stable per-filter slot (and 
reset those slots on restart), or carry an execution-relative mapping into the 
consequence.



##########
drools-core/src/main/java/org/drools/core/reteoo/SequenceNode.java:
##########
@@ -0,0 +1,573 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.drools.core.reteoo;
+
+import org.drools.base.base.ObjectType;
+import org.drools.base.common.RuleBasePartitionId;
+import org.drools.base.reteoo.DynamicFilter;
+import org.drools.base.reteoo.DynamicFilterProto;
+import org.drools.base.reteoo.NodeTypeEnums;
+import org.drools.base.reteoo.sequencing.Sequence.SequenceMemory;
+import org.drools.base.rule.Pattern;
+import org.drools.core.RuleBaseConfiguration;
+import org.drools.core.common.InternalFactHandle;
+import org.drools.core.common.InternalWorkingMemory;
+import org.drools.core.common.Memory;
+import org.drools.core.common.MemoryFactory;
+import org.drools.core.common.PropagationContext;
+import org.drools.core.common.ReteEvaluator;
+import org.drools.core.common.TupleSets;
+import org.drools.core.common.TupleSetsImpl;
+import org.drools.core.common.UpdateContext;
+import org.drools.core.reteoo.SequenceNode.SequenceNodeMemory;
+import org.drools.core.reteoo.builder.BuildContext;
+import org.drools.base.reteoo.sequencing.Sequencer;
+import org.drools.core.reteoo.sequencing.SequencerMemoryImpl;
+import org.drools.base.reteoo.sequencing.SequencerMemory;
+import org.drools.base.util.AbstractLinkedListNode;
+import org.drools.base.util.LinkedList;
+import org.drools.core.util.index.TupleList;
+import org.drools.util.bitmask.BitMask;
+
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.List;
+
+public class SequenceNode extends LeftTupleSource
+    implements
+    LeftTupleNode,
+    LeftTupleSinkNode,
+    MemoryFactory<SequenceNodeMemory> {
+
+    private static final long      serialVersionUID = 510l;
+
+    protected boolean              tupleMemoryEnabled;
+
+    private Sequencer sequencer;
+
+    private AlphaAdapter[] alphaAdapters;
+
+    private DynamicFilterProto[] dynamicFilters;
+
+    private LeftTupleSinkNode      previousTupleSinkNode;
+
+    private LeftTupleSinkNode      nextTupleSinkNode;
+
+    public SequenceNode() {
+
+    }
+
+    public SequenceNode(final int id,
+                        final LeftTupleSource tupleSource,
+                        final BuildContext context) {
+        super(id, context);
+        setLeftTupleSource(tupleSource);
+        this.tupleMemoryEnabled = context.isTupleMemoryEnabled();
+
+        initMasks(context);
+
+        hashcode = calculateHashCode();
+        setStreamMode(true);
+    }
+
+    public void setAlphaAdapters(AlphaAdapter[] adapters) {
+        this.alphaAdapters = adapters;
+    }
+
+    public DynamicFilterProto[] getDynamicFilters() {
+        return dynamicFilters;
+    }
+
+    public void setDynamicFilters(DynamicFilterProto[] dynamicFilters) {
+        this.dynamicFilters = dynamicFilters;
+    }
+
+    public void doAttach(BuildContext context) {
+        super.doAttach(context);
+        this.leftInput.addTupleSink( this, context );
+    }
+
+    public void networkUpdated(UpdateContext updateContext) {
+        this.leftInput.networkUpdated(updateContext);
+    }
+
+
+    /**
+     * Produce a debug string.
+     *
+     * @return The debug string.
+     */
+    public String toString() {
+        return "[SequenceNode(" + this.id + ")]]";
+    }
+
+    private int calculateHashCode() {
+        int result = this.leftInput.hashCode();
+        if (this.sequencer != null) {
+            result = 31 * result + 
System.identityHashCode(this.sequencer.getSequence());
+        }
+        return result;
+    }
+
+    @Override
+    public boolean equals(final Object object) {
+        if (this == object) {
+            return true;
+        }
+
+        if ( object == null || !(object instanceof SequenceNode) || 
this.hashCode() != object.hashCode() ) {
+            return false;
+        }
+
+        SequenceNode other = (SequenceNode) object;
+        return this.leftInput.getId() == other.leftInput.getId()
+            && this.sequencer.getSequence() == other.sequencer.getSequence();
+    }
+
+    public SequenceNodeMemory createMemory(final RuleBaseConfiguration config, 
ReteEvaluator reteEvaluator) {
+        // activeFilters is indexed by adapter index (one slot per distinct 
object type).
+        // AlphaAdapter.assertObject looks up activeFilters[adapterIndex] to 
dispatch to matching filters.
+        // filters is indexed by pattern/filter index (one slot per step).
+        // The two sizes differ when multiple steps share the same object type.
+        LinkedList<DynamicFilter>[] activeFilters = new 
LinkedList[alphaAdapters.length];
+        SequenceNodeMemory          memory  = new SequenceNodeMemory(this, 
activeFilters, new DynamicFilter[dynamicFilters.length]);
+        return memory;
+    }
+
+    public SequencerMemory createSequencerMemory(TupleImpl lt, LeftTupleSink 
sink, SequenceNodeMemory nodeMemory) {
+        SequencerMemory sequencerMemory = new SequencerMemoryImpl(sequencer, 
lt, sink, this, nodeMemory);
+
+        return sequencerMemory;
+    }
+
+    public Sequencer getSequencer() {
+        return sequencer;
+    }
+
+    public void setSequencer(Sequencer sequencer) {
+        this.sequencer = sequencer;
+        // hashcode must include the Sequencer's Sequence so that two 
SequenceNodes
+        // on the same left-input but with different sequences are never 
merged by
+        // the node-sharing mechanism. Recomputed here because setSequencer() 
is
+        // called after construction (in PhreakNodeFactory.buildSequenceNode).
+        this.hashcode = calculateHashCode();
+    }
+
+    public boolean isLeftTupleMemoryEnabled() {
+        return tupleMemoryEnabled;
+    }
+
+    /**
+     * Returns the next node
+     * @return
+     *      The next TupleSinkNode
+     */
+    public LeftTupleSinkNode getNextLeftTupleSinkNode() {
+        return this.nextTupleSinkNode;
+    }
+
+    /**
+     * Sets the next node
+     * @param next
+     *      The next TupleSinkNode
+     */
+    public void setNextLeftTupleSinkNode(final LeftTupleSinkNode next) {
+        this.nextTupleSinkNode = next;
+    }
+
+    /**
+     * Returns the previous node
+     * @return
+     *      The previous TupleSinkNode
+     */
+    public LeftTupleSinkNode getPreviousLeftTupleSinkNode() {
+        return this.previousTupleSinkNode;
+    }
+
+    /**
+     * Sets the previous node
+     * @param previous
+     *      The previous TupleSinkNode
+     */
+    public void setPreviousLeftTupleSinkNode(final LeftTupleSinkNode previous) 
{
+        this.previousTupleSinkNode = previous;
+    }
+
+    public int getType() {
+        return NodeTypeEnums.SequenceNode;
+    }
+
+    public static class SequenceNodeMemory extends 
AbstractLinkedListNode<Memory>
+        implements
+        Externalizable,
+        Memory {
+
+        private static final long serialVersionUID = 510l;
+
+        private TupleMemory       leftTupleMemory;
+
+        private TupleSets         stagedChildTuples;
+
+        private SegmentMemory     memory;
+
+        private LinkedList<DynamicFilter>[] activeFilters;
+
+        private DynamicFilter[] filters;
+
+        private SequenceNode node;
+
+        private long          nodePosMaskBit;
+
+        public SequenceNodeMemory(SequenceNode node, 
LinkedList<DynamicFilter>[] activeFilters, DynamicFilter[] filters) {
+            this.node = node;
+            this.stagedChildTuples = new TupleSetsImpl();
+            this.leftTupleMemory = new TupleList();
+            this.activeFilters = activeFilters;
+            this.filters = filters;
+        }
+
+        public void addActiveFilter(DynamicFilter filter) {
+            int adapterIdx = filter.getAdapterIndex();
+            if (this.activeFilters[adapterIdx] == null) {
+                this.activeFilters[adapterIdx] = new LinkedList<>();
+            }
+            this.activeFilters[adapterIdx].add(filter);
+        }
+
+        public void removeActiveFilter(DynamicFilter filter) {
+            this.activeFilters[filter.getAdapterIndex()].remove(filter);
+        }
+
+        public LinkedList<DynamicFilter>[] getActiveFilters() {
+            return this.activeFilters;
+        }
+
+        public DynamicFilter[] getFilters() {
+            return filters;
+        }
+
+        public void setFilters(DynamicFilter[] filters) {
+            this.filters = filters;
+        }
+
+        public TupleMemory getLeftTupleMemory() {
+            return leftTupleMemory;
+        }
+
+        public TupleSets getStagedChildTuples() {
+            return stagedChildTuples;
+        }
+
+        public SegmentMemory getMemory() {
+            return memory;
+        }
+
+        public void readExternal(ObjectInput in) throws IOException,
+                                                ClassNotFoundException {
+            throw new UnsupportedOperationException("SequenceNodeMemory does 
not support serialization");
+        }
+
+        public void writeExternal(ObjectOutput out) throws IOException {
+            throw new UnsupportedOperationException("SequenceNodeMemory does 
not support serialization");
+        }
+
+        public int getNodeType() {
+            return NodeTypeEnums.SequenceNode;
+        }
+
+        public void setSegmentMemory(SegmentMemory smem) {
+            this.memory = smem;
+        }
+
+        public SegmentMemory getSegmentMemory() {
+            return this.memory;
+        }
+
+        public void reset() { }
+
+        public DynamicFilter getActiveDynamicFilter(int filterIndex) {
+            DynamicFilter filter = filters[filterIndex];
+
+            if (filter == null) {
+                DynamicFilterProto proto = 
node.getDynamicFilters()[filterIndex];
+                filter = new DynamicFilter(proto);
+                filters[filterIndex] = filter;
+                addActiveFilter(filter);
+            } else if (filter.getSignalAdapters().isEmpty()) {
+                // when it's empty, it's  removed from the list of active 
filters, it must be readded.
+                addActiveFilter(filter);
+            }
+
+            return filter;
+        }
+
+        public void setNodePosMaskBit(long nodePosMaskBit) {
+            this.nodePosMaskBit = nodePosMaskBit;
+        }
+
+        public long getNodePosMaskBit() {
+            return nodePosMaskBit;
+        }
+    }
+
+    @Override
+    public ObjectTypeNode getObjectTypeNode() {
+        return leftInput.getObjectTypeNode();
+    }
+
+    protected boolean doRemove(final RuleRemovalContext context,
+                               final ReteooBuilder builder) {
+        return true;
+    }

Review Comment:
   Removing a rule reports this node as removable without detaching it from its 
left input or detaching the `AlphaAdapter`s from their object sources. Unlike 
the other tuple nodes' `doRemove` implementations, this leaves live sinks in 
both networks, so later facts can keep invoking a removed rule and retain its 
graph. Detach both sides when the node is no longer in use, and return false 
while it is shared.



##########
drools-core/src/main/java/org/drools/core/reteoo/SequenceNode.java:
##########
@@ -0,0 +1,573 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.drools.core.reteoo;
+
+import org.drools.base.base.ObjectType;
+import org.drools.base.common.RuleBasePartitionId;
+import org.drools.base.reteoo.DynamicFilter;
+import org.drools.base.reteoo.DynamicFilterProto;
+import org.drools.base.reteoo.NodeTypeEnums;
+import org.drools.base.reteoo.sequencing.Sequence.SequenceMemory;
+import org.drools.base.rule.Pattern;
+import org.drools.core.RuleBaseConfiguration;
+import org.drools.core.common.InternalFactHandle;
+import org.drools.core.common.InternalWorkingMemory;
+import org.drools.core.common.Memory;
+import org.drools.core.common.MemoryFactory;
+import org.drools.core.common.PropagationContext;
+import org.drools.core.common.ReteEvaluator;
+import org.drools.core.common.TupleSets;
+import org.drools.core.common.TupleSetsImpl;
+import org.drools.core.common.UpdateContext;
+import org.drools.core.reteoo.SequenceNode.SequenceNodeMemory;
+import org.drools.core.reteoo.builder.BuildContext;
+import org.drools.base.reteoo.sequencing.Sequencer;
+import org.drools.core.reteoo.sequencing.SequencerMemoryImpl;
+import org.drools.base.reteoo.sequencing.SequencerMemory;
+import org.drools.base.util.AbstractLinkedListNode;
+import org.drools.base.util.LinkedList;
+import org.drools.core.util.index.TupleList;
+import org.drools.util.bitmask.BitMask;
+
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.List;
+
+public class SequenceNode extends LeftTupleSource
+    implements
+    LeftTupleNode,
+    LeftTupleSinkNode,
+    MemoryFactory<SequenceNodeMemory> {
+
+    private static final long      serialVersionUID = 510l;
+
+    protected boolean              tupleMemoryEnabled;
+
+    private Sequencer sequencer;
+
+    private AlphaAdapter[] alphaAdapters;
+
+    private DynamicFilterProto[] dynamicFilters;
+
+    private LeftTupleSinkNode      previousTupleSinkNode;
+
+    private LeftTupleSinkNode      nextTupleSinkNode;
+
+    public SequenceNode() {
+
+    }
+
+    public SequenceNode(final int id,
+                        final LeftTupleSource tupleSource,
+                        final BuildContext context) {
+        super(id, context);
+        setLeftTupleSource(tupleSource);
+        this.tupleMemoryEnabled = context.isTupleMemoryEnabled();
+
+        initMasks(context);
+
+        hashcode = calculateHashCode();
+        setStreamMode(true);
+    }
+
+    public void setAlphaAdapters(AlphaAdapter[] adapters) {
+        this.alphaAdapters = adapters;
+    }
+
+    public DynamicFilterProto[] getDynamicFilters() {
+        return dynamicFilters;
+    }
+
+    public void setDynamicFilters(DynamicFilterProto[] dynamicFilters) {
+        this.dynamicFilters = dynamicFilters;
+    }
+
+    public void doAttach(BuildContext context) {
+        super.doAttach(context);
+        this.leftInput.addTupleSink( this, context );
+    }
+
+    public void networkUpdated(UpdateContext updateContext) {
+        this.leftInput.networkUpdated(updateContext);
+    }
+
+
+    /**
+     * Produce a debug string.
+     *
+     * @return The debug string.
+     */
+    public String toString() {
+        return "[SequenceNode(" + this.id + ")]]";
+    }
+
+    private int calculateHashCode() {
+        int result = this.leftInput.hashCode();
+        if (this.sequencer != null) {
+            result = 31 * result + 
System.identityHashCode(this.sequencer.getSequence());
+        }
+        return result;
+    }
+
+    @Override
+    public boolean equals(final Object object) {
+        if (this == object) {
+            return true;
+        }
+
+        if ( object == null || !(object instanceof SequenceNode) || 
this.hashCode() != object.hashCode() ) {
+            return false;
+        }
+
+        SequenceNode other = (SequenceNode) object;
+        return this.leftInput.getId() == other.leftInput.getId()
+            && this.sequencer.getSequence() == other.sequencer.getSequence();
+    }
+
+    public SequenceNodeMemory createMemory(final RuleBaseConfiguration config, 
ReteEvaluator reteEvaluator) {
+        // activeFilters is indexed by adapter index (one slot per distinct 
object type).
+        // AlphaAdapter.assertObject looks up activeFilters[adapterIndex] to 
dispatch to matching filters.
+        // filters is indexed by pattern/filter index (one slot per step).
+        // The two sizes differ when multiple steps share the same object type.
+        LinkedList<DynamicFilter>[] activeFilters = new 
LinkedList[alphaAdapters.length];
+        SequenceNodeMemory          memory  = new SequenceNodeMemory(this, 
activeFilters, new DynamicFilter[dynamicFilters.length]);
+        return memory;
+    }
+
+    public SequencerMemory createSequencerMemory(TupleImpl lt, LeftTupleSink 
sink, SequenceNodeMemory nodeMemory) {
+        SequencerMemory sequencerMemory = new SequencerMemoryImpl(sequencer, 
lt, sink, this, nodeMemory);
+
+        return sequencerMemory;
+    }
+
+    public Sequencer getSequencer() {
+        return sequencer;
+    }
+
+    public void setSequencer(Sequencer sequencer) {
+        this.sequencer = sequencer;
+        // hashcode must include the Sequencer's Sequence so that two 
SequenceNodes
+        // on the same left-input but with different sequences are never 
merged by
+        // the node-sharing mechanism. Recomputed here because setSequencer() 
is
+        // called after construction (in PhreakNodeFactory.buildSequenceNode).
+        this.hashcode = calculateHashCode();
+    }
+
+    public boolean isLeftTupleMemoryEnabled() {
+        return tupleMemoryEnabled;
+    }
+
+    /**
+     * Returns the next node
+     * @return
+     *      The next TupleSinkNode
+     */
+    public LeftTupleSinkNode getNextLeftTupleSinkNode() {
+        return this.nextTupleSinkNode;
+    }
+
+    /**
+     * Sets the next node
+     * @param next
+     *      The next TupleSinkNode
+     */
+    public void setNextLeftTupleSinkNode(final LeftTupleSinkNode next) {
+        this.nextTupleSinkNode = next;
+    }
+
+    /**
+     * Returns the previous node
+     * @return
+     *      The previous TupleSinkNode
+     */
+    public LeftTupleSinkNode getPreviousLeftTupleSinkNode() {
+        return this.previousTupleSinkNode;
+    }
+
+    /**
+     * Sets the previous node
+     * @param previous
+     *      The previous TupleSinkNode
+     */
+    public void setPreviousLeftTupleSinkNode(final LeftTupleSinkNode previous) 
{
+        this.previousTupleSinkNode = previous;
+    }
+
+    public int getType() {
+        return NodeTypeEnums.SequenceNode;
+    }
+
+    public static class SequenceNodeMemory extends 
AbstractLinkedListNode<Memory>
+        implements
+        Externalizable,
+        Memory {
+
+        private static final long serialVersionUID = 510l;
+
+        private TupleMemory       leftTupleMemory;
+
+        private TupleSets         stagedChildTuples;
+
+        private SegmentMemory     memory;
+
+        private LinkedList<DynamicFilter>[] activeFilters;
+
+        private DynamicFilter[] filters;
+
+        private SequenceNode node;
+
+        private long          nodePosMaskBit;
+
+        public SequenceNodeMemory(SequenceNode node, 
LinkedList<DynamicFilter>[] activeFilters, DynamicFilter[] filters) {
+            this.node = node;
+            this.stagedChildTuples = new TupleSetsImpl();
+            this.leftTupleMemory = new TupleList();
+            this.activeFilters = activeFilters;
+            this.filters = filters;
+        }
+
+        public void addActiveFilter(DynamicFilter filter) {
+            int adapterIdx = filter.getAdapterIndex();
+            if (this.activeFilters[adapterIdx] == null) {
+                this.activeFilters[adapterIdx] = new LinkedList<>();
+            }
+            this.activeFilters[adapterIdx].add(filter);
+        }
+
+        public void removeActiveFilter(DynamicFilter filter) {
+            this.activeFilters[filter.getAdapterIndex()].remove(filter);
+        }
+
+        public LinkedList<DynamicFilter>[] getActiveFilters() {
+            return this.activeFilters;
+        }
+
+        public DynamicFilter[] getFilters() {
+            return filters;
+        }
+
+        public void setFilters(DynamicFilter[] filters) {
+            this.filters = filters;
+        }
+
+        public TupleMemory getLeftTupleMemory() {
+            return leftTupleMemory;
+        }
+
+        public TupleSets getStagedChildTuples() {
+            return stagedChildTuples;
+        }
+
+        public SegmentMemory getMemory() {
+            return memory;
+        }
+
+        public void readExternal(ObjectInput in) throws IOException,
+                                                ClassNotFoundException {
+            throw new UnsupportedOperationException("SequenceNodeMemory does 
not support serialization");
+        }
+
+        public void writeExternal(ObjectOutput out) throws IOException {
+            throw new UnsupportedOperationException("SequenceNodeMemory does 
not support serialization");
+        }
+
+        public int getNodeType() {
+            return NodeTypeEnums.SequenceNode;
+        }
+
+        public void setSegmentMemory(SegmentMemory smem) {
+            this.memory = smem;
+        }
+
+        public SegmentMemory getSegmentMemory() {
+            return this.memory;
+        }
+
+        public void reset() { }
+
+        public DynamicFilter getActiveDynamicFilter(int filterIndex) {
+            DynamicFilter filter = filters[filterIndex];
+
+            if (filter == null) {
+                DynamicFilterProto proto = 
node.getDynamicFilters()[filterIndex];
+                filter = new DynamicFilter(proto);
+                filters[filterIndex] = filter;
+                addActiveFilter(filter);
+            } else if (filter.getSignalAdapters().isEmpty()) {
+                // when it's empty, it's  removed from the list of active 
filters, it must be readded.
+                addActiveFilter(filter);
+            }
+
+            return filter;
+        }
+
+        public void setNodePosMaskBit(long nodePosMaskBit) {
+            this.nodePosMaskBit = nodePosMaskBit;
+        }
+
+        public long getNodePosMaskBit() {
+            return nodePosMaskBit;
+        }
+    }
+
+    @Override
+    public ObjectTypeNode getObjectTypeNode() {
+        return leftInput.getObjectTypeNode();
+    }
+
+    protected boolean doRemove(final RuleRemovalContext context,
+                               final ReteooBuilder builder) {
+        return true;
+    }
+
+
+    public static class AlphaAdapter extends ObjectSource
+            implements
+            ObjectSinkNode,
+            RightTupleSink {
+        private int          adapterIndex;
+
+        private ObjectTypeNodeId otnId;
+
+        private SequenceNode node;
+
+
+        public AlphaAdapter(int id, ObjectSource source, RuleBasePartitionId 
partitionId, SequenceNode node, int adapterIndex) {
+            super(id, source, partitionId);
+            this.adapterIndex = adapterIndex;
+            this.node = node;
+        }
+
+        public void assertObject(final InternalFactHandle factHandle,
+                                 final PropagationContext pctx,
+                                 final ReteEvaluator reteEvaluator) {
+            SequenceNodeMemory memory = reteEvaluator.getNodeMemory(node);
+
+            LinkedList<DynamicFilter> filters       = 
memory.getActiveFilters()[adapterIndex];
+            if (filters != null) {
+                for (DynamicFilter f = filters.getFirst(); f != null; f = 
f.getNext()) {
+                    f.assertObject(factHandle, reteEvaluator);
+                }

Review Comment:
   `f.assertObject` can complete a sequence and remove `f` from this linked 
list, which clears `f.getNext()`. The loop then stops and later active filters 
for the same object type never receive the fact, breaking staggered concurrent 
sequences. Capture the next node before dispatch, as 
`DynamicFilter.assertObject` already does for its mutable adapter list.



##########
drools-base/src/main/java/org/drools/base/reteoo/sequencing/signalprocessors/LogicGate.java:
##########
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.drools.base.reteoo.sequencing.signalprocessors;
+
+import org.drools.base.base.ValueResolver;
+import 
org.drools.base.reteoo.sequencing.signalprocessors.LogicCircuit.LongBiPredicate;
+import org.drools.base.reteoo.sequencing.Sequence.SequenceMemory;
+
+public class LogicGate extends SignalProcessor {
+    protected long allMatched;
+
+    private SignalProcessor output;
+
+    private final LongBiPredicate predicate;
+
+    private final int gateIndex;
+
+    private LogicGate[] inputGates = EMPTY_INPUT_GATES;
+
+    private final int[] filterIndexes;
+
+    private int[] signalAdapterIndexes;
+
+    private static final LogicGate[] EMPTY_INPUT_GATES = new LogicGate[0];
+
+    public LogicGate(LongBiPredicate predicate, int gateIndex, int[] 
filterIndexes, int[] signalAdapterIndexes, int nbrOfInputGates) {
+        this.predicate = predicate;
+
+        this.filterIndexes        = filterIndexes;
+        this.signalAdapterIndexes = signalAdapterIndexes;
+
+        for (int i = 0; i < (signalAdapterIndexes.length + nbrOfInputGates); 
i++) {
+            allMatched = allMatched | (1L << i);
+        }

Review Comment:
   The bit mask can represent at most 64 distinct inputs, but the DSL accepts 
arbitrarily many children and Java shifts wrap modulo 64. A gate with 65 inputs 
aliases inputs 1 and 65 and can match before every child has signalled. Reject 
more than `Long.SIZE` inputs with a descriptive build error, or replace the 
mask with a wider representation.



##########
drools-model/drools-canonical-model/src/main/java/org/drools/model/view/ExistentialExprViewItem.java:
##########
@@ -21,7 +21,7 @@
 import org.drools.model.Condition;
 import org.drools.model.Variable;
 
-public class ExistentialExprViewItem<T> extends AbstractExprViewItem<T> {
+public class ExistentialExprViewItem<T> extends AbstractExprViewItem<T> 
implements org.drools.model.SequenceStep {

Review Comment:
   Marking every existential view item as a `SequenceStep` makes 
`sequence(not(...))` and `sequence(exists(...))` valid at compile time, but 
`KiePackagesBuilder.predicateFor` rejects both condition types. This marker 
therefore advertises combinations the implementation cannot build; remove it 
until existential sequence steps are supported, or add their runtime semantics.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to