Skip to content

Commit 9e5c95c

Browse files
authored
Merge pull request #360 from konlue/feat/issue273-subflow-recursion-boundary
fix(workflow): detect subflow reference cycles at publish and bound the run call chain (issue #273)
2 parents 9b37ba4 + 1bf59d2 commit 9e5c95c

5 files changed

Lines changed: 454 additions & 3 deletions

File tree

‎argi-orchestration/argi-workflow-core/src/main/java/io/github/agentic/ai/workflow/WorkflowAgent.java‎

Lines changed: 61 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ public final class WorkflowAgent implements Agent {
6161

6262
private final ObjectMapper mapper;
6363

64+
private final int subflowMaxDepth;
65+
6466
private final Map<String, StoredContinuation> continuations = new ConcurrentHashMap<>();
6567

6668
private WorkflowAgent(Builder builder) {
@@ -70,6 +72,7 @@ private WorkflowAgent(Builder builder) {
7072
this.tools = Objects.requireNonNull(builder.tools, "tools must not be null");
7173
this.registry = Objects.requireNonNull(builder.registry, "registry must not be null");
7274
this.mapper = Objects.requireNonNull(builder.mapper, "mapper must not be null");
75+
this.subflowMaxDepth = builder.subflowMaxDepth;
7376
}
7477

7578
public static Builder builder(WorkflowDefinition definition) {
@@ -101,6 +104,8 @@ public static final class Builder {
101104

102105
private ObjectMapper mapper = new ObjectMapper();
103106

107+
private int subflowMaxDepth = 16;
108+
104109
private Builder(WorkflowDefinition definition) {
105110
this.definition = Objects.requireNonNull(definition, "definition must not be null");
106111
}
@@ -136,6 +141,14 @@ public Builder objectMapper(ObjectMapper mapper) {
136141
return this;
137142
}
138143

144+
public Builder subflowMaxDepth(int subflowMaxDepth) {
145+
if (subflowMaxDepth < 1) {
146+
throw new IllegalArgumentException("subflowMaxDepth must be greater than or equal to 1");
147+
}
148+
this.subflowMaxDepth = subflowMaxDepth;
149+
return this;
150+
}
151+
139152
public WorkflowAgent build() {
140153
return new WorkflowAgent(this);
141154
}
@@ -307,12 +320,52 @@ private ExecutionResult executeStep(WorkflowStep step, RunData data, AgentExecut
307320
throw new WorkflowExecutionException("Workflow loop exceeded maxIterations: " + loop.id());
308321
}
309322
if (step instanceof WorkflowStep.Subflow subflow) {
310-
WorkflowDefinition nested = registry.get(subflow.workflowId(), subflow.version());
311-
return executeSteps(nested.steps(), 0, data, context);
323+
return executeSubflow(subflow, data, context);
312324
}
313325
throw new WorkflowExecutionException("Unsupported workflow step: " + step.id());
314326
}
315327

328+
/**
329+
* Enters a subflow through the run's call chain (issue #273): a reference that is
330+
* already on the chain closes a cycle, a chain at the configured depth limit is
331+
* refused before recursing, and both fail with a domain error locating the
332+
* reference chain instead of exhausting the JVM stack. The chain lives on the run
333+
* data, so it survives suspensions and is copied per parallel branch. A
334+
* suspension removes the entry from the chain on the way out: the resumed work
335+
* continues inside the subflow, and re-entering the same subflow from the resumed
336+
* steps is sequential reuse, not a cycle — the chain check still bounds whatever
337+
* the resumed segment does.
338+
*/
339+
private ExecutionResult executeSubflow(WorkflowStep.Subflow subflow, RunData data, AgentExecutionContext context) {
340+
String node = subflow.workflowId() + "@" + subflow.version();
341+
if (data.subflowChain.contains(node)) {
342+
List<String> cycle = new ArrayList<>(data.subflowChain.subList(data.subflowChain.indexOf(node),
343+
data.subflowChain.size()));
344+
cycle.add(node);
345+
throw new WorkflowSubflowRecursionException(
346+
"Workflow subflow reference closes a cycle on the call chain: " + String.join(" -> ", cycle),
347+
cycle);
348+
}
349+
if (data.subflowChain.size() >= subflowMaxDepth) {
350+
// The reported chain starts at the executing definition, so the diagnosis
351+
// shows the whole path from the root of the run.
352+
List<String> extended = new ArrayList<>();
353+
extended.add(definition.id() + "@" + definition.version());
354+
extended.addAll(data.subflowChain);
355+
extended.add(node);
356+
throw new WorkflowSubflowRecursionException("Workflow subflow call chain exceeded the configured depth "
357+
+ "limit " + subflowMaxDepth + ": " + String.join(" -> ", extended), extended);
358+
}
359+
WorkflowDefinition nested = registry.get(subflow.workflowId(), subflow.version());
360+
data.subflowChain.add(node);
361+
try {
362+
return executeSteps(nested.steps(), 0, data, context);
363+
}
364+
finally {
365+
data.subflowChain.remove(data.subflowChain.size() - 1);
366+
}
367+
}
368+
316369
private ExecutionResult executeAgent(WorkflowStep.Agent step, RunData data, AgentExecutionContext context) {
317370
Agent agent = Objects.requireNonNull(agentResolver.apply(step.agentRef()),
318371
"agent resolver returned no agent for " + step.agentRef());
@@ -618,6 +671,10 @@ private static final class RunData {
618671

619672
private final List<ChatMessage> messages;
620673

674+
// The subflow call chain (id@version, caller first) of this run; survives
675+
// suspensions through the continuation closures and is copied per branch.
676+
private final List<String> subflowChain;
677+
621678
private Long inputTokens = 0L;
622679

623680
private Long outputTokens = 0L;
@@ -629,13 +686,15 @@ private RunData(AgentRequest request) {
629686
this.state = new LinkedHashMap<>(request.inputs());
630687
this.stepOutputs = new LinkedHashMap<>();
631688
this.messages = new ArrayList<>(request.messages());
689+
this.subflowChain = new ArrayList<>();
632690
}
633691

634692
private RunData(RunData source) {
635693
this.inputs = new LinkedHashMap<>(source.inputs);
636694
this.state = new LinkedHashMap<>(source.state);
637695
this.stepOutputs = new LinkedHashMap<>(source.stepOutputs);
638696
this.messages = new ArrayList<>(source.messages);
697+
this.subflowChain = new ArrayList<>(source.subflowChain);
639698
this.inputTokens = source.inputTokens;
640699
this.outputTokens = source.outputTokens;
641700
this.totalTokens = source.totalTokens;

‎argi-orchestration/argi-workflow-core/src/main/java/io/github/agentic/ai/workflow/WorkflowDefinitionValidator.java‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,13 @@
1515
*/
1616
package io.github.agentic.ai.workflow;
1717

18+
import java.util.ArrayList;
1819
import java.util.HashSet;
20+
import java.util.LinkedHashSet;
21+
import java.util.List;
22+
import java.util.Optional;
1923
import java.util.Set;
24+
import java.util.function.Function;
2025

2126
/** Structural validation performed before a definition can be published. */
2227
public final class WorkflowDefinitionValidator {
@@ -35,6 +40,74 @@ public static void validate(WorkflowDefinition definition) {
3540
definition.steps().forEach(step -> validateStep(step, ids));
3641
}
3742

43+
/**
44+
* Detects cycles among the subflow references that the registry can already
45+
* resolve, so a self-referencing or mutually referencing set of definitions is
46+
* rejected at publish time instead of exhausting the JVM stack at run time
47+
* (issue #273). The resolver maps an {@code id@version} reference to an already
48+
* published definition; unresolvable references are legal forward references and
49+
* are skipped here — the run keeps its own call chain as the second line of
50+
* defense.
51+
*/
52+
public static void detectSubflowCycles(WorkflowDefinition definition,
53+
Function<String, Optional<WorkflowDefinition>> resolver) {
54+
String root = definition.id() + "@" + definition.version();
55+
List<String> chain = new ArrayList<>();
56+
Set<String> visited = new HashSet<>();
57+
chain.add(root);
58+
visit(definition, resolver, chain, visited);
59+
}
60+
61+
private static void visit(WorkflowDefinition definition, Function<String, Optional<WorkflowDefinition>> resolver,
62+
List<String> chain, Set<String> visited) {
63+
Set<String> references = new LinkedHashSet<>();
64+
collectSubflowReferences(definition.steps(), references);
65+
for (String reference : references) {
66+
int cut = chain.indexOf(reference);
67+
if (cut >= 0) {
68+
throw new IllegalArgumentException("workflow subflow reference closes a cycle: " + String.join(" -> ",
69+
chain.subList(cut, chain.size())) + " -> " + reference);
70+
}
71+
if (!visited.add(reference)) {
72+
continue;
73+
}
74+
Optional<WorkflowDefinition> resolved = resolver.apply(reference);
75+
if (resolved.isEmpty()) {
76+
continue;
77+
}
78+
chain.add(reference);
79+
visit(resolved.get(), resolver, chain, visited);
80+
chain.remove(chain.size() - 1);
81+
}
82+
}
83+
84+
private static void collectSubflowReferences(List<WorkflowStep> steps, Set<String> references) {
85+
for (WorkflowStep step : steps) {
86+
collectSubflowReferences(step, references);
87+
}
88+
}
89+
90+
private static void collectSubflowReferences(WorkflowStep step, Set<String> references) {
91+
if (step instanceof WorkflowStep.Subflow subflow) {
92+
references.add(subflow.workflowId() + "@" + subflow.version());
93+
}
94+
else if (step instanceof WorkflowStep.Sequence sequence) {
95+
collectSubflowReferences(sequence.steps(), references);
96+
}
97+
else if (step instanceof WorkflowStep.Condition condition) {
98+
collectSubflowReferences(condition.whenTrue(), references);
99+
if (condition.whenFalse() != null) {
100+
collectSubflowReferences(condition.whenFalse(), references);
101+
}
102+
}
103+
else if (step instanceof WorkflowStep.Parallel parallel) {
104+
parallel.branches().forEach(branch -> collectSubflowReferences(branch, references));
105+
}
106+
else if (step instanceof WorkflowStep.Loop loop) {
107+
collectSubflowReferences(loop.body(), references);
108+
}
109+
}
110+
38111
private static void validateStep(WorkflowStep step, Set<String> ids) {
39112
if (!ids.add(step.id())) {
40113
throw new IllegalArgumentException("duplicate workflow step id: " + step.id());

‎argi-orchestration/argi-workflow-core/src/main/java/io/github/agentic/ai/workflow/WorkflowRegistry.java‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,33 @@
1717

1818
import java.util.Map;
1919
import java.util.Objects;
20+
import java.util.Optional;
2021
import java.util.TreeMap;
2122
import java.util.concurrent.ConcurrentHashMap;
2223

23-
/** In-memory immutable-version registry; replacing a published version is rejected. */
24+
/**
25+
* In-memory immutable-version registry; replacing a published version is rejected.
26+
*
27+
* <p>
28+
* Publishing resolves the subflow reference graph of the definition against the
29+
* already published definitions and rejects cycles (issue #273). A reference to a
30+
* definition that is not published yet is a legal forward reference: it does not
31+
* block the publish, and an unresolved reference surfaces at run time as the usual
32+
* "workflow version is not published" failure.
33+
*/
2434
public final class WorkflowRegistry {
2535

2636
private final Map<String, Map<String, WorkflowDefinition>> definitions = new ConcurrentHashMap<>();
2737

2838
public WorkflowDefinition publish(WorkflowDefinition definition) {
2939
Objects.requireNonNull(definition, "definition must not be null");
3040
definition.validate();
41+
WorkflowDefinitionValidator.detectSubflowCycles(definition, reference -> {
42+
int separator = reference.indexOf('@');
43+
Map<String, WorkflowDefinition> versions = definitions.get(reference.substring(0, separator));
44+
return versions == null ? Optional.empty()
45+
: Optional.ofNullable(versions.get(reference.substring(separator + 1)));
46+
});
3147
Map<String, WorkflowDefinition> versions = definitions.computeIfAbsent(definition.id(), ignored ->
3248
new ConcurrentHashMap<>());
3349
WorkflowDefinition existing = versions.putIfAbsent(definition.version(), definition);
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Copyright 2026 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package io.github.agentic.ai.workflow;
17+
18+
import java.util.List;
19+
20+
/**
21+
* A subflow reference crosses the recursion boundary: either the reference closes a
22+
* cycle on the current call chain, or the chain grew past the configured depth limit.
23+
* Carries the resolved reference chain ({@code id@version} entries, caller first) so
24+
* the error locates the definitions and versions involved instead of exhausting the
25+
* JVM stack.
26+
*/
27+
public class WorkflowSubflowRecursionException extends WorkflowExecutionException {
28+
29+
private final List<String> chain;
30+
31+
public WorkflowSubflowRecursionException(String message, List<String> chain) {
32+
super(message);
33+
this.chain = List.copyOf(chain);
34+
}
35+
36+
public List<String> chain() {
37+
return chain;
38+
}
39+
40+
}

0 commit comments

Comments
 (0)