This is an automated email from the ASF dual-hosted git repository.
Rikkola pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-kie.git
The following commit(s) were added to refs/heads/main by this push:
new 7cf642b870a Drools Sequence: Named consequence before a later sequence
→ wrong anchor skip (#7262)
7cf642b870a is described below
commit 7cf642b870a4156e9d7c27b52f69c1de250276c2
Author: Toni Rikkola <[email protected]>
AuthorDate: Tue Nov 24 14:39:38 2026 +0200
Drools Sequence: Named consequence before a later sequence → wrong anchor
skip (#7262)
* [incubator-kie#7101] Drools Sequential: Named consequence before a later
sequence → wrong anchor skip
Fix anchor skip for named consequences placed before a later sequence.
Sequence-step variables are read from SequencerMemory anchors found by
walking up from the firing terminal, counting `skip` anchors. The skip was
computed from the rule-wide sequence count, which is only correct for the
default (last) consequence. A named consequence placed before a later
sequence has fewer anchors above it, so the skip overshot and the
consequence failed with "no SequencerMemory anchor found".
Snapshot the number of sequences seen so far when the LHS walk reaches a
named consequence (plain and conditional when/elseWhen branches), and use
that snapshot, keyed by consequence name, when computing the skip.
Assisted-by: IBM Bob
---
.../drools/modelcompiler/KiePackagesBuilder.java | 26 ++--
.../java/org/drools/modelcompiler/RuleContext.java | 28 +---
.../org/drools/modelcompiler/SequenceScope.java | 76 +++++++++++
.../PatternDSLSequenceConsequenceTest.java | 151 +++++++++++++++++++++
.../drools/modelcompiler/SequenceScopeTest.java | 76 +++++++++++
5 files changed, 320 insertions(+), 37 deletions(-)
diff --git
a/drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/KiePackagesBuilder.java
b/drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/KiePackagesBuilder.java
index 75fdbd99f72..57324b4cb56 100644
---
a/drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/KiePackagesBuilder.java
+++
b/drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/KiePackagesBuilder.java
@@ -408,7 +408,7 @@ public class KiePackagesBuilder {
Declaration[] requiredDeclarations =
getRequiredDeclarationsIfPossible( ctx, consequence, name );
boolean enabledTupleOptimization = requiredDeclarations != null &&
requiredDeclarations.length > 0;
- Map<String, int[]> sequenceVarIndexes =
buildSequenceVarIndexesForConsequence( ctx, consequence );
+ Map<String, int[]> sequenceVarIndexes =
buildSequenceVarIndexesForConsequence( ctx, consequence, name );
if ( name.equals( RuleImpl.DEFAULT_CONSEQUENCE_NAME ) ) {
if ("java".equals(consequence.getLanguage())) {
@@ -427,19 +427,16 @@ public class KiePackagesBuilder {
* These variables are not accessible via the activation tuple; they must
be resolved
* from SequencerMemory.getData() at consequence evaluation time.
*/
- private Map<String, int[]> buildSequenceVarIndexesForConsequence(
RuleContext ctx, Consequence consequence ) {
- Map<Variable, int[]> seqIndexes = ctx.getSequenceVarIndexes();
- if (seqIndexes.isEmpty()) {
+ private Map<String, int[]> buildSequenceVarIndexesForConsequence(
RuleContext ctx, Consequence consequence, String name ) {
+ if (!ctx.sequences().hasVariables()) {
return Map.of();
}
- int totalSeqs = ctx.getSequenceCount();
Map<String, int[]> result = null;
for (Variable var : consequence.getDeclarations()) {
- int[] entry = seqIndexes.get(var);
- if (entry != null) {
+ int[] ref = ctx.sequences().variableRef( name, var );
+ if (ref != null) {
if (result == null) result = new java.util.HashMap<>();
- int skip = totalSeqs - 1 - entry[RuleContext.SEQ_VAR_SEQ_IDX];
- result.put(var.getName(), new int[]{ skip,
entry[RuleContext.SEQ_VAR_FILTER_IDX] });
+ result.put(var.getName(), ref);
}
}
return result == null ? Map.of() : result;
@@ -541,7 +538,11 @@ public class KiePackagesBuilder {
case CONSEQUENCE:
if (condition instanceof NamedConsequenceImpl) {
NamedConsequenceImpl consequence = (NamedConsequenceImpl)
condition;
- return consequence.getName().equals(
RuleImpl.DEFAULT_CONSEQUENCE_NAME ) ? null : new NamedConsequence(
consequence.getName(), consequence.isBreaking() );
+ if (!consequence.getName().equals(
RuleImpl.DEFAULT_CONSEQUENCE_NAME )) {
+ ctx.sequences().registerNamedConsequence(
consequence.getName() );
+ return new NamedConsequence( consequence.getName(),
consequence.isBreaking() );
+ }
+ return null;
} else if (condition instanceof
ConditionalNamedConsequenceImpl) {
return buildConditionalConsequence(ctx,
(ConditionalNamedConsequenceImpl) condition);
}
@@ -552,7 +553,7 @@ public class KiePackagesBuilder {
private RuleConditionElement buildSequenceElement(RuleContext ctx,
GroupElement group,
SequenceConditionImpl
condition) {
- final int seqIdx = ctx.nextSeqIndex();
+ final int seqIdx = ctx.sequences().open();
final SequenceConditionImpl sc = condition;
final List<Condition> steps = sc.getSubConditions();
final int n = steps.size();
@@ -713,7 +714,7 @@ public class KiePackagesBuilder {
// fact from SequencerMemory.getData() at rule-fire time.
Variable stepVar = patternImpl.getPatternVariable();
if (stepVar != null) {
- ctx.addSequenceVarIndex(stepVar, seqIdx, filterIdx);
+ ctx.sequences().bindVariable(stepVar, seqIdx, filterIdx);
}
LogicGate leaf = new LogicGate(
Gates::and,
@@ -930,6 +931,7 @@ public class KiePackagesBuilder {
} else {
evalCondition = new EvalCondition(LambdaEvalExpression.EMPTY,
null);
}
+ ctx.sequences().registerNamedConsequence(
consequence.getThenConsequence().getName() );
return new ConditionalBranch( evalCondition,
new NamedConsequence(
consequence.getThenConsequence().getName(),
consequence.getThenConsequence().isBreaking() ),
consequence.getElseBranch() != null ?
buildConditionalConsequence(ctx, consequence.getElseBranch()) : null );
diff --git
a/drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/RuleContext.java
b/drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/RuleContext.java
index 3bf255f8231..2be300e0090 100644
---
a/drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/RuleContext.java
+++
b/drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/RuleContext.java
@@ -39,12 +39,6 @@ import org.drools.model.Variable;
public class RuleContext {
- /** Index into the {@code int[]} stored in {@link #sequenceVarIndexes}:
the sequence index (raw, before skip conversion). */
- static final int SEQ_VAR_SEQ_IDX = 0;
- /** Index into the {@code int[]} stored in {@link #sequenceVarIndexes}:
the filter/step index within that sequence. */
- static final int SEQ_VAR_FILTER_IDX = 1;
-
-
private final KiePackagesBuilder builder;
private final InternalKnowledgePackage pkg;
private final RuleImpl rule;
@@ -54,10 +48,9 @@ public class RuleContext {
private Map<Variable, Declaration> queryDeclarations;
private Map<Variable, Accumulate> accumulateSource;
- private Map<Variable, int[]> sequenceVarIndexes;
+ private final SequenceScope sequences = new SequenceScope();
private int patternIndex = -1;
- private int seqIndex = -1;
private boolean needStreamMode = false;
private Deque<Set<Variable>> variablesInOrCondition;
@@ -87,12 +80,8 @@ public class RuleContext {
return ++patternIndex;
}
- int nextSeqIndex() {
- return ++seqIndex;
- }
-
- int getSequenceCount() {
- return seqIndex + 1;
+ SequenceScope sequences() {
+ return sequences;
}
void startOrCondition() {
@@ -153,17 +142,6 @@ public class RuleContext {
declarations.put( variable, declaration );
}
- void addSequenceVarIndex( Variable variable, int seqIndex, int filterIndex
) {
- if (sequenceVarIndexes == null) {
- sequenceVarIndexes = new HashMap<>();
- }
- sequenceVarIndexes.put( variable, new int[]{ seqIndex, filterIndex } );
- }
-
- Map<Variable, int[]> getSequenceVarIndexes() {
- return sequenceVarIndexes == null ? Map.of() : sequenceVarIndexes;
- }
-
void addGroupByDeclaration( Variable groupKeyVar, Declaration declaration
) {
addDeclaration( groupKeyVar, declaration );
}
diff --git
a/drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/SequenceScope.java
b/drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/SequenceScope.java
new file mode 100644
index 00000000000..f06fba562c2
--- /dev/null
+++
b/drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/SequenceScope.java
@@ -0,0 +1,76 @@
+/*
+ * 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.HashMap;
+import java.util.Map;
+
+import org.drools.base.definitions.rule.impl.RuleImpl;
+import org.drools.model.Variable;
+
+/**
+ * Build-time bookkeeping for the {@code sequence(...)} calls of one rule:
where each step variable was
+ * bound, and how many sequences precede each named consequence. Together
these give the number of
+ * SequencerMemory anchors a consequence must walk back to reach a variable's
sequence.
+ */
+class SequenceScope {
+
+ private record FilterPosition( int sequence, int filter ) { }
+
+ private final Map<Variable, FilterPosition> filterPositions = new
HashMap<>();
+ private final Map<String, Integer> sequencesBeforeConsequence = new
HashMap<>();
+ private int sequenceCount = 0;
+
+ int open() {
+ return sequenceCount++;
+ }
+
+ void bindVariable( Variable variable, int sequence, int filter ) {
+ filterPositions.put( variable, new FilterPosition( sequence, filter )
);
+ }
+
+ void registerNamedConsequence( String name ) {
+ if (!RuleImpl.DEFAULT_CONSEQUENCE_NAME.equals( name )) {
+ sequencesBeforeConsequence.put( name, sequenceCount );
+ }
+ }
+
+ boolean hasVariables() {
+ return !filterPositions.isEmpty();
+ }
+
+ int[] variableRef( String consequenceName, Variable variable ) {
+ FilterPosition position = filterPositions.get( variable );
+ if (position == null) {
+ return null;
+ }
+ return new int[]{ sequencesInScope( consequenceName ) - 1 -
position.sequence(), position.filter() };
+ }
+
+ private int sequencesInScope( String consequenceName ) {
+ if (RuleImpl.DEFAULT_CONSEQUENCE_NAME.equals( consequenceName )) {
+ return sequenceCount;
+ }
+ Integer registered = sequencesBeforeConsequence.get( consequenceName );
+ if (registered == null) {
+ throw new IllegalStateException( "Named consequence '" +
consequenceName + "' was not registered with the sequence scope" );
+ }
+ return registered;
+ }
+}
diff --git
a/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PatternDSLSequenceConsequenceTest.java
b/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PatternDSLSequenceConsequenceTest.java
index 29022008775..3b0061d2893 100644
---
a/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PatternDSLSequenceConsequenceTest.java
+++
b/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PatternDSLSequenceConsequenceTest.java
@@ -614,4 +614,155 @@ public class PatternDSLSequenceConsequenceTest {
assertThat(results).containsExactly("alarm:high");
}
+
+ @Test
+ public void namedConsequenceBetweenTwoSequencesResolvesStepVariable() {
+ Variable<Person> personV = declarationOf(Person.class);
+ Variable<Toy> toyV = declarationOf(Toy.class);
+ Variable<Relationship> relV = declarationOf(Relationship.class);
+
+ Rule rule = rule("named-consequence-between-sequences").build(
+ pattern(personV),
+ sequence(
+ pattern(toyV).expr("is-ball", t ->
t.getName().equals("ball"))
+ ),
+ when("always", personV, p -> true).then(
+ on(toyV).breaking().execute(t -> results.add("named:"
+ t.getName()))
+ ),
+ sequence(
+ pattern(relV).expr("is-go", r ->
r.getStart().equals("go"))
+ ),
+ on(toyV, relV).execute((t, r) -> results.add("final:" +
t.getName() + "+" + r.getStart()))
+ );
+
+ KieBase kbase = KieBaseBuilder.createKieBaseFromModel(new
ModelImpl().addRule(rule));
+ ksession = kbase.newKieSession();
+
+ insertAndFire(new Person("alice"));
+ insertAndFire(new Toy("ball"));
+
+ assertThat(results).as("named consequence after first sequence must
resolve step variable without anchor skip error")
+ .containsExactly("named:ball");
+ }
+
+ @Test
+ public void
nonBreakingNamedConsequenceBetweenTwoSequencesThenFinalConsequenceFires() {
+ Variable<Person> personV = declarationOf(Person.class);
+ Variable<Toy> toyV = declarationOf(Toy.class);
+ Variable<Relationship> relV = declarationOf(Relationship.class);
+
+ Rule rule =
rule("non-breaking-named-consequence-between-sequences").build(
+ pattern(personV),
+ sequence(
+ pattern(toyV).expr("is-ball", t ->
t.getName().equals("ball"))
+ ),
+ when("always", personV, p -> true).then(
+ on(toyV).execute(t -> results.add("named:" +
t.getName()))
+ ),
+ sequence(
+ pattern(relV).expr("is-go", r ->
r.getStart().equals("go"))
+ ),
+ on(toyV, relV).execute((t, r) -> results.add("final:" +
t.getName() + "+" + r.getStart()))
+ );
+
+ KieBase kbase = KieBaseBuilder.createKieBaseFromModel(new
ModelImpl().addRule(rule));
+ ksession = kbase.newKieSession();
+
+ insertAndFire(new Person("alice"));
+ insertAndFire(new Toy("ball"));
+ insertAndFire(new Relationship("go", "done"));
+
+ assertThat(results).containsExactly("named:ball", "final:ball+go");
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {5, 20, 50})
+ public void
threeLevelConditionalBetweenTwoSequencesResolvesStepVariableInEveryBranch(int
age) {
+ Variable<Person> personV = declarationOf(Person.class);
+ Variable<Toy> toyV = declarationOf(Toy.class);
+ Variable<Relationship> relV = declarationOf(Relationship.class);
+
+ Rule rule = rule("three-level-conditional-between-sequences-" +
age).build(
+ pattern(personV),
+ sequence(
+ pattern(toyV).expr("is-ball", t ->
t.getName().equals("ball"))
+ ),
+ when("young", personV, p -> p.getAge() < 10).then(
+ on(toyV).breaking().execute(t -> results.add("first:"
+ t.getName()))
+ ).elseWhen("middle", personV, p -> p.getAge() < 30).then(
+ on(toyV).breaking().execute(t -> results.add("second:"
+ t.getName()))
+ ).elseWhen().then(
+ on(toyV).breaking().execute(t -> results.add("third:"
+ t.getName()))
+ ),
+ sequence(
+ pattern(relV).expr("is-go", r ->
r.getStart().equals("go"))
+ ),
+ on(toyV, relV).execute((t, r) -> results.add("final:" +
t.getName() + "+" + r.getStart()))
+ );
+
+ KieBase kbase = KieBaseBuilder.createKieBaseFromModel(new
ModelImpl().addRule(rule));
+ ksession = kbase.newKieSession();
+
+ insertAndFire(new Person("alice", age));
+ insertAndFire(new Toy("ball"));
+
+ String expected = age < 10 ? "first:ball" : age < 30 ? "second:ball" :
"third:ball";
+ assertThat(results).containsExactly(expected);
+ }
+
+ @Test
+ public void plainNamedConsequenceBetweenTwoSequencesResolvesStepVariable()
{
+ Variable<Person> personV = declarationOf(Person.class);
+ Variable<Toy> toyV = declarationOf(Toy.class);
+ Variable<Relationship> relV = declarationOf(Relationship.class);
+
+ Rule rule = rule("plain-named-consequence-between-sequences").build(
+ pattern(personV),
+ sequence(
+ pattern(toyV).expr("is-ball", t ->
t.getName().equals("ball"))
+ ),
+ on(toyV).execute(t -> results.add("named:" + t.getName())),
+ sequence(
+ pattern(relV).expr("is-go", r ->
r.getStart().equals("go"))
+ ),
+ on(toyV, relV).execute((t, r) -> results.add("final:" +
t.getName() + "+" + r.getStart()))
+ );
+
+ KieBase kbase = KieBaseBuilder.createKieBaseFromModel(new
ModelImpl().addRule(rule));
+ ksession = kbase.newKieSession();
+
+ insertAndFire(new Person("alice"));
+ insertAndFire(new Toy("ball"));
+ insertAndFire(new Relationship("go", "done"));
+
+ assertThat(results).containsExactly("named:ball", "final:ball+go");
+ }
+
+ @Test
+ public void plainNamedConsequenceFiresBeforeSecondSequenceIsSatisfied() {
+ Variable<Person> personV = declarationOf(Person.class);
+ Variable<Toy> toyV = declarationOf(Toy.class);
+ Variable<Relationship> relV = declarationOf(Relationship.class);
+
+ Rule rule =
rule("plain-named-consequence-before-second-sequence").build(
+ pattern(personV),
+ sequence(
+ pattern(toyV).expr("is-ball", t ->
t.getName().equals("ball"))
+ ),
+ on(toyV).execute(t -> results.add("named:" + t.getName())),
+ sequence(
+ pattern(relV).expr("is-go", r ->
r.getStart().equals("go"))
+ ),
+ on(toyV, relV).execute((t, r) -> results.add("final:" +
t.getName() + "+" + r.getStart()))
+ );
+
+ KieBase kbase = KieBaseBuilder.createKieBaseFromModel(new
ModelImpl().addRule(rule));
+ ksession = kbase.newKieSession();
+
+ insertAndFire(new Person("alice"));
+ insertAndFire(new Toy("ball"));
+
+ assertThat(results).as("plain named consequence must resolve step
variable when firing before second sequence")
+ .containsExactly("named:ball");
+ }
}
diff --git
a/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/SequenceScopeTest.java
b/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/SequenceScopeTest.java
new file mode 100644
index 00000000000..6e49d037395
--- /dev/null
+++
b/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/SequenceScopeTest.java
@@ -0,0 +1,76 @@
+/*
+ * 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 org.drools.model.Variable;
+import org.drools.model.impl.RuleImpl;
+import org.drools.modelcompiler.domain.Toy;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.drools.model.DSL.declarationOf;
+
+public class SequenceScopeTest {
+
+ private final Variable<Toy> toyV = declarationOf(Toy.class);
+
+ @Test
+ public void defaultConsequenceUsesTotalSequenceCount() {
+ SequenceScope scope = new SequenceScope();
+ int first = scope.open();
+ scope.bindVariable(toyV, first, 0);
+ scope.open();
+
+ // two sequences open, variable in the first: skip one anchor
+ assertThat(scope.variableRef(RuleImpl.DEFAULT_CONSEQUENCE_NAME,
toyV)).containsExactly(1, 0);
+ }
+
+ @Test
+ public void registeredNamedConsequenceUsesSnapshotTakenAtRegistration() {
+ SequenceScope scope = new SequenceScope();
+ int first = scope.open();
+ scope.bindVariable(toyV, first, 0);
+ scope.registerNamedConsequence("named");
+ scope.open();
+
+ // only one sequence precedes "named": no anchor to skip
+ assertThat(scope.variableRef("named", toyV)).containsExactly(0, 0);
+ }
+
+ @Test
+ public void
unregisteredNamedConsequenceIsRejectedInsteadOfFallingBackToTotal() {
+ SequenceScope scope = new SequenceScope();
+ int first = scope.open();
+ scope.bindVariable(toyV, first, 0);
+ scope.open();
+
+ assertThatThrownBy(() -> scope.variableRef("never-registered", toyV))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("never-registered");
+ }
+
+ @Test
+ public void
nonSequenceVariableIsNotResolvedEvenForUnregisteredConsequence() {
+ SequenceScope scope = new SequenceScope();
+ scope.open();
+
+ assertThat(scope.variableRef("never-registered", toyV)).isNull();
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]