This is an automated email from the ASF dual-hosted git repository.

lizhimins pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-dashboard.git


The following commit(s) were added to refs/heads/master by this push:
     new 71310f026 fix(ai): bound the LLM model to the AI record column width 
(#6796)
71310f026 is described below

commit 71310f026f139e5b3f8ff50d918c97e2e3e7d528
Author: Apulupie <[email protected]>
AuthorDate: Fri Nov 27 12:45:40 2026 +0800

    fix(ai): bound the LLM model to the AI record column width (#6796)
---
 .../rocketmq/studio/ops/ai/LlmConfigService.java   | 33 ++++++++++++
 .../ops/ai/conversation/AiConversationService.java |  6 ++-
 .../studio/ops/ai/conversation/AiRunService.java   |  4 ++
 .../studio/settings/GeneralSettingsUpdateDTO.java  |  4 ++
 .../studio/ops/ai/LlmConfigServiceTest.java        | 18 +++++++
 .../ai/conversation/AiConversationServiceTest.java | 16 ++++++
 .../ops/ai/conversation/AiRunServiceTest.java      | 19 +++++++
 .../settings/GeneralSettingsModelBoundTest.java    | 60 ++++++++++++++++++++++
 8 files changed, 159 insertions(+), 1 deletion(-)

diff --git 
a/server/src/main/java/org/apache/rocketmq/studio/ops/ai/LlmConfigService.java 
b/server/src/main/java/org/apache/rocketmq/studio/ops/ai/LlmConfigService.java
index d77554666..cf4ee1867 100644
--- 
a/server/src/main/java/org/apache/rocketmq/studio/ops/ai/LlmConfigService.java
+++ 
b/server/src/main/java/org/apache/rocketmq/studio/ops/ai/LlmConfigService.java
@@ -19,6 +19,8 @@ package org.apache.rocketmq.studio.ops.ai;
 
 import org.springframework.util.StringUtils;
 
+import org.apache.rocketmq.studio.common.exception.BusinessException;
+import org.apache.rocketmq.studio.common.util.TextBounds;
 import org.apache.rocketmq.studio.common.util.UrlHostGuard;
 import org.apache.rocketmq.studio.settings.GeneralSettingsVO;
 import org.apache.rocketmq.studio.settings.SettingsService;
@@ -46,6 +48,15 @@ public class LlmConfigService {
     private static final int DEFAULT_MAX_TOKENS = 4096;
     private static final double DEFAULT_TEMPERATURE = 0.7;
     private static final int MAX_TOKENS_LIMIT = 200_000;
+
+    /**
+     * The model id is written verbatim into {@code rmq_ai_conversation.model} 
and
+     * {@code rmq_ai_run.model}, both {@code VARCHAR(128)}, and the run 
request's own override is
+     * bounded to the same length ({@code AiMessageDTO.model}). A longer 
configured id has to be
+     * refused here — and again where a record copies it — because the 
database would otherwise
+     * answer the first message of the conversation with a 500.
+     */
+    static final int MAX_MODEL_CHARS = 128;
     private static final Map<String, List<LlmModelItemVO>> PROVIDER_MODELS = 
Map.of(
             OPENAI, List.of(
                     new LlmModelItemVO("gpt-5.6-sol", "GPT-5.6 Sol"),
@@ -223,9 +234,31 @@ public class LlmConfigService {
                     "LLM model is required",
                     "Select or enter a model before testing the connection.");
         }
+        if (TextBounds.codePointCount(normalized.getModel().trim()) > 
MAX_MODEL_CHARS) {
+            return LlmOperationResultVO.failure(
+                    "llm.config.invalid_model",
+                    "LLM model is too long",
+                    "Use a model id of at most " + MAX_MODEL_CHARS
+                            + " characters: the conversation and run records 
store it verbatim.");
+        }
         return LlmOperationResultVO.success("Configuration accepted");
     }
 
+    /**
+     * Refuses a model id the AI record columns cannot hold.
+     *
+     * @throws BusinessException 400 when {@code model} is longer than {@link 
#MAX_MODEL_CHARS}
+     *     code points. The callers store the value in {@code VARCHAR(128)} 
columns, where MySQL
+     *     rejects the row and the request would end as a 500; failing here 
names the field the
+     *     operator has to shorten instead.
+     */
+    public static void requireStorableModel(String model) {
+        if (TextBounds.codePointCount(model == null ? null : model.trim()) > 
MAX_MODEL_CHARS) {
+            throw new BusinessException(400, "The LLM model is longer than the 
" + MAX_MODEL_CHARS
+                    + " characters a conversation or run record stores; 
shorten the model id in the AI settings.");
+        }
+    }
+
     public LlmModelsResultVO listModels() {
         return listModels(getConfig());
     }
diff --git 
a/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/AiConversationService.java
 
b/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/AiConversationService.java
index a7490e006..23bba451f 100644
--- 
a/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/AiConversationService.java
+++ 
b/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/AiConversationService.java
@@ -172,7 +172,11 @@ public class AiConversationService implements 
ApplicationRunner {
         conversation.setTitle(DEFAULT_TITLE);
         conversation.setOwner(StringUtils.hasText(owner) ? owner.trim() : 
"system");
         conversation.setEngine(config == null ? "" : config.normalizeEngine());
-        conversation.setModel(config == null || config.getModel() == null ? "" 
: config.getModel().trim());
+        String model = config == null || config.getModel() == null ? "" : 
config.getModel().trim();
+        // The row stores the id verbatim in VARCHAR(128); a longer configured 
value must not reach
+        // the insert, where MySQL would reject the row and the request would 
end as a 500.
+        LlmConfigService.requireStorableModel(model);
+        conversation.setModel(model);
         conversation.setMode(normalizeMode(mode));
         conversation.setInstanceId(StringUtils.hasText(instanceId) ? 
instanceId.trim() : null);
         conversation.setLastSeq(0);
diff --git 
a/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunService.java
 
b/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunService.java
index f2929b276..4e070e08e 100644
--- 
a/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunService.java
+++ 
b/server/src/main/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunService.java
@@ -192,6 +192,10 @@ public class AiRunService {
                     "No model is configured for the " + engine + " engine",
                     "Pick a model in the AI settings.");
         }
+        // The run row snapshots this id into a VARCHAR(128) column, and the 
configured model can
+        // outlive the check that bounds the request override: fail with a 400 
here instead of
+        // letting the insert answer 500.
+        LlmConfigService.requireStorableModel(model);
 
         // Choose the candidate turn BEFORE checking for an active run. If 
another request is admitted
         // after this read, it claims this same turn and the unique key below 
rejects one of us. Reading
diff --git 
a/server/src/main/java/org/apache/rocketmq/studio/settings/GeneralSettingsUpdateDTO.java
 
b/server/src/main/java/org/apache/rocketmq/studio/settings/GeneralSettingsUpdateDTO.java
index 031d9300a..a997b16d9 100644
--- 
a/server/src/main/java/org/apache/rocketmq/studio/settings/GeneralSettingsUpdateDTO.java
+++ 
b/server/src/main/java/org/apache/rocketmq/studio/settings/GeneralSettingsUpdateDTO.java
@@ -20,6 +20,7 @@ import jakarta.validation.constraints.Max;
 import jakarta.validation.constraints.Min;
 import jakarta.validation.constraints.NotBlank;
 import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Size;
 import lombok.AllArgsConstructor;
 import lombok.Builder;
 import lombok.Data;
@@ -57,6 +58,9 @@ public class GeneralSettingsUpdateDTO {
     private String apiKey;
     private boolean clearApiKey;
     @NotBlank
+    // rmq_ai_conversation.model and rmq_ai_run.model are VARCHAR(128) and 
store this id verbatim
+    // (AiMessageDTO bounds the per-run override to the same length).
+    @Size(max = 128, message = "model must not exceed 128 characters")
     private String model;
     @NotNull
     private String baseUrl;
diff --git 
a/server/src/test/java/org/apache/rocketmq/studio/ops/ai/LlmConfigServiceTest.java
 
b/server/src/test/java/org/apache/rocketmq/studio/ops/ai/LlmConfigServiceTest.java
index af9db1899..a40bc7420 100644
--- 
a/server/src/test/java/org/apache/rocketmq/studio/ops/ai/LlmConfigServiceTest.java
+++ 
b/server/src/test/java/org/apache/rocketmq/studio/ops/ai/LlmConfigServiceTest.java
@@ -704,6 +704,24 @@ class LlmConfigServiceTest {
         assertThat(result.getHint()).contains("200000");
     }
 
+    @Test
+    void saveConfigShouldRejectAModelLongerThanTheAiRecordColumnsTest() {
+        LlmConfigVO config = llmConfigService.getConfig();
+        config.setModel("m".repeat(129));
+
+        // rmq_ai_conversation.model and rmq_ai_run.model store the id 
verbatim in VARCHAR(128):
+        // accepting it here would let the conversation's first message fail 
on the insert instead.
+        assertThatThrownBy(() -> llmConfigService.saveConfig(config))
+                .isInstanceOfSatisfying(LlmGatewayException.class, error -> {
+                    assertThat(error.getStatusCode()).isEqualTo(400);
+                    
assertThat(error.getCode()).isEqualTo("llm.config.invalid_model");
+                });
+
+        // The column width itself is storable: one character less must still 
be accepted.
+        config.setModel("m".repeat(128));
+        llmConfigService.saveConfig(config);
+    }
+
     @Test
     void configShouldRejectOutOfRangeTemperatureTest() {
         LlmOperationResultVO result = 
llmConfigService.testConfig(LlmConfigVO.builder()
diff --git 
a/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/AiConversationServiceTest.java
 
b/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/AiConversationServiceTest.java
index c246ab9af..3b18ab0f2 100644
--- 
a/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/AiConversationServiceTest.java
+++ 
b/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/AiConversationServiceTest.java
@@ -137,6 +137,22 @@ class AiConversationServiceTest {
         
assertThat(created.getGmtCreate()).isEqualTo(LocalDateTime.now(Clock.fixed(NOW, 
ZoneOffset.UTC)));
     }
 
+    @Test
+    void 
createShouldRefuseAConfiguredModelTheConversationColumnCannotStoreTest() {
+        when(llmConfigService.getConfig()).thenReturn(LlmConfigVO.builder()
+                .engine(LlmConfigVO.ENGINE_HTTP)
+                .model("m".repeat(129))
+                .build());
+
+        // rmq_ai_conversation.model is VARCHAR(128): the insert would be 
rejected by the database
+        // (Data too long) and the request would end as a 500 instead of 
naming the field to shorten.
+        assertThatThrownBy(() -> service.create(OWNER, null, "chat"))
+                .isInstanceOfSatisfying(BusinessException.class,
+                        error -> 
assertThat(error.getMessage()).contains("128"));
+
+        verify(conversationRepository, 
never()).insert(any(RmqAiConversation.class));
+    }
+
     @Test
     void createShouldFallBackToChatForAnUnknownModeTest() {
         // A mode is a UI hint, not a security boundary: an unexpected value 
degrades instead of failing
diff --git 
a/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunServiceTest.java
 
b/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunServiceTest.java
index e3369dd95..8481bb22c 100644
--- 
a/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunServiceTest.java
+++ 
b/server/src/test/java/org/apache/rocketmq/studio/ops/ai/conversation/AiRunServiceTest.java
@@ -280,6 +280,25 @@ class AiRunServiceTest {
         verify(deferred).submit(any(Runnable.class));
     }
 
+    @Test
+    void admissionShouldRefuseAConfiguredModelTheRunColumnCannotStoreTest() {
+        // The per-request override is bounded by AiMessageDTO; the configured 
model is not, and the
+        // conversation row carries none, so the configured id is what the run 
would snapshot.
+        conversation.setModel(null);
+        when(llmConfigService.getConfig()).thenReturn(LlmConfigVO.builder()
+                .engine(LlmConfigVO.ENGINE_CLAUDE_CODE)
+                .model("m".repeat(129))
+                .enabled(true)
+                .build());
+
+        assertThatThrownBy(() -> service.sendMessage(CONVERSATION_ID, 
AiRunService.RunRequest.of("again")))
+                .isInstanceOfSatisfying(BusinessException.class,
+                        exception -> 
assertThat(exception.getMessage()).contains("128"));
+        // Refused before admission: no run row and no user turn.
+        assertThat(runInserts).isEmpty();
+        assertThat(inserted).isEmpty();
+    }
+
     @Test
     void aConversationWithoutToolsShouldSaySoInItsTimelineTest() {
         when(workspace.prepare(anyLong(), any())).thenReturn(Optional.empty());
diff --git 
a/server/src/test/java/org/apache/rocketmq/studio/settings/GeneralSettingsModelBoundTest.java
 
b/server/src/test/java/org/apache/rocketmq/studio/settings/GeneralSettingsModelBoundTest.java
new file mode 100644
index 000000000..e1a777b51
--- /dev/null
+++ 
b/server/src/test/java/org/apache/rocketmq/studio/settings/GeneralSettingsModelBoundTest.java
@@ -0,0 +1,60 @@
+/*
+ * 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.apache.rocketmq.studio.settings;
+
+import jakarta.validation.Validation;
+import jakarta.validation.ValidatorFactory;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * The model field's column contract. Kept in its own class because the 
general DTO contract
+ * (field mapping, session-timeout bounds, toString redaction) is pinned 
separately, and a merge
+ * conflict between the two would otherwise have to be resolved by hand.
+ */
+class GeneralSettingsModelBoundTest {
+
+    @Test
+    void modelShouldBeBoundedToTheAiRecordColumnsTest() {
+        try (ValidatorFactory validatorFactory = 
Validation.buildDefaultValidatorFactory()) {
+            GeneralSettingsUpdateDTO accepted = validSettings();
+            accepted.setModel("m".repeat(128));
+            
assertThat(validatorFactory.getValidator().validate(accepted)).isEmpty();
+
+            GeneralSettingsUpdateDTO rejected = validSettings();
+            rejected.setModel("m".repeat(129));
+            assertThat(validatorFactory.getValidator().validate(rejected))
+                    .anyMatch(violation -> 
"model".equals(violation.getPropertyPath().toString())
+                            && "model must not exceed 128 
characters".equals(violation.getMessage()));
+        }
+    }
+
+    private static GeneralSettingsUpdateDTO validSettings() {
+        return GeneralSettingsUpdateDTO.builder()
+                .theme("dark")
+                .compact(true)
+                .desktopNotify(true)
+                .notifySound(false)
+                .sessionTimeout(45)
+                .requireLogin(true)
+                .llmProvider("openai")
+                .model("gpt-4o")
+                .baseUrl("https://api.openai.com/v1";)
+                .build();
+    }
+}

Reply via email to