Skip to content

Go: introduce clickhouse - #16996

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix553
Jul 16, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix553

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

Summary

Introduce Clickhouse for data statistics.

@JinHai-CN JinHai-CN added the ci Continue Integration label Jul 16, 2026
@coderabbitai

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

ClickHouse support was added across configuration, Docker Compose, Go dependencies, server startup, connection management, and admin health reporting. Service configuration responses now omit selected sensitive fields, and OTel/ClickHouse services receive explicit service-type mappings.

Changes

ClickHouse configuration and provisioning

Layer / File(s) Summary
Configuration and container provisioning
internal/server/config.go, conf/service_conf.yaml, docker/service_conf.yaml.template, docker/.env, docker/docker-compose-base.yml, docker/init-clickhouse.sql
Adds ClickHouse configuration fields, environment values, a persistent ClickHouse service with healthcheck, and initialization of the ragflow database.

ClickHouse runtime and service integration

Layer / File(s) Summary
ClickHouse driver implementation
internal/engine/clickhouse/clickhouse.go, go.mod
Adds the ClickHouse driver dependency and a singleton driver supporting initialization, ping, status reporting, and shutdown.
Startup and health reporting
cmd/ragflow_server.go, internal/admin/service.go
Initializes ClickHouse during server startup, closes it during shutdown, exposes OLAP/tracing health states, and removes selected sensitive service fields from responses.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ServerMain
  participant ClickhouseDriver
  participant ClickHouse
  participant AdminService
  ServerMain->>ClickhouseDriver: Init ClickHouse configuration
  ClickhouseDriver->>ClickHouse: Open connection and Ping
  ClickHouse-->>ClickhouseDriver: Connection result
  AdminService->>ClickhouseDriver: Request Status
  ClickhouseDriver->>ClickHouse: Read pool stats and server version
  ClickHouse-->>AdminService: Status or error
Loading

Possibly related PRs

Suggested labels: 💞 feature

Suggested reviewers: yuzhichang

Poem

