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


##########
drools-core/src/main/java/org/drools/core/reteoo/SequenceNode.java:
##########
@@ -337,17 +341,57 @@ public AlphaAdapter(int id, ObjectSource source, 
RuleBasePartitionId partitionId
             this.node = node;
         }
 
+        /**
+         * Delivers a newly inserted fact to every active filter registered 
for this adapter's
+         * object-type index.
+         *
+         * <h3>Snapshot walk</h3>
+         * Delivering a fact to a filter can cause an anchor to advance or be 
reset. Advancing
+         * deactivates the current step and activates the next, which removes 
the filter for
+         * the current step from the live {@code activeFilters} list (its 
signal-adapter list
+         * becomes empty) and possibly inserts a new filter for the next step. 
Walking the live
+         * list directly would therefore stop prematurely and skip filters for 
sequences that are
+         * still at the same step; a later snapshot entry whose adapters were 
removed by an
+         * earlier entry's delivery is detected and skipped via {@code 
isEmpty()}.
+         *
+         * <h3>Single-thread invariant</h3>
+         * This method runs entirely on the engine's working-memory thread. 
Agenda rules fire
+         * only after propagation is complete: in the normal {@code 
fireAllRules} path the
+         * propagation queue is flushed before each rule fires, and {@code 
flushPropagations()}
+         * is called again after each {@link 
org.drools.core.phreak.RuleExecutor#fireActivation}
+         * returns. There is therefore no preemption window in which another 
rule could fire
+         * between the snapshot copy and the per-filter loop — the {@code 
isEmpty()} guard
+         * covers only <em>within-delivery</em> deactivation caused by an 
earlier filter in the
+         * same loop iteration, not any form of agenda interleaving.
+         *
+         * <h3>New adapters registered during delivery</h3>
+         * If an anchor advances while this loop is running, a new signal 
adapter may be
+         * registered on a later snapshot entry. The shared {@link 
DeliveryClock} stamps that
+         * adapter with the current epoch, which is equal to the delivery 
start epoch, so
+         * {@link DynamicFilter#assertObject} skips it — the advancing fact is 
not delivered to
+         * the step it just unlocked.
+         */
         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; ) {
-                    DynamicFilter next = f.getNext();
-                    f.assertObject(factHandle, reteEvaluator);
-                    f = next;
+            if (filters != null && !filters.isEmpty()) {
+                int n = filters.size();
+                DynamicFilter[] snapshot = new DynamicFilter[n];
+                int i = 0;
+                for (DynamicFilter f = filters.getFirst(); f != null; f = 
f.getNext()) {
+                    snapshot[i++] = f;
+                }
+                for (int j = 0; j < n; j++) {
+                    // An earlier filter in this loop may have advanced or 
reset an anchor,
+                    // deactivating this filter's step and emptying its 
signal-adapter list.
+                    // Skip it; DynamicFilter.assertObject would be a no-op 
anyway, but the
+                    // check makes the intent explicit and avoids the 
clock.beginDelivery call.
+                    if (!snapshot[j].getSignalAdapters().isEmpty()) {
+                        snapshot[j].assertObject(factHandle, reteEvaluator);
+                    }
                 }
             }

Review Comment:
   This creates a new `DynamicFilter[]` snapshot on every `assertObject` call. 
Since this method can be very hot in large sessions, consider reducing 
per-delivery allocations (e.g., fast-path when `filters.size() == 1`, or 
store/reuse a buffer on `SequenceNodeMemory` sized to the max observed list 
length). This is optional, but could noticeably reduce GC pressure.



##########
drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PatternDSLSequenceLifecycleTest.java:
##########
@@ -269,6 +273,150 @@ public void removedRuleNoLongerReceivesStepEvents() {
                 .isEmpty();
     }
 
+    /**
+     * Updating a consumed step fact must be a no-op for the sequencer 
regardless of the
+     * KieBaseMutabilityOption setting.
+     *
+     * With DISABLED, a fact whose tuples were all retracted is disconnected 
from the object store.
+     * NamedEntryPoint.update() then re-inserts the same handle object 
(reconnect returns null).
+     * DeliveryClock.beginDelivery uses reference identity: if another fact 
was delivered since the
+     * original insert, currentFact changed, so the re-insertion opens a new 
epoch and a signal
+     * adapter registered for the next step (during the original delivery) now 
looks pre-existing —
+     * the sequencer incorrectly fires.
+     *
+     * Control: no intervening fact → currentFact is still the ball handle → 
no new epoch → no firing.
+     * Bug case: intervening "other" toy delivered → currentFact changed → new 
epoch on update → fires.
+     */
+    @Test
+    public void 
updateConsumedStepFactWithInterveningDelivery_disabled_isNoOp() {
+        Variable<Person> personV = declarationOf(Person.class);
+        Variable<Toy>    stepOne = declarationOf(Toy.class);
+        Variable<Toy>    stepTwo = declarationOf(Toy.class);
+
+        Rule rule = rule("update-consumed-disabled").build(
+                pattern(personV),
+                sequence(
+                        pattern(stepOne).expr("is-ball", t -> 
t.getName().equals("ball")),
+                        pattern(stepTwo).expr("is-ball2", t -> 
t.getName().equals("ball"))
+                ),
+                execute(() -> results.add("fired"))
+        );
+
+        KieBaseConfiguration kieBaseConf = 
KieServices.get().newKieBaseConfiguration();
+        kieBaseConf.setOption(KieBaseMutabilityOption.DISABLED);
+        Model model = new ModelImpl().addRule(rule);
+        ksession = KieBaseBuilder.createKieBaseFromModel(model, 
kieBaseConf).newKieSession();
+
+        ksession.insert(new Person("anchor"));
+        ksession.fireAllRules();
+
+        Toy ball = new Toy("ball");
+        FactHandle ballHandle = ksession.insert(ball);
+        ksession.fireAllRules();                    // step-1 consumed; 
sequence now at step-2
+
+        // Deliver an intervening fact so that DeliveryClock.currentFact is no 
longer the ball handle.
+        ksession.insert(new Toy("other"));          // does NOT match either 
step
+        ksession.fireAllRules();
+
+        // Update the step-1 fact — must be a no-op for the sequencer.
+        ksession.update(ballHandle, ball);
+        ksession.fireAllRules();
+
+        assertThat(results)
+                .as("update() of a consumed step fact must not advance the 
sequence, " +
+                    "regardless of KieBaseMutabilityOption or what was 
delivered in between")
+                .isEmpty();
+    }
+
+    /** Control for the above: without an intervening delivery the same 
scenario must also produce 0 firings. */
+    @Test
+    public void 
updateConsumedStepFactWithoutInterveningDelivery_disabled_isNoOp() {
+        Variable<Person> personV = declarationOf(Person.class);
+        Variable<Toy>    stepOne = declarationOf(Toy.class);
+        Variable<Toy>    stepTwo = declarationOf(Toy.class);
+
+        Rule rule = rule("update-consumed-disabled-control").build(
+                pattern(personV),
+                sequence(
+                        pattern(stepOne).expr("is-ball", t -> 
t.getName().equals("ball")),
+                        pattern(stepTwo).expr("is-ball2", t -> 
t.getName().equals("ball"))
+                ),
+                execute(() -> results.add("fired"))
+        );
+
+        KieBaseConfiguration kieBaseConf = 
KieServices.get().newKieBaseConfiguration();
+        kieBaseConf.setOption(KieBaseMutabilityOption.DISABLED);
+        Model model = new ModelImpl().addRule(rule);
+        ksession = KieBaseBuilder.createKieBaseFromModel(model, 
kieBaseConf).newKieSession();
+
+        ksession.insert(new Person("anchor"));
+        ksession.fireAllRules();
+
+        Toy ball = new Toy("ball");
+        FactHandle ballHandle = ksession.insert(ball);
+        ksession.fireAllRules();                    // step-1 consumed; 
sequence now at step-2
+
+        // No intervening delivery; currentFact is still the ball handle.
+        ksession.update(ballHandle, ball);
+        ksession.fireAllRules();
+
+        assertThat(results)
+                .as("update() of a consumed step fact with no intervening 
delivery must not advance the sequence")
+                .isEmpty();
+    }
+
+    /**
+     * A pooled session is reset() on dispose, which restarts fact-handle IDs 
from the same value
+     * but must leave the sequence node with no memory of the previous run. 
Replaying exactly the
+     * same insert script on the recycled session must therefore fire the 
sequence again.
+     *
+     * Regression guard: SequenceNodeMemory.reset() must also reset its 
DeliveryClock. Otherwise the
+     * clock keeps its currentFactId and epoch, and after the ID counter 
restarts the first post-reset
+     * step fact (same ID as the last pre-reset delivered fact) is treated as 
already in flight and
+     * skipped.
+     */
+    @Test
+    public void sequenceFiresAgainWhenPooledSessionIsResetAndScriptReplayed() {
+        Variable<Person> personV = declarationOf(Person.class);
+        Variable<Toy>    toyV    = declarationOf(Toy.class);
+
+        Rule rule = rule("pooled-reset-replay").build(
+                pattern(personV),
+                sequence(
+                        pattern(toyV).expr("is-ball", t -> 
t.getName().equals("ball"))
+                ),
+                execute(() -> results.add("fired"))
+        );
+
+        KieBase kieBase = KieBaseBuilder.createKieBaseFromModel(new 
ModelImpl().addRule(rule));
+        KieSessionsPool pool = kieBase.newKieSessionsPool(1);
+        try {
+            // Run 1: complete the sequence on a fresh pooled session.
+            KieSession first = pool.newKieSession();
+            first.insert(new Person("anchor"));
+            first.fireAllRules();
+            first.insert(new Toy("ball"));
+            first.fireAllRules();
+            assertThat(results).as("control: first run on a fresh session 
fires").containsExactly("fired");
+            first.dispose();                        // returns to the pool -> 
StatefulKnowledgeSessionImpl.reset()

Review Comment:
   If an assertion fails before `first.dispose()`, the pooled session may not 
be returned/reset, which can cascade into confusing failures in later tests. 
Wrap `first` in its own `try/finally` (or use try-with-resources if supported) 
to guarantee `dispose()` even on test failure.



##########
drools-base/src/test/java/org/drools/base/reteoo/DynamicFilterTest.java:
##########
@@ -0,0 +1,292 @@
+/*
+ * 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 java.lang.reflect.Field;
+
+import org.drools.base.base.ValueResolver;
+import org.drools.base.rule.Declaration;
+import org.drools.base.rule.constraint.NegConstraint;
+import org.junit.Test;
+import org.kie.api.runtime.rule.FactHandle;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+public class DynamicFilterTest {
+
+    @Test
+    public void adapterRegisteredBeforeEpochCounterWrapsStillReceivesSignal() 
throws Exception {
+        // NegConstraint(false) allows any non-negated handle and has no 
required declarations (alpha path).
+        DeliveryClock clock = new DeliveryClock();
+        DynamicFilter filter = new DynamicFilter(new DynamicFilterProto(new 
NegConstraint(false), 0), clock);
+
+        // Put the delivery epoch counter on the edge of overflow, as after 
~2^31 deliveries on one node.
+        setEpoch(clock, Integer.MAX_VALUE);
+
+        RecordingSignalAdapter adapter = new RecordingSignalAdapter();
+        filter.addSignalAdapter(adapter);
+
+        // This assertObject increments the epoch counter past 
Integer.MAX_VALUE.
+        filter.assertObject(new TestFactHandle(), null);
+
+        assertThat(adapter.received)
+                .as("a live adapter must still receive the signal when the 
delivery epoch counter wraps")
+                .isEqualTo(1);
+    }
+
+    @Test
+    public void 
adapterRegisteredBeforeEpochCounterWrapsAtLongMaxStillReceivesSignal() throws 
Exception {
+        // Same invariant as the Integer.MAX_VALUE test but exercising the 
true long wrap:
+        // epoch overflows Long.MAX_VALUE → Long.MIN_VALUE, making startEpoch 
negative.
+        // A pre-existing adapter has registrationEpoch == Long.MAX_VALUE; the 
guard
+        //   registrationEpoch >= startEpoch  →  Long.MAX_VALUE >= 
Long.MIN_VALUE  →  true
+        // must NOT fire: the adapter was registered before the delivery, so 
it must receive.
+        DeliveryClock clock = new DeliveryClock();
+        DynamicFilter filter = new DynamicFilter(new DynamicFilterProto(new 
NegConstraint(false), 0), clock);
+
+        // Seed at Long.MAX_VALUE - 1 so the first assertObject increments to 
Long.MAX_VALUE
+        // (registrationEpoch of the adapter) and the second assertObject 
wraps to Long.MIN_VALUE.
+        setEpoch(clock, Long.MAX_VALUE - 1);
+
+        // First delivery: epoch becomes Long.MAX_VALUE.
+        filter.assertObject(new TestFactHandle(), null);
+
+        // Register the adapter while epoch == Long.MAX_VALUE.
+        RecordingSignalAdapter adapter = new RecordingSignalAdapter();
+        filter.addSignalAdapter(adapter);
+
+        // Second delivery: epoch wraps to Long.MIN_VALUE; startEpoch == 
Long.MIN_VALUE.
+        // The adapter's registrationEpoch == Long.MAX_VALUE, which is > 
Long.MIN_VALUE,
+        // so the guard fires and the adapter is skipped — this is the bug 
under test.
+        filter.assertObject(new TestFactHandle(), null);
+
+        assertThat(adapter.received)
+                .as("a live adapter must still receive the signal when the 
delivery epoch counter wraps at Long.MAX_VALUE")
+                .isEqualTo(1);
+    }
+
+    @Test
+    public void 
nonBetaConstraintWithRequiredDeclarationsFailsWithExplanatoryException() {
+        // A constraint that is NOT a BetaConstraint but reports required 
declarations: test() must fail
+        // with a clear IllegalStateException rather than a bare 
ClassCastException.
+        NegConstraint nonBetaWithDeclarations = new NegConstraint(false) {
+            @Override
+            public Declaration[] getRequiredDeclarations() {
+                return new Declaration[]{new Declaration("var", null, null)};
+            }
+        };
+        DynamicFilter filter = new DynamicFilter(new 
DynamicFilterProto(nonBetaWithDeclarations, 0), new DeliveryClock());
+        filter.addSignalAdapter(new RecordingSignalAdapter());
+
+        assertThatThrownBy(() -> filter.assertObject(new TestFactHandle(), 
null))
+                .isInstanceOf(IllegalStateException.class)
+                .hasMessageContaining("non-beta constraint");
+    }
+
+    @Test
+    public void 
filterDeactivatedByEarlierSnapshotEntryIsSkippedWithinDelivery() {
+        // Scenario: two filters on the same adapter (same object type), 
representing two
+        // different active sequences waiting at the same step. When the fact 
arrives:
+        //   1. Filter A receives it and, as a side-effect, removes all signal 
adapters from
+        //      filter B (simulating a step advance or reset that deactivates 
filter B's step).
+        //   2. The snapshot walk must detect isEmpty() on filter B and skip 
it entirely.
+        //
+        // This is the within-delivery deactivation case that isEmpty() was 
designed for.
+        // It is distinct from agenda interleaving, which cannot occur on the 
single engine thread.
+        DeliveryClock clock = new DeliveryClock();
+        DynamicFilter filterA = new DynamicFilter(new DynamicFilterProto(new 
NegConstraint(false), 0), clock);
+        DynamicFilter filterB = new DynamicFilter(new DynamicFilterProto(new 
NegConstraint(false), 0), clock);
+
+        RecordingSignalAdapter adapterB = new RecordingSignalAdapter();
+        filterB.addSignalAdapter(adapterB);
+
+        // adapterA's receive() empties filterB's adapter list (simulates a 
step transition).
+        RecordingSignalAdapter adapterA = new RecordingSignalAdapter() {
+            @Override
+            public void receive(ValueResolver reteEvaluator, FactHandle 
factHandle) {
+                super.receive(reteEvaluator, factHandle);
+                filterB.removeSignalAdapter(adapterB);
+            }
+        };
+        filterA.addSignalAdapter(adapterA);
+
+        // Simulate the snapshot loop in AlphaAdapter.assertObject: deliver to 
filterA first,
+        // then to filterB — but only if its adapter list is non-empty.
+        TestFactHandle fact = new TestFactHandle();
+        clock.beginDelivery(fact);
+        filterA.assertObject(fact, null);
+        if (!filterB.getSignalAdapters().isEmpty()) {
+            filterB.assertObject(fact, null);
+        }
+
+        assertThat(adapterA.received).isEqualTo(1);
+        assertThat(adapterB.received)
+                .as("filter B was deactivated by filter A's delivery; it must 
be skipped")
+                .isZero();
+    }
+
+    @Test
+    public void 
adapterRegisteredWhileFactIsInFlightDoesNotReceiveItOnAnotherFilterOfTheSameClock()
 {
+        // Two filters share one clock, as filters of different object-type 
adapters of one sequence node do.
+        // The fact is delivered to filter A, which registers an adapter on 
filter B; B then handles the same
+        // fact and must not hand it to that adapter.
+        DeliveryClock clock = new DeliveryClock();
+        DynamicFilter filterA = new DynamicFilter(new DynamicFilterProto(new 
NegConstraint(false), 0), clock);
+        DynamicFilter filterB = new DynamicFilter(new DynamicFilterProto(new 
NegConstraint(false), 1), clock);
+        RecordingSignalAdapter lateAdapter = new RecordingSignalAdapter();
+        RecordingSignalAdapter registrar = new RecordingSignalAdapter() {
+            @Override
+            public void receive(ValueResolver reteEvaluator, FactHandle 
factHandle) {
+                super.receive(reteEvaluator, factHandle);
+                filterB.addSignalAdapter(lateAdapter);
+            }
+        };
+        filterA.addSignalAdapter(registrar);
+
+        TestFactHandle fact = new TestFactHandle();
+        filterA.assertObject(fact, null);
+        filterB.assertObject(fact, null);
+
+        assertThat(registrar.received).isEqualTo(1);
+        assertThat(lateAdapter.received)
+                .as("an adapter registered while the fact is in flight must 
not receive that same fact")
+                .isZero();
+
+        filterB.assertObject(new TestFactHandle(), null);
+        assertThat(lateAdapter.received)
+                .as("the same adapter receives the next fact")
+                .isEqualTo(1);
+    }
+
+    @Test
+    public void 
adapterRegisteredDuringDeliveryDoesNotReceiveSameHandleOnRedelivery() {
+        // Simulates the KieBaseMutabilityOption.DISABLED re-insert scenario:
+        // a handle that consumed step-1 (advancing the sequence and 
registering the step-2 adapter)
+        // is re-inserted in a later propagation pass. The step-2 adapter must 
not fire on it.
+        DeliveryClock clock = new DeliveryClock();
+        DynamicFilter step1Filter = new DynamicFilter(new 
DynamicFilterProto(new NegConstraint(false), 0), clock);
+        DynamicFilter step2Filter = new DynamicFilter(new 
DynamicFilterProto(new NegConstraint(false), 0), clock);
+
+        RecordingSignalAdapter step2Adapter = new RecordingSignalAdapter();
+
+        // step1Adapter: when it receives the first ball, registers 
step2Adapter (simulates step advance).
+        RecordingSignalAdapter step1Adapter = new RecordingSignalAdapter() {
+            @Override
+            public void receive(ValueResolver reteEvaluator, FactHandle 
factHandle) {
+                super.receive(reteEvaluator, factHandle);
+                step2Filter.addSignalAdapter(step2Adapter);
+            }
+        };
+        step1Filter.addSignalAdapter(step1Adapter);
+
+        // First delivery of "ball": step1 consumed, step2 adapter registered.
+        TestFactHandle ball = new TestFactHandle();
+        step1Filter.assertObject(ball, null);
+
+        assertThat(step1Adapter.received).isEqualTo(1);
+        assertThat(step2Adapter.received).as("step-2 must not fire during 
step-1 delivery").isZero();
+
+        // Deliver an intervening fact so that DeliveryClock no longer tracks 
ball as the current fact.
+        // (With NegConstraint(false) the constraint accepts everything, so 
other advances step2 once.)
+        step2Filter.assertObject(new TestFactHandle(), null);
+        assertThat(step2Adapter.received).as("other fact advances step-2 
once").isEqualTo(1);
+
+        // Re-delivery of ball (simulates KieBaseMutabilityOption.DISABLED 
re-insert after update).
+        step2Filter.assertObject(ball, null);
+
+        assertThat(step2Adapter.received)
+                .as("re-delivery of the handle that advanced step-1 must not 
fire step-2 again")
+                .isEqualTo(1);   // must NOT have incremented
+
+        // A genuinely new fact (different handle, same type) must still be 
delivered.
+        step2Filter.assertObject(new TestFactHandle(), null);
+        assertThat(step2Adapter.received)
+                .as("a new fact must still be delivered to the step-2 adapter")
+                .isEqualTo(2);
+    }
+
+    @Test
+    public void adapterRegisteredAfterClockResetReceivesHandleWithRecycledId() 
{
+        // Session.reset() restarts handle IDs while the node memory is reset 
in place.
+        // A stale currentFactId in the clock must not make the first 
post-reset fact look "in flight".
+        DeliveryClock clock = new DeliveryClock();
+        DynamicFilter filter = new DynamicFilter(new DynamicFilterProto(new 
NegConstraint(false), 0), clock);
+
+        filter.addSignalAdapter(new RecordingSignalAdapter());
+        filter.assertObject(new TestFactHandle(5), null);          // last 
pre-reset delivery, id 5
+
+        clock.reset();
+
+        RecordingSignalAdapter adapter = new RecordingSignalAdapter();
+        filter.addSignalAdapter(adapter);                           // anchor 
re-registers after reset
+        filter.assertObject(new TestFactHandle(5), null);          // IDs 
restarted: new fact reuses id 5
+
+        assertThat(adapter.received)
+                .as("a fact whose ID equals the last pre-reset delivery must 
reach an adapter registered after reset")
+                .isEqualTo(1);
+    }
+
+    private static void setEpoch(DeliveryClock clock, long value) throws 
Exception {
+        Field field = DeliveryClock.class.getDeclaredField("epoch");
+        field.setAccessible(true);
+        field.setLong(clock, value);
+    }

Review Comment:
   This test relies on reflective access to `DeliveryClock.epoch`, which is 
brittle and may break under stronger module encapsulation or future refactors. 
Consider adding a package-private test hook on `DeliveryClock` (e.g., a 
constructor or setter visible only within the package) to set the epoch 
deterministically without reflection.



-- 
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