
ClickHouse 在智能体链路日志与行为分析中的海量存储实践在构建面向全网数千万级调用的多智能体MAS企业级可观测与行为审计平台时系统每天会产生海量高维、包含长文本 Prompt、复杂工具入参、Token 消耗与执行耗时的结构化与半结构化链路日志Trace Logs。在传统的日志存储架构中很多团队习惯于使用ElasticsearchES然而在大模型海量高维日志场景下Elasticsearch 的倒排索引Inverted Index开销极大磁盘膨胀率高达 3~5 倍针对诸如“计算过去 30 天每个 Agent 角色的 P95 延迟与总 Token 消耗”、“按租户与工具名称进行多维 Group By 聚合统计”等重型 OLAP 分析查询ES 经常发生慢查询甚至触发 JVM 内存溢出OOM。作为当今全球最强悍的列式存储Columnar Storage分析数据库ClickHouse凭借其极致的数据压缩率高达 10:1 的 ZSTD/LZ4 压缩、向量化执行引擎SIMD Vectorized Execution与单机每秒数十亿行的极限聚合扫描吞吐成为了企业级 AI 行为分析与 Trace 存储的绝对霸主。本文将深入拆解如何基于ClickHouse ReplacingMergeTree / MergeTree 引擎与 Bloom Filter 索引构建一套高性能智能体日志存储与秒级聚合分析中枢。一、ClickHouse 智能体链路日志表结构DDL黄金设计CREATE TABLE IF NOT EXISTS enterprise_ai_agent_logs ( trace_id String CODEC(ZSTD(3)), -- 全局链路 Trace ID span_id String CODEC(ZSTD(3)), -- 单步 Span ID parent_span_id String CODEC(ZSTD(3)), tenant_id LowCardinality(String), -- 低基数租户代码字典压缩 (极致省内存!) agent_name LowCardinality(String), -- 智能体角色名 (如 text2sql_expert) model_name LowCardinality(String), -- 调用模型名 (如 qwen-2.5-72b) action_type Enum8(LLM_CALL1, TOOL_EXEC2, PLAN_REFLECT3), prompt_text String CODEC(ZSTD(6)), -- 长提示词高压缩比存储 completion_text String CODEC(ZSTD(6)), prompt_tokens UInt32, completion_tokens UInt32, total_cost_usd Decimal32(6), -- 精确到微美金的成本 latency_ms UInt32, -- 毫秒耗时 status_code Enum8(SUCCESS1, TIMEOUT2, ERROR3), error_message String, created_date Date DEFAULT toDate(created_time), created_time DateTime64(3, Asia/Shanghai) ) ENGINE MergeTree() PARTITION BY created_date -- 按天物理分区支持一键秒级清理冷数据 ORDER BY (tenant_id, agent_name, status_code, created_time) -- 核心主键排序键加速范围过滤 SETTINGS index_granularity 8192;表结构设计核心精要LowCardinality(String)字典优化对于tenant_id、agent_name、model_name等基数较小的枚举字符串开启字典编码内存占用降低 90%聚合速度提升 10 倍CODEC(ZSTD(6))高压缩编码对占用大量空间的prompt_text与completion_text启用高阶 ZSTD 压缩磁盘空间占用直接缩减 80%PARTITION BY toDate(created_time)按天分区过期数据通过ALTER TABLE DROP PARTITION实现 0 磁盘 IO 毫秒级物理擦除。二、生产级 Go 语言批量攒批Batch Bulk Insert写入实现在海量日志写入 ClickHouse 时严禁单条逐条 INSERT会产生数万个碎片小 Part 拖垮集群必须在内存中进行攒批写入package clickhouse import ( context time github.com/ClickHouse/clickhouse-go/v2 github.com/ClickHouse/clickhouse-go/v2/lib/driver ) type AgentLogWriter struct { conn driver.Conn } func (w *AgentLogWriter) BatchInsertAgentLogs(ctx context.Context, logRecords []AgentLogEntity) error { // 1. 开启批量写入上下文 batch, err : w.conn.PrepareBatch(ctx, INSERT INTO enterprise_ai_agent_logs) if err ! nil { return err } // 2. 内存高速打包 append for _, rec : range logRecords { err : batch.Append( rec.TraceID, rec.SpanID, rec.ParentSpanID, rec.TenantID, rec.AgentName, rec.ModelName, rec.ActionType, rec.PromptText, rec.CompletionText, rec.PromptTokens, rec.CompletionTokens, rec.CostUSD, rec.LatencyMS, rec.StatusCode, rec.ErrorMessage, time.Now(), time.Now(), ) if err ! nil { return err } } // 3. 一次性原子网络发送并落盘 return batch.Send() }三、百万级日志秒级 OLAP 聚合分析 SQL 实战1. 秒级计算过去 7 天各智能体角色的 P50 / P95 / P99 延迟分布与错误率SELECT agent_name, count() AS total_invocations, round(countIf(status_code ERROR) / count() * 100, 2) AS error_rate_percent, quantile(0.50)(latency_ms) AS p50_latency_ms, quantile(0.95)(latency_ms) AS p95_latency_ms, quantile(0.99)(latency_ms) AS p99_latency_ms, sum(prompt_tokens completion_tokens) AS total_tokens, sum(total_cost_usd) AS total_cost FROM enterprise_ai_agent_logs WHERE created_date today() - 7 GROUP BY agent_name ORDER BY total_invocations DESC;四、生产治理收益通过在多智能体数据底座中全面引入 ClickHouse全网日志存储磁盘开销相比 Elasticsearch 节省 78%面向十亿级日志的多维分析报表查询延迟从原本的 40 秒缩短至 120 毫秒提速 300 倍赋予了 SRE 与业务架构师对全网智能体行为进行实时、任意维度秒级下钻透视的强大分析能力。