Skip to content

Commit 3e59352

Browse files
committed
fix(graph): avoid mutating append inputs
1 parent 4a82325 commit 3e59352

2 files changed

Lines changed: 44 additions & 1 deletion

File tree

spring-ai-alibaba-graph-core/src/main/java/com/alibaba/cloud/ai/graph/state/strategy/AppendStrategy.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,9 @@ else if (newValue instanceof Collection) {
9494
oldList.addAll(list);
9595
}
9696
else {
97-
oldList.add(newValue);
97+
var result = new ArrayList<>(oldList);
98+
result.add(newValue);
99+
return result;
98100
}
99101
return oldList;
100102
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/*
2+
* Copyright 2024-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 com.alibaba.cloud.ai.graph;
17+
18+
import com.alibaba.cloud.ai.graph.state.strategy.AppendStrategy;
19+
import org.junit.jupiter.api.Test;
20+
21+
import java.util.ArrayList;
22+
import java.util.List;
23+
24+
import static org.junit.jupiter.api.Assertions.assertEquals;
25+
import static org.junit.jupiter.api.Assertions.assertNotSame;
26+
27+
class AppendStrategyMutationRegressionTest {
28+
29+
// https://github.com/alibaba/spring-ai-alibaba/issues/4757
30+
@Test
31+
void issue4757_singleValueAppend_doesNotMutateExistingList() {
32+
AppendStrategy strategy = new AppendStrategy();
33+
List<Object> oldValues = new ArrayList<>(List.of("question"));
34+
35+
Object result = strategy.apply(oldValues, "user-answer");
36+
37+
assertEquals(List.of("question"), oldValues);
38+
assertEquals(List.of("question", "user-answer"), result);
39+
assertNotSame(oldValues, result);
40+
}
41+
}

0 commit comments

Comments
 (0)