I’m a rabbit with a database tune,
ClickHouse wakes beneath the moon.
Config flows and health checks glow,
Startup starts, shutdowns slow.
Credentials hide, connections sing—
Hop, hop, what a tidy thing! 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly matches the main change: adding ClickHouse support in Go.
Description check ✅ Passed The description includes the required Summary section and briefly explains the ClickHouse addition.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@JinHai-CN
JinHai-CN marked this pull request as ready for review July 16, 2026 09:15
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 16, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft July 16, 2026 09:16
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 16, 2026 09:16

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docker/docker-compose-base.yml`:
- Around line 356-359: Update the clickhouse service environment to include
CLICKHOUSE_DB, assigning it from the configured CLICKHOUSE_DATABASE value so the
official entrypoint creates the selected database on startup. Preserve the
existing user, password, and access-management settings.

In `@docker/service_conf.yaml.template`:
- Around line 66-71: Update the ClickHouse connection configuration to use the
container’s internal port by replacing the CLICKHOUSE_TCP_PORT-based value in
the clickhouse service block with port 9000. Keep the existing host,
credentials, and database settings unchanged.

In `@internal/admin/service.go`:
- Around line 1396-1401: Update the ClickHouse-uninitialized branch in the
health-check logic to set status to the standard value "timeout" and move
"ClickHouse engine not initialized" into the message field, preserving the
existing service_name and return behavior.

In `@internal/engine/clickhouse/clickhouse.go`:
- Around line 81-102: Update Ping, Status, and Close to guard d.conn or
globalDriver.conn before dereferencing them, returning a descriptive error for
uninitialized connections and making Close safely no-op or return an error
without panicking. Preserve normal behavior when the ClickHouse connection is
initialized.

In `@internal/server/config.go`:
- Around line 445-448: Update the "clickhouse" case in the service configuration
switch to remove the user and password fields from configDict before it can be
exposed, matching the sanitization performed for mysql, minio, and redis while
preserving the existing id, name, and service_type assignments.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5fb82fb7-1ea0-429e-aa1c-c68320a93f20

📥 Commits

Reviewing files that changed from the base of the PR and between feba9e1 and c100c87.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (10)
  • cmd/ragflow_server.go
  • conf/service_conf.yaml
  • docker/.env
  • docker/docker-compose-base.yml
  • docker/init-clickhouse.sql
  • docker/service_conf.yaml.template
  • go.mod
  • internal/admin/service.go
  • internal/engine/clickhouse/clickhouse.go
  • internal/server/config.go

Comment on lines +356 to +359
environment:
- CLICKHOUSE_USER=${CLICKHOUSE_USER:-ragflow}
- CLICKHOUSE_PASSWORD=${CLICKHOUSE_PASSWORD:-infini_rag_flow}
- CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Ensure dynamic creation of the configured ClickHouse database.

The clickhouse service environment lacks the CLICKHOUSE_DB variable. While an init script might be mapped, if a user overrides CLICKHOUSE_DATABASE in .env, the customized target database won't be automatically created on startup by the ClickHouse entrypoint. This will cause RAGFlow to crash when it attempts to connect.

Adding CLICKHOUSE_DB instructs the official ClickHouse entrypoint to auto-create the specified database if it doesn't already exist.

🐛 Proposed fix to pass the database environment variable
     environment:
       - CLICKHOUSE_USER=${CLICKHOUSE_USER:-ragflow}
       - CLICKHOUSE_PASSWORD=${CLICKHOUSE_PASSWORD:-infini_rag_flow}
+      - CLICKHOUSE_DB=${CLICKHOUSE_DATABASE:-ragflow}
       - CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
environment:
- CLICKHOUSE_USER=${CLICKHOUSE_USER:-ragflow}
- CLICKHOUSE_PASSWORD=${CLICKHOUSE_PASSWORD:-infini_rag_flow}
- CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1
environment:
- CLICKHOUSE_USER=${CLICKHOUSE_USER:-ragflow}
- CLICKHOUSE_PASSWORD=${CLICKHOUSE_PASSWORD:-infini_rag_flow}
- CLICKHOUSE_DB=${CLICKHOUSE_DATABASE:-ragflow}
- CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docker/docker-compose-base.yml` around lines 356 - 359, Update the clickhouse
service environment to include CLICKHOUSE_DB, assigning it from the configured
CLICKHOUSE_DATABASE value so the official entrypoint creates the selected
database on startup. Preserve the existing user, password, and access-management
settings.

Comment on lines +66 to +71
clickhouse:
host: '${CLICKHOUSE_HOST:-clickhouse}'
port: ${CLICKHOUSE_TCP_PORT:-9000}
user: '${CLICKHOUSE_USER:-ragflow}'
password: '${CLICKHOUSE_PASSWORD:-infini_rag_flow}'
database: '${CLICKHOUSE_DATABASE:-ragflow}'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use the internal container port for ClickHouse communication.

This template evaluates port: ${CLICKHOUSE_TCP_PORT:-9000}. However, CLICKHOUSE_TCP_PORT (default 9900 in .env) represents the host port mapped by Docker Compose.

Inside the ragflow Docker network, the ClickHouse container always listens on its native internal port (9000). If CLICKHOUSE_TCP_PORT evaluates to 9900, RAGFlow will attempt to connect to clickhouse:9900 inside the Docker network, resulting in a connection failure. Hardcode the port to 9000 to correctly match the internal network topology.

🐛 Proposed fix to use the internal port
 clickhouse:
   host: '${CLICKHOUSE_HOST:-clickhouse}'
-  port: ${CLICKHOUSE_TCP_PORT:-9000}
+  port: 9000
   user: '${CLICKHOUSE_USER:-ragflow}'
   password: '${CLICKHOUSE_PASSWORD:-infini_rag_flow}'
   database: '${CLICKHOUSE_DATABASE:-ragflow}'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
