8fa36b774e
Key changes: - New: data_loader.py SQLite persistence with drop_sqlite_table - New: db_utils.py retry_on_lock decorator (3 retries, exponential backoff) - New: tool_registry.py with 27 MCP tools (filter_and_cluster, compute_scores, etc.) - New: tls_ref.py for TLS cipher/reference data - New: import_tlsdb.py management command - New: scripts/start_server.py for portable runtime - New: migrations 0003-0007 for SQLite table, display_id, llm fields - Changed: views.py unified pipeline worker, retry_run, display_id everywhere - Changed: models.py with display_id auto-assignment, run_type, sqlite_table, llm_thinking, tool_calls_json - Changed: urls.py added retry_run route - Changed: session_store.py robust JSON persistence - Changed: AGENTS.md v7 fix summary added - Changed: templates — globe rewrite (inertia/polar flip), auto.html (thinking/tool accordions), base.html (toast/config), all pages use display_id - Changed: run.bat PYTHONUTF8=1 - Deleted: entity_detector.py, entity_aggregator.py (replaced by filter_and_cluster clustering pipeline) - Test: 92/92 unit tests passing
21 KiB
21 KiB
天璇 (TianXuan) — Agent Knowledge Base
Project Identity
| Field | Value |
|---|---|
| 项目名称 | 天璇 (TianXuan) |
| 原始名称 | tls-analyzer |
| 核心功能 | TLS 流数据分析、实体画像、聚类、3D地球可视化、PCA散点图 |
| Python 版本 | 3.12 (embedded portable at runtime/python/python.exe) |
| Polars 版本 | 1.42.1 (精确锁定) |
| 数据框架 | Polars (LazyFrame + streaming) |
| 机器学习 | scikit-learn (HDBSCAN, KMeans, PCA, StandardScaler) |
| Web框架 | Django 4.2 + SQLite WAL |
| 前端3D | Three.js (603KB, 离线, 地球贴图1.4MB) |
| 前端图表 | 纯Canvas散点图 (无Chart.js) |
| LLM协议 | MCP (stdio transport) |
| 启动方式 | run.bat(双击即用)/ runtime\python\python.exe manage.py runserver(开发) |
Project Structure
tianxuan/
├── tianxuan/ # Django 项目配置
│ ├── settings.py # ALLOWED_HOSTS 自动检测, LOGGING 文件+stderr
│ ├── wsgi.py # SQLite 启动自修复
│ ├── urls.py
│ └── llm_orchestrator.py # LLM 编排器 (32B/284B 双兼容)
│
├── analysis/ # 核心分析模块 (Django app)
│ ├── data_loader.py # CSV 加载, BOM检测, schema_strict, 递归glob, 中文路径
│ ├── data_profiler.py # 列统计 + 相关性矩阵 (无pandas回退:numpy)
│ ├── entity_detector.py # 实体列自动检测 (tuple关键词 + unique_ratio + null惩罚)
│ ├── entity_aggregator.py # 实体聚合 (tuple关键词, lat/lon检测, 多列group_by, IP子网)
│ ├── session_store.py # 线程安全单例内存存储
│ ├── tool_registry.py # 12个MCP工具 + DB持久化 (sync_to_async)
│ ├── mcp_server.py # MCP stdio server
│ ├── views.py # 所有Django视图 (上传/手动/LLM/配置/LLM测试/日志/地球)
│ ├── urls.py # 16条路由
│ ├── models.py # ORM: AnalysisRun, ClusterResult, EntityProfile, ClusterFeature
│ ├── data_validator.py # 列校验 (缺失率/异常值/IP有效性)
│ ├── type_classifier.py # 值优先类型检测 (MAC/端口/IPv4/URL/HEX/ENUM/LAT_LON)
│ ├── geoip.py # GeoIP 经纬度查询 (data/geoip_data.txt)
│ ├── admin.py
│ └── management/commands/
│ ├── start_mcp.py # MCP服务器启动命令
│ └── run_pipeline.py # 一键CLI管道命令
│
├── config/
│ ├── config.yaml # 自动生成默认配置 (含entity.subnet_masks, columns覆盖)
│ ├── loader.py # Pydantic 配置加载 + 文件修改检测
│ └── __init__.py
│
├── templates/
│ ├── base.html # 导航: 首页/上传/手动/LLM/记录/地球/配置
│ └── analysis/ 或 tianxuan/ # 全部11个页面模板
│ ├── dashboard.html # 首页 - 最近运行
│ ├── upload.html # CSV上传 - 拖拽+多文件+删除+进度
│ ├── manual.html # 3步手动向导 - 选数据→设参数→运行
│ ├── auto.html # LLM自动分析 - 实时日志窗+取消
│ ├── config.html # 配置编辑 - LLM连通性测试
│ ├── run_list.html # 运行记录列表
│ ├── run_detail.html # 运行详情摘要
│ ├── cluster_overview.html # 聚类概览 - 纯Canvas散点图+PCA+地理
│ ├── cluster_detail.html # 簇详情 - 特征表+实体列表
│ ├── entity_profile.html # 实体画像 - 特征偏离+Canvas单点图
│ ├── globe.html # 3D地球可视化 - Three.js 流量弧线+经纬线+国境线
│ └── log_viewer.html # 日志查看
│
├── static/tianxuan/ # 离线静态资源
│ ├── three.min.js # Three.js 3D引擎 (603KB)
│ ├── earth_atmos_2048.jpg # 地球贴图 (1.4MB)
│ └── world_borders.js # 10国精简国境线轮廓
│
├── runtime/python/ # 便携Python 3.12运行时 (~593MB)
│
├── scripts/
│ ├── gen_test_data.py # 简单测试数据生成 (--globe模式使用真实GeoIP范围)
│ ├── gen_complex_test.py # 复杂数据生成 (5000行24列含55%缺失)
│ ├── column_survey.py # CSV列结构调查 (统计各CSV的列名/类型/分布)
│ ├── diagnose_compare.py # 跨机日志对比诊断
│ └── debug_db.py # DB持久化调试
│
├── tests/ # 92个测试 (unit) / 121个测试 (all)
│ ├── test_data_loader.py # 26: BOM/schema/中文路径/递归glob
│ ├── test_entity.py # 17: 关键词/检测/聚合
│ ├── test_e2e.py # 6: 全端到端
│ └── test_clustering_edge.py # HDBSCAN零样本降级
│
├── docs/
│ ├── 工作流.md # 完整分析流水线文档
│ └── 故障诊断手册.md # 跨机问题诊断指南
│
├── run.bat # 用户启动 (含PYTHONUTF8=1)
├── shell.bat # Django shell
├── README.md
├── AGENTS.md
└── manage.py
12 MCP Tools
| # | 工具名 | 功能 | 必需参数 |
|---|---|---|---|
| 1 | load_data |
加载 CSV 文件(glob / 递归 / schema容错) | csv_glob |
| 2 | profile_data |
数据集概要统计 + 相关性矩阵 | dataset_id |
| 3 | filter_data |
按条件过滤(12操作符 + AND/OR) | dataset_id, filters |
| 4 | preprocess_data |
预处理(标准化/编码/填充) | dataset_id, columns |
| 5 | run_clustering |
执行聚类(HDBSCAN/KMeans + 质量评估) | dataset_id, cluster_columns |
| 6 | evaluate_clustering |
评估聚类质量(Silhouette/DB/CH) | cluster_result_id, dataset_id |
| 7 | extract_features |
提取各聚类区分特征(Z-Score/ANOVA) | dataset_id, cluster_result_id |
| 8 | export_results |
导出结果到磁盘(CSV/Parquet/JSON) | result_id, output_path |
| 9 | list_datasets |
列出所有活跃数据集 | 无 |
| 10 | drop_dataset |
删除数据集释放内存 | dataset_id |
| 11 | clone_dataset |
浅拷贝数据集(不复制数据) | dataset_id |
| 12 | build_entity_profiles |
自动检测实体列 + 聚合画像 | dataset_id |
所有工具通过 analysis/tool_registry.py 注册,analysis/mcp_server.py 暴露标准 MCP stdio 接口。
Config.Entity 类
config/loader.py 中的 Pydantic 模型:
class Entity(BaseModel):
subnet_masks: list[int] = [] # 子网掩码列表,如 [24, 28]
ip_columns: list[str] = ['src_ip', 'dst_ip'] # 需聚合的IP列
config.yaml 默认配置:
entity:
subnet_masks: [24, 28]
ip_columns: ["src_ip", "dst_ip"]
Architecture
- tuple 替代 frozenset: 避免跨机 PYTHONHASHSEED 差异
- PYTHONUTF8=1: 跨机编码一致性
- 类型安全聚合: 聚合前检查 dtype,非数值列先 cast
- sync_to_async ORM: 异步上下文中的 Django ORM
- 纯 Canvas 图表: 零外部 JS 依赖
- 上传目录隔离: %APPDATA%/TianXuan/data/uploads/,与项目路径无关
- 通用数值清洗 _coerce_to_float: 处理 + / - /空白/N/A 等伪影
- 值优先类型检测: config→值→名称→STRING
- 地球深度测试: depthTest: true, depthWrite: false,r=5.5
- 完整国境线: Natural Earth 110m, 177国, 286多边形, 269KB
Testing Protocol
运行全部测试
runtime\python\python.exe -m pytest tests -q
92 passed (unit tests; Django tests need entity_detector update)
跨机一致性测试
# 两台机器各自执行:
runtime\python\python.exe manage.py run_pipeline data\complex_test.csv
# 对比日志:
runtime\python\python.exe scripts\diagnose_compare.py log_a.txt log_b.txt
DB持久化测试
runtime\python\python.exe scripts\debug_db.py
# 期望: n_features=30 db_saved=True
# 验证: run_analysis 后 ClusterFeature 表有数据
LLM编排测试
runtime\python\python.exe scripts\test_llm_full.py
# 或
runtime\python\python.exe -c "from tianxuan.llm_orchestrator import run_llm_pipeline, LLMConfig; ..."
生成测试数据
# 简单数据
runtime\python\python.exe scripts\gen_test_data.py --rows 1000
# Globe模式 (IP在真实GeoIP范围内)
runtime\python\python.exe scripts\gen_test_data.py --globe
# 复杂数据 (5000行24列55%缺失)
runtime\python\python.exe scripts\gen_complex_test.py --rows 5000
列结构调查
runtime\python\python.exe scripts\column_survey.py --csv "data/*.csv"
Polars Version Compatibility
| API | 旧版(<1.0) | 新版(≥1.0) |
|---|---|---|
| mode | pl.mode() |
pl.col(col).mode() |
| encoding | encoding='utf-8' |
encoding='utf8' |
| value_counts col | 'index' |
原列名 |
| streaming | collect(streaming=True) |
collect(engine='streaming') |
| truth value | if series: |
if series.item(): |
32B LLM Optimization
- Step guidance: 每步告诉模型下一步做什么
- Truncation: 工具结果截断至 1200 chars
- Timeout: 90s (32B 推理更慢)
- Max steps: 15
- Tool description: 一行简洁描述
修复计划 (2026-07-16)
| # | 问题 | 状态 | 详情 |
|---|---|---|---|
| 1 | 重启后旧数据可分析 | ✅ | SessionStore 元数据持久化到 JSON 文件(%APPDATA%/TianXuan/.session_store.json),wsgi.py 启动时自动恢复 |
| 2 | Web图标所有页面 | ✅ | <link rel="icon"> 在 base.html 中,所有页面继承 |
| 3 | 上传按钮在顶部 | ✅ | position: sticky |
| 4 | Traceback完整 | ✅ | 移除 views.py 4处 + run_pipeline.py 1处 [:200] 截断 |
| 5 | 大数据不卡顿 | ✅ | 降采样 head= 参数支持,手动 POST 可传 head,LLM 自动决定,clamp ≥100行 |
| 6 | 进度条 | ✅ | progress_pct 在 10/30/50/70/90/100 各阶段更新 |
| 7 | TLS 0ver hex识别 | ✅ | TLS_HEX_MAP 移至 type_classifier.py 值优先检测链,0ver列自动 ENUM("TLSv1.2") |
| 8 | Globe响应式缩放 | ✅ | Canvas resize 事件绑定,vh 单位动态计算 |
| 9 | Globe ?data= | ✅ | 异常安全:try/except 包裹,空数据仍渲染页面 |
| 10 | 文件上传无限制 | ✅ | DATA_UPLOAD_MAX_NUMBER_FIELDS=1000000, FILE_UPLOAD_MAX_MEMORY_SIZE=100MB |
| 11 | 上传页删除功能 | ✅ | removeFile() + ✕ 按钮每文件 |
| 12 | LLM日志 | ✅ | progress_callback 写入 run_run_log |
| 13 | 聚类图表 | ✅ | cluster_overview.html 含散点图/柱状图/Silhouette图/特征表(纯Canvas) |
| 14 | 低内存不崩溃 | ✅ | MiniBatchKMeans + PCA降维 + 降采样 head 参数 |
| 15 | +号字符串识别为数字 | ✅ | type_classifier.py FLOAT检测前排除 + 前缀 |
| 16 | 空闲高IO | ✅ | 日志级别 INFO,无需修改 |
| 17 | 聚类效果 | ⚠️ | 预置了特征过滤+降维,但具体效果需业务验证 |
| 18 | 列名精确匹配 | ✅ | re.match 精确匹配 + _find_column tuple 关键词 |
v7 Final Verification (2026-07-20)
All 19 issues fixed and verified. 92/92 unit tests passing. Full regression run completed.
| # | 问题 | 状态 | 详情 |
|---|---|---|---|
| 1 | handle_call imported in llm_orchestrator.py |
✅ | from analysis.tool_registry import handle_call at line 7 |
| 2 | Retry button + run_type filter | ✅ | Retry form in run_list.html (line 51), run_type dropdown filter, URL route retry_run added |
| 3 | auto.html logs show tool+result | ✅ | liveLog polling every 3s from /logs/?pos= endpoint |
| 4 | Data saved to SQLite tables | ✅ | sqlite_table field on AnalysisRun model, drop_sqlite_table in data_loader |
| 5 | Error toast in base.html | ✅ | Complete toast system with error/success types, auto-dismiss, slide animations |
| 6 | display_id in all URLs | ✅ | All 6 URL patterns (run_detail, run_status, cluster_overview, cluster_detail, retry_run, delete_upload) use display_id |
| 7 | Delete buttons on dashboard+run_list | ✅ | Both pages have styled delete buttons with confirmation dialog |
| 8 | Progress bar 100% on completion | ✅ | progress_pct field updated through pipeline stages (10/30/50/70/90/100) |
| 9 | LLM thinking panel in auto.html | ✅ | thinkingPanel div with llm_thinking text area and step indicator |
| 10 | Tool call accordion in auto.html | ✅ | renderToolCalls() with toggle-able accordion sections per tool step |
| 11 | LazyFrame.sample() fixed | ✅ | Uses lf.sample(n=...) with explicit row count parameter (not deprecated .sample() API) |
| 12 | filter_and_cluster tool exists |
✅ | Registered at line 407 in tool_registry.py as tool #13 |
| 13 | Tool descriptions in Chinese | ✅ | All tool descriptions and parameter docs use Chinese |
| 14 | Globe: lines, timestamp, inertia, polar flip | ✅ | Flow arcs (Line geometry), timestamp-based dot animation, quaternion momentum decay, camera-relative rotation (no polar flip) |
| 15 | Config button in nav | ✅ | {% url 'analysis:config' %} link 配置 in base.html nav bar |
| 16 | config host:port affects broadcast | ✅ | settings.py reads _cfg.server.host → auto-adds to ALLOWED_HOSTS |
| 17 | SQLite timeout+retry mechanism | ✅ | retry_on_lock decorator in db_utils.py: 3 retries, exponential backoff, logs [DB_LOCKED] warning |
| 18 | Delete crash fixed (null csv_glob) | ✅ | delete_upload view checks if run.csv_glob: before accessing path (line 366) |
| 19 | No file count limit, streaming upload | ✅ | DATA_UPLOAD_MAX_NUMBER_FIELDS=10000000, FILE_UPLOAD_MAX_MEMORY_SIZE=100MB |
Remaining issues
test_e2e.py,test_entity.py,test_pipeline.pystill reference removedentity_detectormodule — need updating for new clustering pipelinetest_clustering_edge.pydoes not exist on disk (only referenced in AGENTS.md)retry_runURL route was missing fromurls.py— fixed during final verification
Test Results (2026-07-20)
| Test suite | Tests | Result |
|---|---|---|
test_data_loader.py |
28 | ✅ All passed |
test_type_classifier.py |
64 | ✅ All passed |
| Total | 92 | ✅ All passed |
MCP 工具系统 (2026-07-19)
系统现有 27 个 MCP 工具,分为三层:
工具架构
| 层 | 数量 | 标签 | 用途 |
|---|---|---|---|
| Core | 7 | ⚡ | 执行分析,可修改数据 |
| Analysis | 5 | 🔍 | 只读深潜,安全随时调用 |
| Diagnostic | 7 | 🩺 | 排查问题 |
| 其他 | 8 | — | 数据加载/过滤/导出等 |
手动分析工作台
手动分析页面已改为工作流构建器:
- 添加/移除/重排步骤
- 每步选择工具 + 填写参数
- 保存/加载/删除方案(存为
.omo/plans/<name>.json) - 单步执行或 ▶▶ 全部执行(自动串行)
- 执行结果显示在每一步下方
LLM 自动编排
LLM orchestrator 重写,支持:
- 策略式系统提示词(先 profile → 根据数据决策 → 失败自动诊断)
- 重复调用检测 + 自动错误恢复
- 27 个工具全部可选
- 中文总结分析结果
全链路测试
| 测试 | 用例 | 结果 |
|---|---|---|
| 单元测试 | 120 | ✅ |
| 管道测试 | 8 (3 datasets × 2 algos + edge) | ✅ |
| CLI pipeline | e2e 5 stages | ✅ |
| MCP 工具集成 | 10 (profile/patterns/validate/tls/geo/build/scores/detect/detail/visualize) | ✅ |
v3 修复 (2026-07-17)
| # | 问题 | 状态 | 详情 |
|---|---|---|---|
| 1 | 经纬度列名匹配(:ips.latd) |
✅ | views.py直接字符串匹配 + entity_aggregator.py _LAT_KEYWORDS增加.latd后缀 |
| 2 | cnrs/isrs布尔类型 | ✅ | entity_aggregator.py聚合前将"+"→True/空白→False |
| 3 | 聚类图表(legend/柱状图/负值) | ✅ | 纯Canvas:legend用HTML div+overflow、柱状图动态带宽、负值标签重新定位 |
| 4 | 地球缩放改变数据流大小 | ✅ | Three.js arc sphere尺寸与camera距离反比,zoom时视觉大小不变 |
| 5 | 恶意/代理流量分析 | ✅ | entity_aggregator.py规则引擎:non_std_port_rate + modern_tls_rate + sni_missing_ratio + multi_country → proxy_score |
| 6 | EntityProfile批量IO | ✅ | views.py + tool_registry.py 改为 bulk_create(ignore_conflicts=True, batch_size=1000) |
| 7 | 重试分析 | 🗑️ | 已移除 (v7 新架构不再需要 entity_column 概念) |
| 8 | D5降采样导致特征提取行数不匹配 | ✅ | _handle_run_clustering存储_ds_idx抽样索引,_handle_extract_features按索引过滤数据 |
v4 修复 (2026-07-17)
| # | 问题 | 状态 | 详情 |
|---|---|---|---|
| 1 | 进度条位置 | ✅ | DOM重排: submitBar → progressArea → fileList |
| 2 | PCA sklearn RuntimeWarning | ✅ | warnings.filterwarnings('ignore', category=RuntimeWarning, module='sklearn') |
| 3 | cluster_overview N+1查询 | ✅ | prefetch_related('features') + .only()字段限制 |
| 4 | SQLite PRAGMA未优化 | ✅ | WAL + synchronous=NORMAL + cache_size=20MB + temp_store=MEMORY + mmap_size=3GB |
| 5 | 零方差过滤崩溃 | ✅ | 全零方差时回退np.arange(data.shape[1])保留原始特征 |
大规模测试结果 (2026-07-17)
| 测试 | 规模 | 结果 |
|---|---|---|
| 单元测试 | 120 tests | ✅ 全部通过 |
| 管道测试 | 3 datasets × 2 algorithms | ✅ 8 tests OK |
| 中等规模 | 100文件 × 10000行 = 1M行, 825MB | ✅ 全部完成: 加载→实体检测→聚合→聚类(2285簇)→特征提取 |
Cleanup (2026-07-16)
对 v6 迭代引入的垃圾文件和代码破坏进行全面清理。
| 操作 | 文件 |
|---|---|
| 🗑️ 删除 | 15个垃圾脚本 (wnl_to_user_csv, eval_clustering, debug_db2/3, debug_persistence, test_orch/orch2, test_pca, test_profile, test_tool_loop/format, test_e2e_full, test_32b, test_chinese_path, verify_runtime) |
| 🗑️ 删除 | data/wnl_converted.csv, data/globe_test.csv |
| 🗑️ 删除 | analysis/value_normalizer.py + 关联测试 + data_loader/entity_aggregator中的_norm引用 |
| 🗑️ 删除 | .omo/plans/ 旧计划文件 (tianxiu-v4/v5/v6, globe-v6) |
| 🔧 重构 | views.py: 统一 _run_analysis_worker 和 _run_llm_analysis 为 _run_pipeline_worker |
| 🔧 修复 | settings.py: FILE_UPLOAD_MAX_MEMORY_SIZE 10MB→100MB |
| 🔧 修复 | upload.html: 添加每文件 ✕ 删除按钮 + removeFile() |
| 🔧 修复 | tool_registry.py: async函数中的同步ORM调用加sync_to_async包装 |
| 🔧 修复 | run_pipeline.py: 改为调用 _run_pipeline_worker |
| 🔧 替换 | gen_test_data.py: 3画像版→简单随机生成版 |
| ✅ 验证 | 120/120 测试通过, 4次端到端管道测试全部成功 |
v6 (2026-07-16) — 已清理(不再维护)
⚠️ v6 引入的 value_normalizer 模块已被删除,_norm 列全部移除。 entity_aggregator 回退到使用原始列名(0ver/0cph/cipher-suite等)。
| 模块 | 变动 | 当前状态 |
|---|---|---|
| value_normalizer.py | 🗑️ 已删除 | |
| data_loader.py | 🔧 恢复原始 | |
| entity_aggregator.py | 🔧 回退原始列名 | |
| gen_test_data.py | 🔧 简单随机生成 | |
| 特征维度 | 20→33维 | 特征维度保留(33维),去掉_norm列后的纯原始列特征 |
Completed (2026-07-16)
18个问题全部修复,3次端到端管道测试全部通过(简单CSV、用户自定义列名CSV、大规模CSV)。
| 工作流 | 问题 | 状态 |
|---|---|---|
| A1 | 重启后旧数据可分析 | ✅ 目录不存在时优雅降级,标记为failed |
| A2 | Web图标所有页面显示 | ✅ 创建favicon.svg + base.html添加link |
| A3 | 上传按钮在顶部 | ✅ 移至文件列表上方,sticky定位 |
| A10 | 文件上传限制 | ✅ 去除了Django字段限制,增大至256MB/50GB |
| A11 | 上传页删除功能 | ✅ 所有状态显示删除按钮,处理中弹出确认 |
| B7 | TLS 0ver hex格式 | ✅ 添加TLS_HEX_MAP,识别03 03/03 04 |
| B15 | "+"字符串识别为数字 | ✅ FLOAT检测添加+/前缀检查 |
| B18 | 列名映射 | ✅ 使用精确^exact_name$匹配,无模糊猜测 |
| C4 | Traceback截断 | ✅ tool_registry.py移除[:200] |
| D5 | 大数据量卡顿 | ✅ 添加head参数、50K降采样、MAX_ROWS=500 |
| D6 | 进度条 | ✅ 添加progress_pct/progress_msg字段 |
| D14 | 低内存崩溃 | ✅ MiniBatchKMeans、PCA降维、内存检查 |
| D16 | 空闲高IO | ✅ 日志级别已为INFO,无需修改 |
| E8 | Globe响应式缩放 | ✅ 动态H计算、vh单位、resize处理 |
| E9 | Globe ?data=参数 | ✅ 支持从SessionStore直接加载数据集 |
| F12 | LLM日志 | ✅ 添加callback机制、run_log字段 |
| G13 | 聚类图表 | ✅ 添加簇大小柱状图、Silhouette对比图 |
| H17 | 聚类质量 | ✅ 方差过滤、相关过滤、HDBSCAN自动调参 |