Skip to content

Commit 3eb05ba

Browse files
feat(agent): wire strict tool-state mode into graph tool node (T37)
Opt-in strictToolState on the graph path: tools receive a read-only state view (store preserved), failed calls never contribute state via the shared StrictPatchAdmission, sequential merges go through the declared KeyStrategies via a shared mergeEntry, and parallel merges enforce declared-strategy rules for every conflicting key before mergeAll. Default off: legacy behavior pinned by tests. Refs #140
1 parent 2b7e143 commit 3eb05ba

5 files changed

Lines changed: 535 additions & 21 deletions

File tree

‎argi-orchestration/argi-agent-framework/src/main/java/io/github/agentic/ai/agent/orchestration/Builder.java‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ public abstract class Builder {
129129

130130
protected boolean validateToolArguments = false;
131131

132+
protected boolean strictToolState = false;
133+
132134
public Builder name(String name) {
133135
this.name = name;
134136
return this;
@@ -308,6 +310,19 @@ public Builder validateToolArguments(boolean validate) {
308310
return this;
309311
}
310312

313+
/**
314+
* Opt-in strict tool-state semantics for the agent's tool node: read-only state
315+
* views for tools, mandatory failure-discard of patches, KeyStrategy-honoring
316+
* sequential merges and strategy-explicit parallel merges. Default
317+
* {@code false}: legacy behavior.
318+
* @param strict true to enable strict tool-state semantics
319+
* @return this builder instance
320+
*/
321+
public Builder strictToolState(boolean strict) {
322+
this.strictToolState = strict;
323+
return this;
324+
}
325+
311326
public Builder assistantMessageSanitizerEnabled(boolean assistantMessageSanitizerEnabled) {
312327
this.assistantMessageSanitizerEnabled = assistantMessageSanitizerEnabled;
313328
return this;

‎argi-orchestration/argi-agent-framework/src/main/java/io/github/agentic/ai/agent/orchestration/DefaultBuilder.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,8 @@ else if (this.outputType != null) {
112112
.validateToolArguments(this.validateToolArguments)
113113
.toolBindingStore(toolBindings)
114114
.businessOutcomeMappers(this.businessOutcomeMappers)
115-
.toolContextPatchPolicy(this.toolContextPatchPolicy);
115+
.toolContextPatchPolicy(this.toolContextPatchPolicy)
116+
.strictToolState(this.strictToolState);
116117

117118
toolBuilder.throwOnToolError(throwOnToolError);
118119

‎argi-orchestration/argi-agent-framework/src/main/java/io/github/agentic/ai/agent/orchestration/node/AgentToolNode.java‎

Lines changed: 144 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import io.github.agentic.ai.api.chat.ToolCall;
2222
import io.github.agentic.ai.api.tool.ToolRegistry;
2323
import io.github.agentic.ai.api.tool.ToolResult;
24+
import io.github.agentic.ai.workflow.graph.KeyStrategy;
2425
import io.github.agentic.ai.workflow.graph.OverAllState;
2526
import io.github.agentic.ai.workflow.graph.RunnableConfig;
2627
import io.github.agentic.ai.workflow.graph.action.NodeActionWithConfig;
@@ -39,6 +40,10 @@
3940
import io.github.agentic.ai.agent.tool.patch.ToolContextPatchSpec;
4041
import io.github.agentic.ai.agent.tool.patch.ToolContextPatchValidator;
4142
import io.github.agentic.ai.agent.tool.patch.ToolContextPatchViolationException;
43+
import io.github.agentic.ai.agent.tool.patch.strict.StateIsolation;
44+
import io.github.agentic.ai.agent.tool.patch.strict.StrictMergeRules;
45+
import io.github.agentic.ai.agent.tool.patch.strict.StrictPatchAdmission;
46+
import io.github.agentic.ai.agent.tool.patch.strict.ToolUpdateUnit;
4247
import io.github.agentic.ai.agent.validation.ToolArgumentValidator;
4348
import io.github.agentic.ai.runtime.execution.ExecutionGuard;
4449
import io.github.agentic.ai.workflow.graph.checkpoint.lease.LeaseLostException;
@@ -129,6 +134,8 @@ public class AgentToolNode implements NodeActionWithConfig {
129134

130135
private final ToolContextPatchPolicy toolContextPatchPolicy;
131136

137+
private final boolean strictToolState;
138+
132139
private final ThreadPoolExecutor neutralInvocationExecutor;
133140

134141
public AgentToolNode(Builder builder) {
@@ -154,6 +161,7 @@ public AgentToolNode(Builder builder) {
154161
this.throwOnToolError = builder.throwOnToolError;
155162
this.businessOutcomeMappers = builder.businessOutcomeMappers;
156163
this.toolContextPatchPolicy = builder.toolContextPatchPolicy;
164+
this.strictToolState = builder.strictToolState;
157165
}
158166

159167
public void setToolInterceptors(List<ToolInterceptor> toolInterceptors) {
@@ -240,9 +248,10 @@ else if (lastMessage.role() == ChatRole.TOOL) {
240248
* </p>
241249
* <p>
242250
* Note: This differs from parallel execution mode, which respects
243-
* {@link io.github.agentic.ai.workflow.graph.KeyStrategy} for merge operations. If you need
244-
* deterministic merge behavior (e.g., APPEND for lists), use parallel execution mode
245-
* instead.
251+
* {@link io.github.agentic.ai.workflow.graph.KeyStrategy} for merge operations - unless
252+
* {@code strictToolState(true)} is enabled, in which case sequential merges go through
253+
* the same KeyStrategy map and the divergence disappears. Without strict mode, use
254+
* parallel execution for deterministic merge behavior (e.g., APPEND for lists).
246255
* </p>
247256
*
248257
* @see #executeToolCallsParallel(List, OverAllState, RunnableConfig)
@@ -256,13 +265,14 @@ private Map<String, Object> executeToolCallsSequential(List<io.github.agentic.ai
256265
// successful tools
257266
List<ChatMessage> toolResponses = new ArrayList<>();
258267

268+
OverAllState toolState = toolVisibleState(state);
259269
Boolean returnDirect = null;
260270
for (io.github.agentic.ai.api.chat.ToolCall toolCall : toolCalls) {
261271
config.assertExecutionActive();
262272
// Each tool gets its own isolated update map
263273
// If this tool times out, clear() only affects this map, not mergedUpdates
264274
Map<String, Object> toolSpecificUpdate = new ConcurrentHashMap<>();
265-
ToolCallResponse response = executeToolCallWithInterceptors(toolCall, state, config, toolSpecificUpdate,
275+
ToolCallResponse response = executeToolCallWithInterceptors(toolCall, toolState, config, toolSpecificUpdate,
266276
false);
267277
config.assertExecutionActive();
268278
toolResponses.add(response.toMessage());
@@ -272,7 +282,12 @@ private Map<String, Object> executeToolCallsSequential(List<io.github.agentic.ai
272282
// data. A configured patch policy gates the merge boundary: patches of failed
273283
// calls and invalid patches never reach the next turn's state.
274284
if (admitsPatch(toolCall.name(), response, toolSpecificUpdate)) {
275-
mergedUpdates.putAll(toolSpecificUpdate);
285+
if (strictToolState) {
286+
mergeThroughStrategies(mergedUpdates, toolSpecificUpdate, state);
287+
}
288+
else {
289+
mergedUpdates.putAll(toolSpecificUpdate);
290+
}
276291
}
277292
}
278293
config.assertExecutionActive();
@@ -297,7 +312,9 @@ private Map<String, Object> executeToolCallsSequential(List<io.github.agentic.ai
297312
* <b>Important:</b> The state snapshot created via {@code state.snapShot()} is a
298313
* shallow copy. Mutable objects within the state (like Lists) are shared. Tools
299314
* should NOT directly modify collections retrieved from the state. Use the
300-
* {@code extraStateFromToolCall} map to write updates.
315+
* {@code extraStateFromToolCall} map to write updates. With
316+
* {@code strictToolState(true)} this advisory becomes structural: tools receive a
317+
* read-only view whose collections reject mutation.
301318
* </p>
302319
*
303320
* <h3>State Merge Semantics</h3>
@@ -335,7 +352,7 @@ private Map<String, Object> executeToolCallsParallel(List<io.github.agentic.ai.a
335352
// Create state snapshot for thread safety
336353
// Note: snapShot() is a shallow copy, shared mutable objects (like messages List)
337354
// should not be directly modified by tools
338-
OverAllState stateSnapshot = state.snapShot().orElse(state);
355+
OverAllState stateSnapshot = toolVisibleState(state.snapShot().orElse(state));
339356

340357
ToolStateCollector stateCollector = new ToolStateCollector(toolCalls.size(), state.keyStrategies());
341358

@@ -466,6 +483,9 @@ private Map<String, Object> executeToolCallsParallel(List<io.github.agentic.ai.a
466483
// Same merge-boundary gate as sequential mode, applied per tool index: rejected
467484
// patches are discarded before mergeAll() so they cannot pollute the state.
468485
discardRejectedPatches(toolCalls, orderedResponses, stateCollector);
486+
if (strictToolState) {
487+
enforceDeclaredMergeStrategies(toolCalls, stateCollector, state);
488+
}
469489
updatedState.putAll(stateCollector.mergeAll());
470490

471491
if (enableActingLog) {
@@ -775,11 +795,12 @@ private void propagateToolFailure(Throwable failure) {
775795

776796
/**
777797
* Applies the configured patch policy to every collected response before the parallel
778-
* merge, discarding the update maps of rejected calls. No-op without a policy.
798+
* merge, discarding the update maps of rejected calls. No-op without a policy and
799+
* without strict mode; in strict mode the admission runs even without a policy.
779800
*/
780801
private void discardRejectedPatches(List<io.github.agentic.ai.api.chat.ToolCall> toolCalls,
781802
AtomicReferenceArray<ToolCallResponse> orderedResponses, ToolStateCollector stateCollector) {
782-
if (toolContextPatchPolicy == null) {
803+
if (!strictToolState && toolContextPatchPolicy == null) {
783804
return;
784805
}
785806
for (int i = 0; i < orderedResponses.length(); i++) {
@@ -793,6 +814,94 @@ private void discardRejectedPatches(List<io.github.agentic.ai.api.chat.ToolCall>
793814
}
794815
}
795816

817+
/**
818+
* The state a tool may read in strict mode: an {@link OverAllState} whose data map and
819+
* one-level-deep collections reject mutation, so state writes can escape only through
820+
* the patch channel. Without strict mode the state passes through untouched.
821+
* @param state the state the node was invoked with
822+
* @return the state a tool may read
823+
*/
824+
private OverAllState toolVisibleState(OverAllState state) {
825+
if (!strictToolState) {
826+
return state;
827+
}
828+
var view = new OverAllState(StateIsolation.readOnlyView(state.data()), state.getStore());
829+
view.registerKeyAndStrategy(state.keyStrategies());
830+
return view;
831+
}
832+
833+
/**
834+
* Merges one admitted patch into the accumulated sequential updates through the
835+
* declared {@link KeyStrategy} map - the same rules the parallel collector applies -
836+
* closing the historical sequential/parallel divergence for strict mode.
837+
* @param merged the accumulated updates of earlier tools
838+
* @param patch the admitted patch of the tool that just completed
839+
* @param state the node's state, source of the declared strategies
840+
*/
841+
private void mergeThroughStrategies(Map<String, Object> merged, Map<String, Object> patch,
842+
OverAllState state) {
843+
Map<String, KeyStrategy> strategies = state.keyStrategies();
844+
for (Map.Entry<String, Object> entry : patch.entrySet()) {
845+
ToolStateCollector.mergeEntry(merged, strategies, entry.getKey(), entry.getValue());
846+
}
847+
}
848+
849+
/**
850+
* Strict parallel merge rule: a key written by several tools without a declared
851+
* {@link KeyStrategy} is a policy violation, not a silent replace-last-in-tool-order.
852+
* ABORT runs throw the same violation exception as patch validation; DISCARD drops
853+
* every admitted patch touching the conflicting key, whole patches at a time.
854+
* @param toolCalls the calls of the parallel batch, in tool order
855+
* @param stateCollector the batch's admitted update maps
856+
* @param state the node's state, source of the declared strategies
857+
*/
858+
private void enforceDeclaredMergeStrategies(List<io.github.agentic.ai.api.chat.ToolCall> toolCalls,
859+
ToolStateCollector stateCollector, OverAllState state) {
860+
// Re-check after every discard round: dropping a patch can resolve further
861+
// conflicts (or expose the next one), and each round discards at least one
862+
// non-empty patch, so the loop terminates.
863+
Map<String, KeyStrategy> strategies = state.keyStrategies();
864+
while (true) {
865+
var conflict = StrictMergeRules.checkUndeclaredConflicts(admittedPatches(toolCalls, stateCollector),
866+
strategies.keySet());
867+
if (conflict.isEmpty()) {
868+
return;
869+
}
870+
StrictMergeRules.ConflictFailure failure = conflict.get();
871+
if (toolContextPatchPolicy != null
872+
&& toolContextPatchPolicy.violationPolicy() == ToolContextPatchPolicy.ViolationPolicy.ABORT_RUN) {
873+
throw new ToolContextPatchViolationException(new ToolContextPatchValidator.PatchValidationFailure(
874+
failure.errorCode(), failure.key(), failure.message()));
875+
}
876+
logger.warn("Discarding context patches writing state key '{}': written by several tools without a "
877+
+ "declared merge strategy", failure.key());
878+
for (int i = 0; i < toolCalls.size(); i++) {
879+
Map<String, Object> patch = stateCollector.toolUpdateMap(i);
880+
if (patch != null && patch.containsKey(failure.key())) {
881+
stateCollector.discardToolUpdateMap(i);
882+
}
883+
}
884+
}
885+
}
886+
887+
/**
888+
* The update maps still admitted to the parallel merge, in tool order.
889+
* @param toolCalls the calls of the parallel batch, in tool order
890+
* @param stateCollector the batch's update maps
891+
* @return the non-empty admitted patches, never {@code null}
892+
*/
893+
private List<Map<String, Object>> admittedPatches(List<io.github.agentic.ai.api.chat.ToolCall> toolCalls,
894+
ToolStateCollector stateCollector) {
895+
List<Map<String, Object>> patches = new ArrayList<>();
896+
for (int i = 0; i < toolCalls.size(); i++) {
897+
Map<String, Object> patch = stateCollector.toolUpdateMap(i);
898+
if (patch != null && !patch.isEmpty()) {
899+
patches.add(patch);
900+
}
901+
}
902+
return patches;
903+
}
904+
796905
/**
797906
* Merge-boundary admission for one tool's context patch. Without a policy every patch
798907
* is admitted (legacy behavior). With a policy, patches of failed calls are discarded
@@ -805,6 +914,16 @@ private void discardRejectedPatches(List<io.github.agentic.ai.api.chat.ToolCall>
805914
* @return {@code true} when the patch may be merged into the next turn's state
806915
*/
807916
private boolean admitsPatch(String toolName, ToolCallResponse response, Map<String, Object> patch) {
917+
if (strictToolState) {
918+
boolean admitted = StrictPatchAdmission.admit(toolContextPatchPolicy,
919+
new ToolUpdateUnit(toolName, !response.isError(), patch));
920+
if (!admitted) {
921+
logger.warn(
922+
"Discarding context patch of tool {}: strict admission rejected the tool's update unit",
923+
toolName);
924+
}
925+
return admitted;
926+
}
808927
if (toolContextPatchPolicy == null || patch == null || patch.isEmpty()) {
809928
return true;
810929
}
@@ -945,6 +1064,8 @@ public Builder toolRegistry(ToolRegistry toolRegistry) {
9451064

9461065
private ToolContextPatchPolicy toolContextPatchPolicy;
9471066

1067+
private boolean strictToolState;
1068+
9481069
/** Controls failure propagation for provider-neutral tool stages. */
9491070
public Builder throwOnToolError(boolean throwOnToolError) {
9501071
this.throwOnToolError = throwOnToolError;
@@ -963,6 +1084,20 @@ public Builder toolContextPatchPolicy(ToolContextPatchPolicy toolContextPatchPol
9631084
return this;
9641085
}
9651086

1087+
/**
1088+
* Opt-in strict tool-state mode. Tools then see a read-only view of the state
1089+
* instead of the live map or a shallow snapshot, a failed call's patch is always
1090+
* discarded regardless of the patch policy, sequential merges honor the declared
1091+
* KeyStrategies, and parallel merges refuse keys written by several tools without
1092+
* a declared strategy. Default {@code false}: legacy behavior.
1093+
* @param strict true to enable strict tool-state semantics
1094+
* @return this builder
1095+
*/
1096+
public Builder strictToolState(boolean strict) {
1097+
this.strictToolState = strict;
1098+
return this;
1099+
}
1100+
9661101
private Builder() {
9671102
}
9681103

‎argi-orchestration/argi-agent-framework/src/main/java/io/github/agentic/ai/agent/orchestration/tool/ToolStateCollector.java‎

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -150,23 +150,35 @@ public Map<String, Object> mergeAll() {
150150
}
151151

152152
for (Map.Entry<String, Object> entry : toolUpdate.entrySet()) {
153-
String key = entry.getKey();
154-
Object newValue = entry.getValue();
155-
Object existingValue = result.get(key);
156-
157-
if (existingValue == null) {
158-
result.put(key, newValue);
159-
}
160-
else {
161-
KeyStrategy strategy = keyStrategies.getOrDefault(key, KeyStrategy.REPLACE);
162-
result.put(key, strategy.apply(existingValue, newValue));
163-
}
153+
mergeEntry(result, keyStrategies, entry.getKey(), entry.getValue());
164154
}
165155
}
166156

167157
return result;
168158
}
169159

160+
/**
161+
* Merges one update entry into an accumulated update map through the declared
162+
* strategy, falling back to {@link KeyStrategy#REPLACE} for undeclared keys. This is
163+
* the single strategy-aware entry merge shared by the parallel collector and strict
164+
* sequential merging, so the two paths cannot drift apart.
165+
* @param updates the accumulated updates to merge into
166+
* @param keyStrategies the declared strategies, or {@code null} for none
167+
* @param key the state key being written
168+
* @param newValue the value the tool produced for the key
169+
*/
170+
public static void mergeEntry(Map<String, Object> updates, Map<String, KeyStrategy> keyStrategies, String key,
171+
Object newValue) {
172+
Object existingValue = updates.get(key);
173+
if (existingValue == null) {
174+
updates.put(key, newValue);
175+
return;
176+
}
177+
KeyStrategy strategy = (keyStrategies != null ? keyStrategies : Map.<String, KeyStrategy>of())
178+
.getOrDefault(key, KeyStrategy.REPLACE);
179+
updates.put(key, strategy.apply(existingValue, newValue));
180+
}
181+
170182
/**
171183
* Gets the number of tools that have submitted updates.
172184
* @return the count of tools with updates

0 commit comments

Comments
 (0)