clickhouse:
host: '${CLICKHOUSE_HOST:-clickhouse}'
port: ${CLICKHOUSE_TCP_PORT:-9000}
user: '${CLICKHOUSE_USER:-ragflow}'
password: '${CLICKHOUSE_PASSWORD:-infini_rag_flow}'
database: '${CLICKHOUSE_DATABASE:-ragflow}'
clickhouse:
host: '${CLICKHOUSE_HOST:-clickhouse}'
port: 9000
user: '${CLICKHOUSE_USER:-ragflow}'
password: '${CLICKHOUSE_PASSWORD:-infini_rag_flow}'
database: '${CLICKHOUSE_DATABASE:-ragflow}'
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docker/service_conf.yaml.template` around lines 66 - 71, Update the
ClickHouse connection configuration to use the container’s internal port by
replacing the CLICKHOUSE_TCP_PORT-based value in the clickhouse service block
with port 9000. Keep the existing host, credentials, and database settings
unchanged.

Comment thread internal/admin/service.go
Comment on lines +1396 to +1401
if clickhouseDriver == nil {
return map[string]interface{}{
"service_name": name,
"status": "ClickHouse engine not initialized",
}, nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Fix the health check status value.

Returning "ClickHouse engine not initialized" in the status field breaks the standard convention where status is typically a simple enum-like string ("alive", "timeout", or "unknown"). Move this explanation to the message field and set status to "timeout".

🐛 Proposed fix
 	if clickhouseDriver == nil {
 		return map[string]interface{}{
 			"service_name": name,
-			"status":       "ClickHouse engine not initialized",
+			"status":       "timeout",
+			"message":      "ClickHouse engine not initialized",
 		}, nil
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if clickhouseDriver == nil {
return map[string]interface{}{
"service_name": name,
"status": "ClickHouse engine not initialized",
}, nil
}
if clickhouseDriver == nil {
return map[string]interface{}{
"service_name": name,
"status": "timeout",
"message": "ClickHouse engine not initialized",
}, nil
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/admin/service.go` around lines 1396 - 1401, Update the
ClickHouse-uninitialized branch in the health-check logic to set status to the
standard value "timeout" and move "ClickHouse engine not initialized" into the
message field, preserving the existing service_name and return behavior.

Comment on lines +81 to +102
func (d *Driver) Ping(ctx context.Context) error {
return d.conn.Ping(ctx)
}

func (d *Driver) Status() (map[string]interface{}, error) {
stats := d.conn.Stats()
version, err := d.conn.ServerVersion()
if err != nil {
return nil, fmt.Errorf("failed to get server version: %w", err)
}
return map[string]interface{}{
"max_open_conns": stats.MaxOpenConns,
"max_idle_conns": stats.MaxIdleConns,
"open": stats.Open,
"idle": stats.Idle,
"server_version": version.String(),
}, nil
}

