|
|
@@ -1,1118 +0,0 @@
|
|
|
-package com.zsjz.ai.module.ai.core.agent.python;
|
|
|
-
|
|
|
-import com.zsjz.ai.common.constants.PathConst;
|
|
|
-import com.zsjz.ai.common.context.CaseContextHolder;
|
|
|
-import com.zsjz.ai.common.datasource.CaseDataSourceRegistry;
|
|
|
-import com.zsjz.ai.common.model.plat.entity.CaseInfo;
|
|
|
-import com.zsjz.ai.common.storage.StorageLayout;
|
|
|
-import com.zsjz.ai.module.ai.core.agent.analysis.AnalysisWorkspaceService;
|
|
|
-import com.zsjz.ai.module.ai.config.PythonProperties;
|
|
|
-
|
|
|
-import com.zsjz.ai.module.plat.mapper.CaseInfoMapper;
|
|
|
-import lombok.extern.slf4j.Slf4j;
|
|
|
-import org.springframework.stereotype.Service;
|
|
|
-
|
|
|
-import java.io.IOException;
|
|
|
-import java.nio.charset.StandardCharsets;
|
|
|
-import java.nio.file.Files;
|
|
|
-import java.nio.file.Path;
|
|
|
-import java.nio.file.Paths;
|
|
|
-import java.util.ArrayList;
|
|
|
-import java.util.Comparator;
|
|
|
-import java.util.List;
|
|
|
-import java.util.Map;
|
|
|
-import java.util.UUID;
|
|
|
-import java.util.concurrent.TimeUnit;
|
|
|
-import java.util.stream.Stream;
|
|
|
-
|
|
|
-/**
|
|
|
- * Python 子进程执行器(独立临时目录)。
|
|
|
- *
|
|
|
- * <p>每次执行使用独立临时目录({@code cases/{caseId}/ai/python/sandbox/{execId}}),
|
|
|
- * 超时强制终止、输出截断;执行后将沙箱内生成的图片移动到
|
|
|
- * {@code cases/{caseId}/ai/python/out/{execId}} 供文件服务接口输出。
|
|
|
- *
|
|
|
- * <p><b>不做代码内容拦截</b>:文件读写、子进程、网络等操作由 Python 代码自行决定,
|
|
|
- * 只保留空代码校验、执行超时和输出截断。进程与 Java 同用户运行,需要隔离时
|
|
|
- * 请使用容器/受限 OS 用户,或只挂载当前案件目录。
|
|
|
- *
|
|
|
- * <h3>ETL_DB_PATH 指向的是「快照副本」而不是原库</h3>
|
|
|
- * DuckDB 单文件只允许一个进程读写打开,而案件库在本进程(Java)里是常驻打开的 ——
|
|
|
- * 子进程直接连原库必然失败(Windows 报「另一个程序正在使用此文件」)。
|
|
|
- * 因此执行前由本进程用 {@code ATTACH + COPY FROM DATABASE} 导出一份单文件快照
|
|
|
- * ({@code cases/{caseId}/ai/python/snapshot/case.duckdb},见 {@link CaseDataSourceRegistry#exportSnapshot}),
|
|
|
- * 把 {@code ETL_DB_PATH} 指向它。快照里表与视图都在,Python 侧用法不变(仍可 read_only 打开)。
|
|
|
- * 目录按工作空间隔离、文件名再带上工作空间 ID,多用户/多空间并发时既不会重名也好辨认。
|
|
|
- *
|
|
|
- * <p>快照按<b>源库指纹</b>(主文件与 WAL 的大小/修改时间)缓存:源库自上次导出后没变就直接复用,
|
|
|
- * 避免模型连着跑几段 Python 时反复导出整库。
|
|
|
- */
|
|
|
-@Slf4j
|
|
|
-@Service
|
|
|
-public class PythonExecutor {
|
|
|
-
|
|
|
- /**
|
|
|
- * 依赖检测 import 语句
|
|
|
- */
|
|
|
- private static final String CHECK_IMPORTS = "import pandas, duckdb, matplotlib";
|
|
|
-
|
|
|
- /**
|
|
|
- * 环境注入的 DuckDB 文件路径变量名。
|
|
|
- *
|
|
|
- * <p>值是<b>快照副本</b>路径(不是案件原库):原库被本进程写锁持有,子进程连不上。
|
|
|
- */
|
|
|
- public static final String ENV_DB_PATH = "ETL_DB_PATH";
|
|
|
-
|
|
|
- /**
|
|
|
- * Python 图片 URL 前缀。
|
|
|
- *
|
|
|
- * <p>必须与 {@code AgentPythonFileController} 的映射路径叠加应用 context-path 后一致:
|
|
|
- * context-path = {@code /js/a}(见 application.yaml),控制器映射 {@code /py/files},
|
|
|
- * 因此对外可达地址为 {@code /js/a/py/files/{workspaceId}/{execId}/{filename}}。
|
|
|
- * 前端经 ctxPath({@code /js}) + adminPath({@code /a}) 访问,与此保持一致。
|
|
|
- */
|
|
|
- public static final String IMAGE_URL_PREFIX = "/js/a/py/files/";
|
|
|
-
|
|
|
- /** Matplotlib 配置:无头渲染 + 中文字体(Windows 优先雅黑/黑体,Linux 回退 DejaVu Sans) */
|
|
|
- private static final String MPL_RC = """
|
|
|
- backend: Agg
|
|
|
- font.family: sans-serif
|
|
|
- font.sans-serif: Microsoft YaHei, SimHei, DejaVu Sans
|
|
|
- axes.unicode_minus: False
|
|
|
- """;
|
|
|
-
|
|
|
- /**
|
|
|
- * 快照文件名前缀。
|
|
|
- *
|
|
|
- * <p>文件名里带<b>工作空间 ID</b>({@code case-{workspaceId}.db}):本系统是多用户、多工作空间并存的,
|
|
|
- * 通用文件名一旦被挪到同一目录就会互相覆盖,也不利于排障时辨认归属。
|
|
|
- */
|
|
|
- private static final String SNAPSHOT_PREFIX = "case-";
|
|
|
-
|
|
|
- /** 关系图输出辅助模块:每次执行注入沙箱,模型用 {@code from zgraph import emit_relation_graph} 调用 */
|
|
|
- private static final String RELATION_HELPER_MODULE = "zgraph.py";
|
|
|
-
|
|
|
- /** 关系图载荷文件名:辅助模块写出,执行后由后端读取并透传给前端 */
|
|
|
- private static final String RELATION_GRAPH_FILE = "relation_graph.json";
|
|
|
-
|
|
|
- /** 关系图 JSON 读取上限:超过说明模型没有先聚合,直接给可读错误 */
|
|
|
- private static final long MAX_RELATION_GRAPH_BYTES = 2L * 1024 * 1024;
|
|
|
-
|
|
|
- /** Python 输出目录的执行归属文件:第一行 userId,第二行 sessionId */
|
|
|
-
|
|
|
- /** 内联输出上限的硬上限(与 ZCode 的 BASH_MAX_OUTPUT_LENGTH 上限一致) */
|
|
|
- private static final int MAX_INLINE_OUTPUT_CHARS = 150_000;
|
|
|
-
|
|
|
- /** 截断时完整输出落盘的文件名(放在 py-out/{execId} 下) */
|
|
|
- private static final String STDOUT_LOG = "stdout.log";
|
|
|
- private static final String STDERR_LOG = "stderr.log";
|
|
|
-
|
|
|
- /**
|
|
|
- * 关系图辅助模块源码。
|
|
|
- *
|
|
|
- * <p>为什么由后端注入:给模型一个稳定的关系图序列化入口,避免每次手写节点/边 JSON。
|
|
|
- * Python 代码拥有完整文件/进程/网络权限,模型也可以直接用 {@code open}/{@code pathlib}
|
|
|
- * 写 HTML/CSV;这里的小工具<b>只做序列化</b>,节点/边的业务口径仍全部由模型在 Python 里决定。
|
|
|
- */
|
|
|
- private static final String RELATION_HELPER_SOURCE = """
|
|
|
- # 关系图输出辅助模块(后端注入,随沙箱清理)
|
|
|
- import json
|
|
|
- import math
|
|
|
-
|
|
|
-
|
|
|
- def _records(value):
|
|
|
- if value is None:
|
|
|
- return []
|
|
|
- if hasattr(value, "to_dict"):
|
|
|
- try:
|
|
|
- return value.to_dict("records")
|
|
|
- except TypeError:
|
|
|
- pass
|
|
|
- return list(value)
|
|
|
-
|
|
|
-
|
|
|
- def _clean(value):
|
|
|
- if isinstance(value, dict):
|
|
|
- return {str(k): _clean(v) for k, v in value.items()}
|
|
|
- if isinstance(value, (list, tuple)):
|
|
|
- return [_clean(v) for v in value]
|
|
|
- # pandas / numpy 标量(含 float32 的 NaN)先转成 Python 原生类型
|
|
|
- if hasattr(value, "item"):
|
|
|
- try:
|
|
|
- value = value.item()
|
|
|
- except Exception:
|
|
|
- pass
|
|
|
- if isinstance(value, float) and (math.isnan(value) or math.isinf(value)):
|
|
|
- return None
|
|
|
- return value
|
|
|
-
|
|
|
-
|
|
|
- def emit_relation_graph(nodes=None, edges=None, title=None):
|
|
|
- # nodes: list[dict] / DataFrame -> {id, label, type, value}
|
|
|
- # edges: list[dict] / DataFrame -> {source, target, relation, weight, directed}
|
|
|
- # relation 是关系线标签(如通话/转账/亲属);缺失时回退 label,再回退“关联”
|
|
|
- node_records = _clean(_records(nodes))
|
|
|
- edge_records = _clean(_records(edges))
|
|
|
- missing_relation = 0
|
|
|
- for edge in edge_records:
|
|
|
- if isinstance(edge, dict) and not edge.get("relation") and not edge.get("label"):
|
|
|
- edge["relation"] = "关联"
|
|
|
- missing_relation += 1
|
|
|
- payload = {"nodes": node_records, "edges": edge_records}
|
|
|
- if title:
|
|
|
- payload["title"] = str(title)[:100]
|
|
|
- with open("relation_graph.json", "w", encoding="utf-8") as f:
|
|
|
- json.dump(payload, f, ensure_ascii=False, default=str)
|
|
|
- print("[relation-graph] %d nodes, %d edges -> relation_graph.json"
|
|
|
- % (len(payload["nodes"]), len(payload["edges"])))
|
|
|
- if missing_relation:
|
|
|
- print("[relation-graph] warning: %d edges have no relation; labeled 关联"
|
|
|
- % missing_relation)
|
|
|
- """;
|
|
|
-
|
|
|
- private final PythonProperties pythonProperties;
|
|
|
- private final CaseInfoMapper caseInfoMapper;
|
|
|
- private final CaseDataSourceRegistry caseDataSourceRegistry;
|
|
|
- private final StorageLayout storageLayout;
|
|
|
- private final AnalysisWorkspaceService analysisWorkspaceService;
|
|
|
-
|
|
|
- public PythonExecutor(PythonProperties pythonProperties,
|
|
|
- CaseInfoMapper caseInfoMapper,
|
|
|
- CaseDataSourceRegistry caseDataSourceRegistry,
|
|
|
- StorageLayout storageLayout,
|
|
|
- AnalysisWorkspaceService analysisWorkspaceService) {
|
|
|
- this.pythonProperties = pythonProperties;
|
|
|
- this.caseInfoMapper = caseInfoMapper;
|
|
|
- this.caseDataSourceRegistry = caseDataSourceRegistry;
|
|
|
- this.storageLayout = storageLayout;
|
|
|
- this.analysisWorkspaceService = analysisWorkspaceService;
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 解析后的 Python 解释器路径(懒加载,配置在启动后不会变)。
|
|
|
- */
|
|
|
- private volatile String resolvedPythonCommand;
|
|
|
-
|
|
|
- /**
|
|
|
- * 解析 Python 解释器:默认使用随项目分发的内置 Python,不依赖系统 PATH。
|
|
|
- *
|
|
|
- * <p>`etl.python.command` 若显式配置为路径(含分隔符 / .exe / 以 . 开头),优先按配置执行;
|
|
|
- * 相对路径按项目根目录解析。内置解释器候选同时覆盖两种目录布局:</p>
|
|
|
- * <ul>
|
|
|
- * <li>源码仓库:{@code qingjian/system/python/python.exe};</li>
|
|
|
- * <li>独立部署包:{@code <root>/python/python.exe}。</li>
|
|
|
- * </ul>
|
|
|
- * <p>只有内置解释器都不存在时才回退到配置值(兼容开发机已有 Python 的情况)。</p>
|
|
|
- */
|
|
|
- private String pythonCommand() {
|
|
|
- String cached = resolvedPythonCommand;
|
|
|
- if (cached != null) {
|
|
|
- return cached;
|
|
|
- }
|
|
|
- synchronized (this) {
|
|
|
- if (resolvedPythonCommand == null) {
|
|
|
- resolvedPythonCommand = resolvePythonCommand();
|
|
|
- }
|
|
|
- return resolvedPythonCommand;
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- private String resolvePythonCommand() {
|
|
|
- String configured = pythonProperties.getCommand();
|
|
|
- configured = configured == null ? "" : configured.trim();
|
|
|
- boolean looksLikePath = configured.contains("/") || configured.contains("\\")
|
|
|
- || configured.endsWith(".exe") || configured.startsWith(".");
|
|
|
- if (looksLikePath) {
|
|
|
- Path configuredPath = Paths.get(configured);
|
|
|
- Path absolute = configuredPath.isAbsolute()
|
|
|
- ? configuredPath
|
|
|
- : PathConst.ROOT_PATH.resolve(configured);
|
|
|
- if (Files.isRegularFile(absolute)) {
|
|
|
- return absolute.toAbsolutePath().normalize().toString();
|
|
|
- }
|
|
|
- log.warn("配置的 Python 解释器不存在,尝试使用内置解释器: {}", absolute);
|
|
|
- }
|
|
|
- for (Path candidate : List.of(
|
|
|
- PathConst.PYTHON_PATH_WIN,
|
|
|
- PathConst.PYTHON_PATH_LINUX,
|
|
|
- PathConst.ROOT_PATH.resolve("python").resolve("python.exe"),
|
|
|
- PathConst.ROOT_PATH.resolve("python").resolve("bin").resolve("python3"))) {
|
|
|
- if (Files.isRegularFile(candidate)) {
|
|
|
- String command = candidate.toAbsolutePath().normalize().toString();
|
|
|
- log.info("使用内置 Python 解释器: {}", command);
|
|
|
- return command;
|
|
|
- }
|
|
|
- }
|
|
|
- String fallback = configured.isEmpty() ? "python" : configured;
|
|
|
- log.warn("未找到内置 Python 解释器,回退到系统命令: {}", fallback);
|
|
|
- return fallback;
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 依赖检测缓存(null = 未检测;true/false = 检测结果)
|
|
|
- */
|
|
|
- private volatile Boolean available;
|
|
|
-
|
|
|
- /**
|
|
|
- * 环境就绪检测:python 可用且 pandas/duckdb/matplotlib 可导入(结果缓存)
|
|
|
- */
|
|
|
- public boolean isAvailable() {
|
|
|
- if (!pythonProperties.isEnabled()) {
|
|
|
- return false;
|
|
|
- }
|
|
|
- if (available == null) {
|
|
|
- synchronized (this) {
|
|
|
- if (available == null) {
|
|
|
- available = detect();
|
|
|
- }
|
|
|
- }
|
|
|
- }
|
|
|
- return available;
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 单路输出内联字符上限:配置值钳到 [1, 150000],非法值回退 30000。
|
|
|
- * 超出后由 {@link OutputCollector} 保留头尾并把完整输出落盘。
|
|
|
- */
|
|
|
- private int resolveMaxOutputChars() {
|
|
|
- int configured = pythonProperties.getMaxOutputChars();
|
|
|
- if (configured <= 0) {
|
|
|
- configured = 30_000;
|
|
|
- }
|
|
|
- return Math.min(configured, MAX_INLINE_OUTPUT_CHARS);
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 当前解析到的 Python 解释器命令(健康检查/排障用)。
|
|
|
- */
|
|
|
- public String pythonCommandForProbe() {
|
|
|
- return pythonCommand();
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 探测可选依赖(分析/建模/办公常用库)是否可导入。
|
|
|
- *
|
|
|
- * <p>设计 §8.3 要求「启动完整 import 健康检查」:随包 wheel、锁定版本、禁止运行时 pip install。
|
|
|
- * 缺失只记日志、不阻断启动;工具/技能自行按可用性降级。
|
|
|
- *
|
|
|
- * @return module → 是否可导入;探测进程失败时返回空 Map
|
|
|
- */
|
|
|
- public Map<String, Boolean> probeOptionalDependencies() {
|
|
|
- List<String> modules = List.of(
|
|
|
- "pyarrow", "scipy", "sklearn", "seaborn", "plotly",
|
|
|
- "pptx", "reportlab", "pdfplumber", "xlsxwriter");
|
|
|
- String script = "import json\n"
|
|
|
- + "mods=" + modules.stream().map(m -> "'" + m + "'")
|
|
|
- .collect(java.util.stream.Collectors.joining(",", "[", "]")) + "\n"
|
|
|
- + "res={}\n"
|
|
|
- + "for m in mods:\n"
|
|
|
- + " try:\n"
|
|
|
- + " __import__(m)\n"
|
|
|
- + " res[m]=True\n"
|
|
|
- + " except Exception:\n"
|
|
|
- + " res[m]=False\n"
|
|
|
- + "print(json.dumps(res))\n";
|
|
|
- try {
|
|
|
- Process process = new ProcessBuilder(pythonCommand(), "-c", script).start();
|
|
|
- if (!process.waitFor(60, TimeUnit.SECONDS)) {
|
|
|
- process.destroyForcibly();
|
|
|
- return Map.of();
|
|
|
- }
|
|
|
- String output = new String(process.getInputStream().readAllBytes(),
|
|
|
- StandardCharsets.UTF_8).trim();
|
|
|
- int lineStart = output.lastIndexOf('\n');
|
|
|
- String json = lineStart >= 0 ? output.substring(lineStart + 1) : output;
|
|
|
- return com.zsjz.ai.common.utils.Json.objectMapper().readValue(json, Map.class);
|
|
|
- } catch (Exception e) {
|
|
|
- log.info("Python 可选依赖探测失败: {}", e.getMessage());
|
|
|
- return Map.of();
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 执行 Python 代码(子进程沙箱)
|
|
|
- *
|
|
|
- * @param code Python 3 源码
|
|
|
- * @return 执行结果(exitCode/stdout/stderr/imageUrls/durationMs/error)
|
|
|
- */
|
|
|
- public PythonResult execute(String code) {
|
|
|
- return execute(code, null, null);
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 执行 Python,并记录执行归属(用户 + 会话),供分析工作区按归属隔离。
|
|
|
- */
|
|
|
- public PythonResult execute(String code, String userId, String sessionId) {
|
|
|
- return execute(code, userId, sessionId, null);
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 执行 Python,并记录执行归属(用户 + 会话),供分析工作区按归属隔离。
|
|
|
- *
|
|
|
- * <p>{@code explicitCaseId} 来自工具侧 {@code RuntimeContext}({@code AiRuntimeKeys.CASE_ID}):
|
|
|
- *ScopedValue 绑定只在绑定线程内有效,专家/异步段等外部长调用结束后,同批后续工具可能落在
|
|
|
- * 无绑定的 Reactor 线程上,此时 {@link CaseContextHolder#get()} 拿不到案件——
|
|
|
- * 调用方显式把案件 ID 从上下文传进来即可不再依赖线程绑定。
|
|
|
- */
|
|
|
- public PythonResult execute(String code, String userId, String sessionId, Long explicitCaseId) {
|
|
|
- long start = System.currentTimeMillis();
|
|
|
- if (!isAvailable()) {
|
|
|
- return PythonResult.error("Python 执行环境不可用(未安装或缺少依赖:pip install pandas duckdb matplotlib)");
|
|
|
- }
|
|
|
- if (code == null || code.isBlank()) {
|
|
|
- return PythonResult.error("Python 代码不能为空");
|
|
|
- }
|
|
|
- // 案件上下文:显式传入优先(随 RuntimeContext 流转,不依赖线程绑定),其次读
|
|
|
- // CaseContextHolder(CaseScopeTool 在工具调用入口用 runWith 显式绑定的作用域值)。
|
|
|
- // 这里不能用 StateManager.getCaseId() —— 它取不到时返回哨兵 888888,
|
|
|
- // 会导致 selectById(888888) 拿到 null 再 NPE,报错信息毫无指向性。
|
|
|
- Long workspaceId = explicitCaseId != null ? explicitCaseId : CaseContextHolder.get();
|
|
|
- if (workspaceId == null) {
|
|
|
- return PythonResult.error("当前没有打开的案件,无法执行 Python 分析");
|
|
|
- }
|
|
|
- CaseInfo caseInfo = caseInfoMapper.selectById(workspaceId);
|
|
|
- if (caseInfo == null) {
|
|
|
- return PythonResult.error("案件不存在或已被删除: workspaceId=" + workspaceId);
|
|
|
- }
|
|
|
- String dbFile = caseInfo.getDbPath();
|
|
|
- if (dbFile == null) {
|
|
|
- return PythonResult.error("工作空间数据库不存在或未初始化: workspaceId=" + workspaceId);
|
|
|
- }
|
|
|
-
|
|
|
- String execId = UUID.randomUUID().toString();
|
|
|
- // 持久分析工作区(analysis.workspace.enabled):cwd=work、交付物=outputs、运行记录=runs。
|
|
|
- // 关闭时回退「每次执行独立临时沙箱」的旧行为。
|
|
|
- AnalysisWorkspaceService.Workspace analysisWorkspace = null;
|
|
|
- Long persistentUserId = parseUserId(userId);
|
|
|
- if (analysisWorkspaceService.isEnabled() && persistentUserId != null
|
|
|
- && sessionId != null && !sessionId.isBlank()) {
|
|
|
- try {
|
|
|
- analysisWorkspace = analysisWorkspaceService.prepare(
|
|
|
- workspaceId, persistentUserId, sessionId);
|
|
|
- } catch (IOException e) {
|
|
|
- return PythonResult.error("创建分析工作区失败: " + e.getMessage());
|
|
|
- }
|
|
|
- }
|
|
|
- boolean persistent = analysisWorkspace != null;
|
|
|
- Path sandbox = persistent
|
|
|
- ? analysisWorkspace.work()
|
|
|
- : storageLayout.pythonSandboxDir(workspaceId, execId);
|
|
|
- Path outDir = persistent
|
|
|
- ? analysisWorkspace.outputs()
|
|
|
- : storageLayout.pythonOutDir(workspaceId, execId);
|
|
|
- Path runDir = persistent ? analysisWorkspace.runs().resolve(execId) : outDir; long runStartedAt = System.currentTimeMillis();
|
|
|
- ACTIVE_EXEC_IDS.add(execId);
|
|
|
- try {
|
|
|
- Files.createDirectories(sandbox);
|
|
|
- if (persistent) {
|
|
|
- // 运行记录目录只在工作区模式预建;旧沙箱模式按需创建(落盘日志时才建),
|
|
|
- // 避免每次执行都留下一个空的 py-out/{execId} 目录。
|
|
|
- Files.createDirectories(runDir);
|
|
|
- }
|
|
|
- // main.py 放脚本目录:工作区模式用 runs/{execId}(work 留给模型的可复用文件);
|
|
|
- // 旧沙箱模式仍放临时沙箱(随沙箱删除,不在 py-out 留垃圾)。
|
|
|
- Path scriptDir = persistent ? runDir : sandbox;
|
|
|
- Path mainPy = scriptDir.resolve("main.py");
|
|
|
- Files.writeString(mainPy, code);
|
|
|
- // 关系图输出辅助模块:只做序列化,不参与关系分析(见 RELATION_HELPER_SOURCE)
|
|
|
- try {
|
|
|
- Files.writeString(scriptDir.resolve(RELATION_HELPER_MODULE), RELATION_HELPER_SOURCE);
|
|
|
- } catch (IOException e) {
|
|
|
- return PythonResult.error("关系图辅助模块写入失败: " + e.getMessage());
|
|
|
- }
|
|
|
-
|
|
|
- ProcessBuilder pb = new ProcessBuilder(pythonCommand(), mainPy.toAbsolutePath().toString())
|
|
|
- .directory(sandbox.toFile());
|
|
|
- // 指向快照副本:原库被本进程写锁持有,子进程连只读都打不开(见类注释)
|
|
|
- String pythonDbFile = resolvePythonDbFile(workspaceId, dbFile);
|
|
|
- pb.environment().put(ENV_DB_PATH, pythonDbFile);
|
|
|
- pb.environment().put("MPLBACKEND", "Agg"); // matplotlib 无头渲染
|
|
|
- // 中文字体配置:固定在工作空间下,字体缓存只建一次;否则中文图表会显示方框
|
|
|
- Path mplDir = storageLayout.pythonMplDir(workspaceId);
|
|
|
- Files.createDirectories(mplDir);
|
|
|
- Path mplRc = mplDir.resolve("matplotlibrc");
|
|
|
- if (!Files.exists(mplRc)) {
|
|
|
- Files.writeString(mplRc, MPL_RC);
|
|
|
- }
|
|
|
- pb.environment().put("MPLCONFIGDIR", mplDir.toAbsolutePath().toString());
|
|
|
-
|
|
|
- Process process = pb.start();
|
|
|
- int maxInlineChars = resolveMaxOutputChars();
|
|
|
- long maxFullChars = pythonProperties.getMaxFullOutputChars();
|
|
|
- // 日志目录:工作区模式进 runs/{execId}(永久保留);旧沙箱模式仍在 py-out
|
|
|
- Path logDir = persistent ? runDir : outDir;
|
|
|
- OutputCollector stdout = new OutputCollector(process.getInputStream(),
|
|
|
- maxInlineChars, maxFullChars, logDir.resolve(STDOUT_LOG));
|
|
|
- OutputCollector stderr = new OutputCollector(process.getErrorStream(),
|
|
|
- maxInlineChars, maxFullChars, logDir.resolve(STDERR_LOG));
|
|
|
- stdout.start();
|
|
|
- stderr.start();
|
|
|
-
|
|
|
- boolean finished = process.waitFor(pythonProperties.getTimeoutSeconds(), TimeUnit.SECONDS);
|
|
|
- if (!finished) {
|
|
|
- process.destroyForcibly();
|
|
|
- process.waitFor(5, TimeUnit.SECONDS);
|
|
|
- if (persistent) {
|
|
|
- analysisWorkspaceService.writeRunMeta(runDir, runMeta(execId, workspaceId, userId,
|
|
|
- sessionId, -1, System.currentTimeMillis() - runStartedAt, code,
|
|
|
- stdout.getTotalChars(), stderr.getTotalChars(), "执行超时"));
|
|
|
- }
|
|
|
- return PythonResult.error("执行超时(" + pythonProperties.getTimeoutSeconds()
|
|
|
- + " 秒)已终止,请优化代码或减少数据量");
|
|
|
- }
|
|
|
- stdout.join(5000);
|
|
|
- stderr.join(5000);
|
|
|
-
|
|
|
- // 必须在 collectGeneratedFiles 之前读:该步骤会把 relation_graph.json 移到 py-out
|
|
|
- RelationGraphFile relationGraph = readRelationGraph(sandbox);
|
|
|
- // 旧沙箱模式:图片移入 py-out 并返回可内联 URL;工作区模式文件原地保留
|
|
|
- List<String> imageUrls = persistent ? List.of()
|
|
|
- : collectGeneratedFiles(workspaceId, execId, sandbox);
|
|
|
- // 只有截断时才落盘输出日志;若本目录没有图片,collectGeneratedFiles 不会触发 LRU 清理
|
|
|
- if (!persistent && (stdout.isPersisted() || stderr.isPersisted())) {
|
|
|
- evictOldExecs(storageLayout.pythonOutRoot(workspaceId));
|
|
|
- }
|
|
|
- long durationMs = System.currentTimeMillis() - start;
|
|
|
- log.info("Python 执行完成: workspaceId={}, execId={}, persistent={}, exitCode={}, images={}, "
|
|
|
- + "relationGraph={}, stdoutChars={}, stderrChars={}, "
|
|
|
- + "stdoutTruncated={}, stderrTruncated={}, costMs={}",
|
|
|
- workspaceId, execId, persistent, process.exitValue(), imageUrls.size(),
|
|
|
- relationGraph.json() != null,
|
|
|
- stdout.getTotalChars(), stderr.getTotalChars(),
|
|
|
- stdout.isTruncated(), stderr.isTruncated(), durationMs);
|
|
|
- if (persistent) {
|
|
|
- analysisWorkspaceService.writeRunMeta(runDir, runMeta(execId, workspaceId, userId,
|
|
|
- sessionId, process.exitValue(), durationMs, code,
|
|
|
- stdout.getTotalChars(), stderr.getTotalChars(), null));
|
|
|
- }
|
|
|
- return new PythonResult(process.exitValue(), stdout.getContent(), stderr.getContent(),
|
|
|
- imageUrls, durationMs, null, relationGraph.json(), relationGraph.error(),
|
|
|
- stdout.isTruncated(), stderr.isTruncated(),
|
|
|
- stdout.getTotalChars(), stderr.getTotalChars(),
|
|
|
- stdout.getPersistedPath(), stderr.getPersistedPath());
|
|
|
- } catch (IOException e) {
|
|
|
- return PythonResult.error("Python 进程启动失败: " + e.getMessage());
|
|
|
- } catch (InterruptedException e) {
|
|
|
- Thread.currentThread().interrupt();
|
|
|
- return PythonResult.error("执行被中断: " + e.getMessage());
|
|
|
- } finally {
|
|
|
- if (!persistent) {
|
|
|
- deleteRecursively(sandbox);
|
|
|
- }
|
|
|
- ACTIVE_EXEC_IDS.remove(execId);
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 运行记录(runs/{execId}/meta.json):永久保留,便于排障时回溯代码与输出。
|
|
|
- */
|
|
|
- private static java.util.Map<String, Object> runMeta(String execId, Long caseId, String userId,
|
|
|
- String sessionId, int exitCode,
|
|
|
- long durationMs, String code,
|
|
|
- long stdoutChars, long stderrChars,
|
|
|
- String error) {
|
|
|
- java.util.Map<String, Object> meta = new java.util.LinkedHashMap<>();
|
|
|
- meta.put("execId", execId);
|
|
|
- meta.put("caseId", caseId);
|
|
|
- meta.put("userId", userId);
|
|
|
- meta.put("sessionId", sessionId);
|
|
|
- meta.put("exitCode", exitCode);
|
|
|
- meta.put("durationMs", durationMs);
|
|
|
- meta.put("stdoutChars", stdoutChars);
|
|
|
- meta.put("stderrChars", stderrChars);
|
|
|
- if (error != null) {
|
|
|
- meta.put("error", error);
|
|
|
- }
|
|
|
- // 代码原文入库(文件系统):工作区永久保留,排障时可直接复跑
|
|
|
- meta.put("code", code);
|
|
|
- return meta;
|
|
|
- }
|
|
|
-
|
|
|
- private static Long parseUserId(String userId) {
|
|
|
- if (userId == null || userId.isBlank()) {
|
|
|
- return null;
|
|
|
- }
|
|
|
- try {
|
|
|
- return Long.valueOf(userId.trim());
|
|
|
- } catch (NumberFormatException e) {
|
|
|
- return null;
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 读取关系图载荷(沙箱内 {@code relation_graph.json})。
|
|
|
- *
|
|
|
- * <p>包级可见:单测直接验证「不存在 / 正常 / 超限」三种分支,不需要真的起 Python 进程。
|
|
|
- */
|
|
|
- static RelationGraphFile readRelationGraph(Path sandbox) {
|
|
|
- Path file = sandbox.resolve(RELATION_GRAPH_FILE);
|
|
|
- if (!Files.isRegularFile(file)) {
|
|
|
- return new RelationGraphFile(null, null);
|
|
|
- }
|
|
|
- try {
|
|
|
- long size = Files.size(file);
|
|
|
- if (size > MAX_RELATION_GRAPH_BYTES) {
|
|
|
- return new RelationGraphFile(null,
|
|
|
- "relation_graph.json 超过 2MB(" + size + " 字节),请在 Python 里聚合/取 TOP N 后再输出");
|
|
|
- }
|
|
|
- return new RelationGraphFile(Files.readString(file), null);
|
|
|
- } catch (IOException e) {
|
|
|
- return new RelationGraphFile(null, "读取 relation_graph.json 失败: " + e.getMessage());
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /** 关系图载荷读取结果:json 与 error 互斥;两者都为 null 表示模型没调用 emit_relation_graph */
|
|
|
- record RelationGraphFile(String json, String error) {
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 执行结果 record(error 非空表示未正常执行)。
|
|
|
- *
|
|
|
- * <p>{@code relationGraphJson} / {@code relationGraphError} 对应沙箱里的
|
|
|
- * {@code relation_graph.json}:前者是模型调用 {@code emit_relation_graph} 写出的原文,
|
|
|
- * 后者是读取失败的原因,两者互斥;都为 null 表示本次没有生成关系图。
|
|
|
- *
|
|
|
- * <p><b>输出截断</b>:{@code stdout/stderr} 已按内联上限保留头尾(中间有截断说明);
|
|
|
- * {@code *Truncated} 为真实截断标志,{@code *Chars} 是原始总字符数,
|
|
|
- * {@code *FullOutputPath} 是完整输出落盘路径(未截断或落盘失败时为 null)。
|
|
|
- */
|
|
|
- public record PythonResult(int exitCode, String stdout, String stderr,
|
|
|
- List<String> imageUrls, long durationMs, String error,
|
|
|
- String relationGraphJson, String relationGraphError,
|
|
|
- boolean stdoutTruncated, boolean stderrTruncated,
|
|
|
- long stdoutChars, long stderrChars,
|
|
|
- String stdoutFullOutputPath, String stderrFullOutputPath) {
|
|
|
-
|
|
|
- /**
|
|
|
- * 兼容旧调用/单测:没有截断元数据时按「未截断」处理。
|
|
|
- */
|
|
|
- public PythonResult(int exitCode, String stdout, String stderr,
|
|
|
- List<String> imageUrls, long durationMs, String error,
|
|
|
- String relationGraphJson, String relationGraphError) {
|
|
|
- this(exitCode, stdout, stderr, imageUrls, durationMs, error,
|
|
|
- relationGraphJson, relationGraphError,
|
|
|
- false, false,
|
|
|
- stdout == null ? 0L : stdout.length(),
|
|
|
- stderr == null ? 0L : stderr.length(),
|
|
|
- null, null);
|
|
|
- }
|
|
|
-
|
|
|
- static PythonResult error(String message) {
|
|
|
- return new PythonResult(-1, "", "", List.of(), 0, message, null, null);
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- // ==================== 内部实现 ====================
|
|
|
-
|
|
|
- /**
|
|
|
- * 检测 Python 与三方库可用性(结果缓存;失败打印安装提示)
|
|
|
- */
|
|
|
- private boolean detect() {
|
|
|
- try {
|
|
|
- String command = pythonCommand();
|
|
|
- Process process = new ProcessBuilder(command, "-c", CHECK_IMPORTS).start();
|
|
|
- if (!process.waitFor(30, TimeUnit.SECONDS)) {
|
|
|
- process.destroyForcibly();
|
|
|
- process.waitFor(5, TimeUnit.SECONDS);
|
|
|
- log.error("Python 依赖检测超时(execute_python 工具将不注册): command={}", command);
|
|
|
- return false;
|
|
|
- }
|
|
|
- if (process.exitValue() == 0) {
|
|
|
- log.info("Python 执行环境就绪: command={}", command);
|
|
|
- return true;
|
|
|
- }
|
|
|
- log.info("Python 执行环境不可用(command={},需安装依赖: pip install pandas duckdb matplotlib),"
|
|
|
- + "execute_python 工具将不注册", command);
|
|
|
- return false;
|
|
|
- } catch (Exception e) {
|
|
|
- log.error("Python 检测失败(execute_python 工具将不注册): command={}, error={}",
|
|
|
- pythonCommand(), e.getMessage());
|
|
|
- return false;
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 按案件互斥快照导出:读指纹 → 比对 → exportSnapshot → 写指纹 是一串 check-then-act,
|
|
|
- * 同案件两段 Python 并发执行且源库刚变化时,A 导出完成后 B 可能拿着旧指纹误判"可复用"
|
|
|
- * 而读到陈旧数据,或与 Registry.close 的回收窗口交错。按 workspaceId 串行化整段流程。
|
|
|
- */
|
|
|
- private static final java.util.concurrent.ConcurrentHashMap<Long, Object> SNAPSHOT_LOCKS =
|
|
|
- new java.util.concurrent.ConcurrentHashMap<>();
|
|
|
-
|
|
|
- /**
|
|
|
- * 正在执行中的 execId:py-out 的 LRU 清理必须跳过这些目录,
|
|
|
- * 否则超额时 A 刚产出的图片会被 B 的清理线程删掉(前端 404)
|
|
|
- */
|
|
|
- private static final java.util.Set<String> ACTIVE_EXEC_IDS =
|
|
|
- java.util.concurrent.ConcurrentHashMap.newKeySet();
|
|
|
-
|
|
|
- /**
|
|
|
- * 解析注入给 Python 的库文件路径:优先「当前案件的快照副本」。
|
|
|
- *
|
|
|
- * <p>导出时机用源库指纹判断:主文件与 WAL 的大小/修改时间都没变 → 复用已有快照。
|
|
|
- * 任何写入都会改 WAL,因此数据新鲜度与「每次重新导出」等价,代价只在真正变更时付一次。
|
|
|
- *
|
|
|
- * <p><b>不再回退原库(P1-15)</b>:原库被本进程以写锁持有,Python 子进程根本打不开,
|
|
|
- * 静默回退只会把问题推迟成难排查的"执行环境不可用"。导出失败重试一次,
|
|
|
- * 仍失败则显式报错,让上层给用户明确提示。
|
|
|
- */
|
|
|
- private String resolvePythonDbFile(Long workspaceId, String dbFile) {
|
|
|
- if (!pythonProperties.isSnapshotEnabled()) {
|
|
|
- return dbFile;
|
|
|
- }
|
|
|
- Path db = storageLayout.resolve(dbFile);
|
|
|
- Path snapshot = storageLayout.pythonSnapshot(workspaceId);
|
|
|
- Path meta = snapshot.resolveSibling(SNAPSHOT_PREFIX + workspaceId + ".meta");
|
|
|
- Object lock = SNAPSHOT_LOCKS.computeIfAbsent(workspaceId, key -> new Object());
|
|
|
- synchronized (lock) {
|
|
|
- try {
|
|
|
- String fingerprint = sourceFingerprint(db);
|
|
|
- if (Files.isRegularFile(snapshot) && Files.isRegularFile(meta)
|
|
|
- && fingerprint.equals(Files.readString(meta).trim())) {
|
|
|
- return snapshot.toAbsolutePath().toString();
|
|
|
- }
|
|
|
- // Windows 上目标文件被上一个 Python 子进程占用时 replace 会失败,
|
|
|
- // 这里给一次重试机会再放弃
|
|
|
- if (!caseDataSourceRegistry.exportSnapshot(workspaceId, snapshot)
|
|
|
- && !caseDataSourceRegistry.exportSnapshot(workspaceId, snapshot)) {
|
|
|
- throw new IllegalStateException("案件数据库快照导出失败(Python 分析依赖快照副本,"
|
|
|
- + "不可回退被本进程锁定的原库),请稍后重试: caseId=" + workspaceId);
|
|
|
- }
|
|
|
- // 指纹在导出之后再取一次:避免把导出过程自身对源库的副作用算进来
|
|
|
- Files.writeString(meta, sourceFingerprint(db));
|
|
|
- return snapshot.toAbsolutePath().toString();
|
|
|
- } catch (IllegalStateException e) {
|
|
|
- throw e;
|
|
|
- } catch (Exception e) {
|
|
|
- throw new IllegalStateException("准备 Python 数据库快照失败: " + e.getMessage(), e);
|
|
|
- }
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 源库指纹:主文件 + WAL 的大小与修改时间。任一写入都会动 WAL,因此指纹变化 = 数据变了。
|
|
|
- */
|
|
|
- private static String sourceFingerprint(Path dbFile) {
|
|
|
- StringBuilder sb = new StringBuilder();
|
|
|
- sb.append(statOf(dbFile)).append('|').append(statOf(Path.of(dbFile + ".wal")));
|
|
|
- return sb.toString();
|
|
|
- }
|
|
|
-
|
|
|
- private static String statOf(Path file) {
|
|
|
- try {
|
|
|
- if (!Files.exists(file)) {
|
|
|
- return "-";
|
|
|
- }
|
|
|
- return Files.size(file) + "@" + Files.getLastModifiedTime(file).toMillis();
|
|
|
- } catch (Exception e) {
|
|
|
- return "?";
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 捕获沙箱内生成的图片:移动到 py-out/{execId}/ 并返回可内联 URL。
|
|
|
- *
|
|
|
- * <p>收集范围:沙箱根目录 + {@code outputs/} 子树(工具描述约定交付物写
|
|
|
- * {@code ./outputs},cwd 就是沙箱根);非图片文件不收集。</p>
|
|
|
- *
|
|
|
- * <p>图片返回可内联展示的 URL({@code imageUrls},py-out 里扁平存放,
|
|
|
- * 子目录用 {@code __} 连接避免 URL 多段路径);图片数量受 {@code maxImages} 限制。</p>
|
|
|
- */
|
|
|
- private List<String> collectGeneratedFiles(long workspaceId, String execId, Path sandbox) {
|
|
|
- List<String> urls = new ArrayList<>();
|
|
|
- try (Stream<Path> files = Files.walk(sandbox, 6)) {
|
|
|
- List<Path> generated = files
|
|
|
- .filter(Files::isRegularFile)
|
|
|
- .filter(p -> !Files.isSymbolicLink(p))
|
|
|
- .filter(p -> isImageFile(p.getFileName().toString()))
|
|
|
- .filter(p -> isDeliverableInSandbox(sandbox, p))
|
|
|
- .sorted(Comparator.comparing(p -> relativePath(sandbox, p)))
|
|
|
- .toList();
|
|
|
- if (generated.isEmpty()) {
|
|
|
- return urls;
|
|
|
- }
|
|
|
- Path outDir = storageLayout.pythonOutDir(workspaceId, execId);
|
|
|
- Files.createDirectories(outDir);
|
|
|
- int imageCount = 0;
|
|
|
- int maxImages = pythonProperties.getMaxImages();
|
|
|
- for (Path file : generated) {
|
|
|
- if (imageCount >= maxImages) {
|
|
|
- break;
|
|
|
- }
|
|
|
- String relative = relativePath(sandbox, file);
|
|
|
- // 图片走 /py/files/{case}/{execId}/{filename},接口只认单段文件名
|
|
|
- String flatName = relative.replace('/', '_').replace('\\', '_');
|
|
|
- Path target = uniqueTarget(outDir, flatName);
|
|
|
- Files.move(file, target);
|
|
|
- imageCount++;
|
|
|
- urls.add(IMAGE_URL_PREFIX + workspaceId + "/" + execId + "/"
|
|
|
- + target.getFileName());
|
|
|
- }
|
|
|
- evictOldExecs(storageLayout.pythonOutRoot(workspaceId));
|
|
|
- } catch (IOException e) {
|
|
|
- log.error("Python 图片捕获失败: workspaceId={}, execId={}, error={}",
|
|
|
- workspaceId, execId, e.getMessage());
|
|
|
- }
|
|
|
- return urls;
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 是否图片文件(仅图片会被收集并返回内联 URL)。
|
|
|
- */
|
|
|
- private static boolean isImageFile(String fileName) {
|
|
|
- if (fileName == null) {
|
|
|
- return false;
|
|
|
- }
|
|
|
- int dot = fileName.lastIndexOf('.');
|
|
|
- if (dot < 0 || dot == fileName.length() - 1) {
|
|
|
- return false;
|
|
|
- }
|
|
|
- String ext = fileName.substring(dot + 1).toLowerCase();
|
|
|
- return "png".equals(ext) || "jpg".equals(ext) || "jpeg".equals(ext)
|
|
|
- || "gif".equals(ext) || "webp".equals(ext) || "bmp".equals(ext)
|
|
|
- || "svg".equals(ext);
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 沙箱内哪些文件算交付物:根目录文件(历史行为)+ {@code outputs/} 子树
|
|
|
- * (工具描述约定的交付物目录)。其它中间目录(如 {@code work/})不收集,
|
|
|
- * 避免把模型的过程文件一并收集。
|
|
|
- */
|
|
|
- private static boolean isDeliverableInSandbox(Path sandbox, Path file) {
|
|
|
- Path parent = file.getParent();
|
|
|
- if (parent == null || parent.equals(sandbox)) {
|
|
|
- return true;
|
|
|
- }
|
|
|
- Path relative = sandbox.relativize(file);
|
|
|
- return relative.getNameCount() > 1
|
|
|
- && "outputs".equalsIgnoreCase(relative.getName(0).toString());
|
|
|
- }
|
|
|
-
|
|
|
- private static String relativePath(Path root, Path file) {
|
|
|
- return root.relativize(file).toString().replace('\\', '/');
|
|
|
- }
|
|
|
-
|
|
|
- /** py-out 内的同名文件兜底:图片扁平化后可能与根目录同名图片冲突 */
|
|
|
- private static Path uniqueTarget(Path dir, String name) {
|
|
|
- Path target = dir.resolve(name);
|
|
|
- if (!Files.exists(target)) {
|
|
|
- return target;
|
|
|
- }
|
|
|
- int dot = name.lastIndexOf('.');
|
|
|
- String base = dot > 0 ? name.substring(0, dot) : name;
|
|
|
- String ext = dot > 0 ? name.substring(dot) : "";
|
|
|
- for (int i = 1; i < 1000; i++) {
|
|
|
- Path candidate = dir.resolve(base + "-" + i + ext);
|
|
|
- if (!Files.exists(candidate)) {
|
|
|
- return candidate;
|
|
|
- }
|
|
|
- }
|
|
|
- return dir.resolve(base + "-" + UUID.randomUUID() + ext);
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * LRU 清理 py-out 超额执行目录。
|
|
|
- * <b>跳过在途执行</b>(ACTIVE_EXEC_IDS):并发执行时,刚产出图片的目录
|
|
|
- * 若恰好排在最旧一侧会被误删,前端取图 404(P2-23)
|
|
|
- */
|
|
|
- private void evictOldExecs(Path pyOutRoot) {
|
|
|
- int max = pythonProperties.getMaxHistoryExecs();
|
|
|
- if (max <= 0) {
|
|
|
- // 0 = 永久保留:图片要能在历史会话里长期回看,不做 LRU 清理
|
|
|
- return;
|
|
|
- }
|
|
|
- try (Stream<Path> dirs = Files.list(pyOutRoot)) {
|
|
|
- List<Path> execDirs = dirs
|
|
|
- .filter(p -> !ACTIVE_EXEC_IDS.contains(p.getFileName().toString()))
|
|
|
- .sorted(Comparator.comparingLong(
|
|
|
- p -> p.toFile().lastModified()))
|
|
|
- .toList();
|
|
|
- int excess = execDirs.size() - max;
|
|
|
- for (int i = 0; i < excess; i++) {
|
|
|
- deleteRecursively(execDirs.get(i));
|
|
|
- }
|
|
|
- } catch (IOException e) {
|
|
|
- log.debug("py-out 清理失败: {}, error={}", pyOutRoot, e.getMessage());
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 递归删除目录(沙箱清理,失败仅告警)
|
|
|
- */
|
|
|
- private static void deleteRecursively(Path dir) {
|
|
|
- if (!Files.exists(dir)) {
|
|
|
- return;
|
|
|
- }
|
|
|
- try (Stream<Path> walk = Files.walk(dir)) {
|
|
|
- walk.sorted(Comparator.reverseOrder()).forEach(p -> {
|
|
|
- try {
|
|
|
- Files.delete(p);
|
|
|
- } catch (IOException ignored) {
|
|
|
- // 清理失败不影响主流程
|
|
|
- }
|
|
|
- });
|
|
|
- } catch (IOException e) {
|
|
|
- log.debug("目录清理失败: {}, error={}", dir, e.getMessage());
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 进程输出流采集线程:内联只保留头尾,超出上限时把完整输出落盘。
|
|
|
- *
|
|
|
- * <p>只留前 N 个字符会把错误栈/汇总行(通常在最后)丢掉;这里把内联预算对半分成
|
|
|
- * 头/尾两段,中间用截断说明代替。第一次超出上限时把已读前缀写盘,后续输出继续追加,
|
|
|
- * 模型可从结果里的 {@code *_full_output_path} 取全文(用 execute_python 读取)。
|
|
|
- *
|
|
|
- * <p>落盘只在截断时发生:短输出既不需要额外文件,也不会改变返回内容。
|
|
|
- */
|
|
|
- static class OutputCollector extends Thread {
|
|
|
-
|
|
|
- private final java.io.InputStream in;
|
|
|
- private final int maxInlineChars;
|
|
|
- private final int headChars;
|
|
|
- private final int tailChars;
|
|
|
- private final long maxPersistedChars;
|
|
|
- private final Path outputPath;
|
|
|
-
|
|
|
- /** 未截断时的全文缓冲 */
|
|
|
- private final StringBuilder inline = new StringBuilder();
|
|
|
- /** 截断后的头段 */
|
|
|
- private final StringBuilder head = new StringBuilder();
|
|
|
- /** 截断后的尾段(最多 tailChars + 1,保持有界) */
|
|
|
- private final StringBuilder tail = new StringBuilder();
|
|
|
-
|
|
|
- private long totalChars;
|
|
|
- private boolean truncated;
|
|
|
- private boolean persisted;
|
|
|
- private boolean persistedTruncated;
|
|
|
- private boolean persistFailed;
|
|
|
- private java.io.BufferedWriter writer;
|
|
|
- private long persistedChars;
|
|
|
-
|
|
|
- OutputCollector(java.io.InputStream in, int maxInlineChars, long maxPersistedChars,
|
|
|
- Path outputPath) {
|
|
|
- this.in = in;
|
|
|
- this.maxInlineChars = Math.max(1, maxInlineChars);
|
|
|
- this.headChars = this.maxInlineChars / 2;
|
|
|
- this.tailChars = this.maxInlineChars - this.headChars;
|
|
|
- this.maxPersistedChars = maxPersistedChars;
|
|
|
- this.outputPath = outputPath;
|
|
|
- setDaemon(true);
|
|
|
- }
|
|
|
-
|
|
|
- @Override
|
|
|
- public void run() {
|
|
|
- try (java.io.BufferedReader reader = new java.io.BufferedReader(
|
|
|
- new java.io.InputStreamReader(in, StandardCharsets.UTF_8))) {
|
|
|
- char[] buf = new char[8192];
|
|
|
- int n;
|
|
|
- while ((n = reader.read(buf)) != -1) {
|
|
|
- append(buf, n);
|
|
|
- }
|
|
|
- } catch (IOException ignored) {
|
|
|
- // 进程终止导致的流关闭,忽略
|
|
|
- } finally {
|
|
|
- closeWriter();
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- private void append(char[] buf, int len) {
|
|
|
- if (len <= 0) {
|
|
|
- return;
|
|
|
- }
|
|
|
- totalChars += len;
|
|
|
- if (!truncated) {
|
|
|
- int room = maxInlineChars - inline.length();
|
|
|
- if (len <= room) {
|
|
|
- inline.append(buf, 0, len);
|
|
|
- return;
|
|
|
- }
|
|
|
- if (room > 0) {
|
|
|
- inline.append(buf, 0, room);
|
|
|
- }
|
|
|
- truncated = true;
|
|
|
- // 此时 inline 恰好是截断前的完整前缀,先落盘再拆成头/尾
|
|
|
- startPersistence();
|
|
|
- splitInline();
|
|
|
- appendTailAndPersist(buf, room, len - room);
|
|
|
- return;
|
|
|
- }
|
|
|
- appendTailAndPersist(buf, 0, len);
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 把「前 maxInlineChars 个字符」拆成头段 + 尾段;不拆开代理对(emoji 等)。
|
|
|
- *
|
|
|
- * <p>拆分点落在高代理上时(代理对可能完整在 prefix 内,也可能低代理还在下一个 chunk),
|
|
|
- * 把高代理让给尾段:尾段后续会拼上低代理,头段绝不能留下半个字符。
|
|
|
- */
|
|
|
- private void splitInline() {
|
|
|
- String prefix = inline.toString();
|
|
|
- inline.setLength(0);
|
|
|
- int split = Math.min(headChars, prefix.length());
|
|
|
- if (split > 0 && Character.isHighSurrogate(prefix.charAt(split - 1))) {
|
|
|
- split--;
|
|
|
- }
|
|
|
- head.append(prefix, 0, split);
|
|
|
- tail.append(prefix, split, prefix.length());
|
|
|
- trimTail();
|
|
|
- }
|
|
|
-
|
|
|
- private void appendTailAndPersist(char[] buf, int off, int len) {
|
|
|
- if (len <= 0) {
|
|
|
- return;
|
|
|
- }
|
|
|
- if (tailChars > 0) {
|
|
|
- int take = Math.min(len, tailChars);
|
|
|
- tail.append(buf, off + len - take, take);
|
|
|
- trimTail();
|
|
|
- }
|
|
|
- persist(buf, off, len);
|
|
|
- }
|
|
|
-
|
|
|
- /** 尾段只保留最后 tailChars 个字符;超过两倍再裁剪,均摊 O(1)。 */
|
|
|
- private void trimTail() {
|
|
|
- if (tailChars <= 0) {
|
|
|
- tail.setLength(0);
|
|
|
- return;
|
|
|
- }
|
|
|
- if (tail.length() <= tailChars * 2) {
|
|
|
- return;
|
|
|
- }
|
|
|
- int cut = tail.length() - tailChars;
|
|
|
- if (cut > 0 && Character.isLowSurrogate(tail.charAt(cut))) {
|
|
|
- cut--;
|
|
|
- }
|
|
|
- tail.delete(0, cut);
|
|
|
- }
|
|
|
-
|
|
|
- private String tailText() {
|
|
|
- if (tail.length() <= tailChars) {
|
|
|
- return tail.toString();
|
|
|
- }
|
|
|
- int start = tail.length() - tailChars;
|
|
|
- if (start > 0 && Character.isLowSurrogate(tail.charAt(start))) {
|
|
|
- start--;
|
|
|
- }
|
|
|
- return tail.substring(start);
|
|
|
- }
|
|
|
-
|
|
|
- private void startPersistence() {
|
|
|
- if (outputPath == null || persisted || persistFailed) {
|
|
|
- return;
|
|
|
- }
|
|
|
- try {
|
|
|
- Path parent = outputPath.getParent();
|
|
|
- if (parent != null) {
|
|
|
- Files.createDirectories(parent);
|
|
|
- }
|
|
|
- writer = Files.newBufferedWriter(outputPath, StandardCharsets.UTF_8,
|
|
|
- java.nio.file.StandardOpenOption.CREATE,
|
|
|
- java.nio.file.StandardOpenOption.TRUNCATE_EXISTING,
|
|
|
- java.nio.file.StandardOpenOption.WRITE);
|
|
|
- persisted = true;
|
|
|
- String prefix = inline.toString();
|
|
|
- int allow = persistedAllowance(prefix.length());
|
|
|
- if (allow > 0) {
|
|
|
- writer.write(prefix, 0, allow);
|
|
|
- persistedChars += allow;
|
|
|
- }
|
|
|
- if (allow < prefix.length()) {
|
|
|
- persistedTruncated = true;
|
|
|
- }
|
|
|
- } catch (IOException e) {
|
|
|
- persistFailed = true;
|
|
|
- persistedTruncated = true;
|
|
|
- log.warn("Python 输出落盘失败(仅返回内联头尾): path={}, err={}",
|
|
|
- outputPath, e.getMessage());
|
|
|
- closeWriter();
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- private void persist(char[] buf, int off, int len) {
|
|
|
- if (writer == null || persistFailed || len <= 0) {
|
|
|
- return;
|
|
|
- }
|
|
|
- int allow = persistedAllowance(len);
|
|
|
- if (allow <= 0) {
|
|
|
- persistedTruncated = true;
|
|
|
- return;
|
|
|
- }
|
|
|
- try {
|
|
|
- writer.write(buf, off, allow);
|
|
|
- persistedChars += allow;
|
|
|
- if (allow < len) {
|
|
|
- persistedTruncated = true;
|
|
|
- }
|
|
|
- } catch (IOException e) {
|
|
|
- persistFailed = true;
|
|
|
- persistedTruncated = true;
|
|
|
- log.warn("Python 输出落盘中断(仅返回内联头尾): path={}, err={}",
|
|
|
- outputPath, e.getMessage());
|
|
|
- closeWriter();
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- /** 本次允许写入的字符数;{@code maxPersistedChars <= 0} 表示不限。 */
|
|
|
- private int persistedAllowance(int requested) {
|
|
|
- if (maxPersistedChars <= 0) {
|
|
|
- return requested;
|
|
|
- }
|
|
|
- long remaining = maxPersistedChars - persistedChars;
|
|
|
- if (remaining <= 0) {
|
|
|
- return 0;
|
|
|
- }
|
|
|
- return (int) Math.min(requested, remaining);
|
|
|
- }
|
|
|
-
|
|
|
- private void closeWriter() {
|
|
|
- if (writer == null) {
|
|
|
- return;
|
|
|
- }
|
|
|
- try {
|
|
|
- writer.close();
|
|
|
- } catch (IOException ignored) {
|
|
|
- // 关闭失败不影响已写内容
|
|
|
- }
|
|
|
- writer = null;
|
|
|
- }
|
|
|
-
|
|
|
- /**
|
|
|
- * 模型可见的输出:未截断返回全文;截断返回「头段 + 截断说明 + 尾段」。
|
|
|
- */
|
|
|
- String getContent() {
|
|
|
- if (!truncated) {
|
|
|
- return inline.toString();
|
|
|
- }
|
|
|
- String tailText = tailText();
|
|
|
- long truncatedChars = Math.max(0, totalChars - head.length() - tailText.length());
|
|
|
- StringBuilder out = new StringBuilder(head);
|
|
|
- out.append("\n\n... [").append(truncatedChars).append(" characters truncated");
|
|
|
- if (persisted) {
|
|
|
- out.append("; full output");
|
|
|
- if (persistedTruncated) {
|
|
|
- out.append(" (first ").append(persistedChars).append(" chars)");
|
|
|
- }
|
|
|
- out.append(": ").append(outputPath);
|
|
|
- }
|
|
|
- out.append("] ...\n\n").append(tailText);
|
|
|
- return out.toString();
|
|
|
- }
|
|
|
-
|
|
|
- long getTotalChars() {
|
|
|
- return totalChars;
|
|
|
- }
|
|
|
-
|
|
|
- boolean isTruncated() {
|
|
|
- return truncated;
|
|
|
- }
|
|
|
-
|
|
|
- boolean isPersisted() {
|
|
|
- return persisted;
|
|
|
- }
|
|
|
-
|
|
|
- String getPersistedPath() {
|
|
|
- return persisted ? outputPath.toString() : null;
|
|
|
- }
|
|
|
- }
|
|
|
-}
|