func Close() error {
return globalDriver.conn.Close()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Add nil checks to prevent panics on uninitialized connections.

If ClickHouse fails to initialize (e.g., unreachable host or invalid config), Init returns an error, but the server continues execution. Because Close() is deferred, and Status() can be called via the admin health check, any method accessing d.conn or globalDriver.conn will trigger a nil-pointer dereference (NPE) and crash the application.

🛡️ Proposed fix to protect against nil pointers
 func (d *Driver) Ping(ctx context.Context) error {
+	if d == nil || d.conn == nil {
+		return fmt.Errorf("clickhouse connection is not initialized")
+	}
 	return d.conn.Ping(ctx)
 }
 
 func (d *Driver) Status() (map[string]interface{}, error) {
+	if d == nil || d.conn == nil {
+		return nil, fmt.Errorf("clickhouse connection is not initialized")
+	}
 	stats := d.conn.Stats()
 	version, err := d.conn.ServerVersion()
 	if err != nil {
 		return nil, fmt.Errorf("failed to get server version: %w", err)
 	}
 	return map[string]interface{}{
 		"max_open_conns": stats.MaxOpenConns,
 		"max_idle_conns": stats.MaxIdleConns,
 		"open":           stats.Open,
 		"idle":           stats.Idle,
 		"server_version": version.String(),
 	}, nil
 }
 
 func Close() error {
+	if globalDriver == nil || globalDriver.conn == nil {
+		return nil
+	}
 	return globalDriver.conn.Close()
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (d *Driver) Ping(ctx context.Context) error {
return d.conn.Ping(ctx)
}
func (d *Driver) Status() (map[string]interface{}, error) {
stats := d.conn.Stats()
version, err := d.conn.ServerVersion()
if err != nil {
return nil, fmt.Errorf("failed to get server version: %w", err)
}
return map[string]interface{}{
"max_open_conns": stats.MaxOpenConns,
"max_idle_conns": stats.MaxIdleConns,
"open": stats.Open,
"idle": stats.Idle,
"server_version": version.String(),
}, nil
}
func Close() error {
return globalDriver.conn.Close()
}
func (d *Driver) Ping(ctx context.Context) error {
if d == nil || d.conn == nil {
return fmt.Errorf("clickhouse connection is not initialized")
}
return d.conn.Ping(ctx)
}
func (d *Driver) Status() (map[string]interface{}, error) {
if d == nil || d.conn == nil {
return nil, fmt.Errorf("clickhouse connection is not initialized")
}
stats := d.conn.Stats()
version, err := d.conn.ServerVersion()
if err != nil {
return nil, fmt.Errorf("failed to get server version: %w", err)
}
return map[string]interface{}{
"max_open_conns": stats.MaxOpenConns,
"max_idle_conns": stats.MaxIdleConns,
"open": stats.Open,
"idle": stats.Idle,
"server_version": version.String(),
}, nil
}
func Close() error {
if globalDriver == nil || globalDriver.conn == nil {
return nil
}
return globalDriver.conn.Close()
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/engine/clickhouse/clickhouse.go` around lines 81 - 102, Update Ping,
Status, and Close to guard d.conn or globalDriver.conn before dereferencing
them, returning a descriptive error for uninitialized connections and making
Close safely no-op or return an error without panicking. Preserve normal
behavior when the ClickHouse connection is initialized.

Comment thread internal/server/config.go
Comment on lines +445 to +448
case "clickhouse":
configDict["id"] = id
configDict["name"] = "clickhouse"
configDict["service_type"] = "olap"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win

Prevent leakage of ClickHouse credentials.

The clickhouse configuration map retains the user and password fields, unlike the mysql, minio, and redis cases. If this configuration dictionary is exposed via admin API endpoints (such as GetServiceDetails), the plaintext credentials will be leaked. Sanitize the dictionary by deleting these sensitive fields.

🔒️ Proposed fix to sanitize the credentials
 		case "clickhouse":
 			configDict["id"] = id
 			configDict["name"] = "clickhouse"
 			configDict["service_type"] = "olap"
+			delete(configDict, "user")
+			delete(configDict, "password")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
case "clickhouse":
configDict["id"] = id
configDict["name"] = "clickhouse"
configDict["service_type"] = "olap"
case "clickhouse":
configDict["id"] = id
configDict["name"] = "clickhouse"
configDict["service_type"] = "olap"
delete(configDict, "user")
delete(configDict, "password")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/server/config.go` around lines 445 - 448, Update the "clickhouse"
case in the service configuration switch to remove the user and password fields
from configDict before it can be exposed, matching the sanitization performed
for mysql, minio, and redis while preserving the existing id, name, and
service_type assignments.

@codecov

codecov Bot commented Jul 16, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (4518a58) to head (c100c87).
⚠️ Report is 22 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16996   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit c7a623f into infiniflow:main Jul 16, 2026
16 of 24 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jul 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant