Skip to content

Go: refactor log and config - #17684

Merged
JinHai-CN merged 7 commits into
infiniflow:mainfrom
JinHai-CN:fix602
Aug 2, 2026
Merged

JinHai-CN merged 7 commits into
infiniflow:mainfrom
JinHai-CN:fix602

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

No description provided.

Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
@coderabbitai

coderabbitai Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1de704a9-edec-40ad-acf3-509bfe96a606

📥 Commits

Reviewing files that changed from the base of the PR and between 8b9a0d3 and 0beda90.

📒 Files selected for processing (1)
  • internal/service/system.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/service/system.go

📝 Walkthrough

Walkthrough

The change renames registration and startup APIs, preserves unset environment states, updates the configuration response, uses duration-formatted heartbeat intervals, centralizes server logging, and improves Redis address parsing.

Changes

Configuration and startup updates

Layer / File(s) Summary
Registration configuration contract
internal/common/environments.go, internal/server/config/environments.go, internal/server/config/api_server_config.go, docker/.env
Registration settings use EnableRegister. Environment overrides use pointer fields and the ENABLE_REGISTER variable.
Registration API and service consumers
internal/service/system.go, internal/service/user.go, internal/handler/system.go
The configuration response exposes the registration setting as a boolean. Registration uses EnableRegister(). The documented route includes /api.
Heartbeat and language configuration
internal/server/config/general_config.go, conf/service_conf.yaml, docker/service_conf.yaml.template, cmd/ragflow_server.go
Heartbeat defaults and templates use 3s. Scheduling receives the duration directly. The default language is en, with environment language fallback.
Startup initialization and logging
internal/common/logger.go, internal/engine/global.go, internal/storage/storage_factory.go, cmd/ragflow_server.go, internal/server/config.go, internal/ingestion/task/pipeline_real_integration_test.go, internal/tokenizer/tokenizer_concurrent_test.go, internal/engine/redis/redis.go, cmd/ragflow-cli.go
Startup uses renamed initialization APIs. Configuration logging uses common.Info. The server logger setter and test logger override are removed.
Redis address parsing
internal/server/config/cache_engine_config.go
Redis host and port parsing uses net.SplitHostPort with address and host validation.

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

Possibly related PRs

Suggested labels: ☯️ refactor

Poem

A rabbit updates config with care,
EnableRegister now lives there.
Three-second heartbeats keep time,
Clean logs and Redis parsing align.
Startup runs with names that rhyme.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request has no description, so it does not provide the required summary or background context. Add a Summary section that explains the purpose of the logging and configuration refactoring and provides relevant background for reviewers.
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main logging and configuration refactoring changes.
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.

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 August 2, 2026 09:57
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Aug 2, 2026

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/server/config.go (1)

172-172: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Remove the stale SetLogger call before deleting this API.

mustLoadRealIntegrationConfig still calls server.SetLogger(zap.NewNop()); remove the call or migrate it to the test’s shared logger setup before deleting SetLogger.

🤖 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` at line 172, Remove the stale
server.SetLogger(zap.NewNop()) call from mustLoadRealIntegrationConfig, or
replace it with the test’s shared logger setup before deleting SetLogger. Ensure
the integration configuration loading path no longer depends on the SetLogger
API.

Source: Coding guidelines

🤖 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 `@cmd/ragflow_server.go`:
- Line 528: Update the heartbeat interval configuration flow before constructing
the “Heartbeat reporter” ScheduledTask to reject bare numeric values, including
RAGFLOW_GENERAL__HEARTBEAT_INTERVAL, instead of interpreting them as
nanoseconds. Parse and accept explicit duration strings, return a clear startup
error for unitless values, and add coverage for valid duration strings, rejected
numbers, and the environment-variable configuration path.

In `@internal/common/environments.go`:
- Line 171: Align registration configuration across Go and Python by making
EnvEnableRegister and settings.REGISTER_ENABLED use one shared key or retiring
the legacy Python setting, while preserving a consistent default. Update the
deployment entry at docker/.env lines 271-271 accordingly and remove duplicate
legacy documentation or deployment entries; apply the corresponding
configuration change at internal/common/environments.go lines 171-171.

In `@internal/server/config/environments.go`:
- Around line 57-77: The environment boolean parsing in the EnableRegister and
DisablePasswordLogin handling must distinguish valid true and false values from
invalid input. Accept true/1/yes as true and false/0/no as false, while
returning an error for any other value instead of silently assigning false;
preserve the existing pointer initialization and propagate the parsing error
from the surrounding configuration method.

---

Outside diff comments:
In `@internal/server/config.go`:
- Line 172: Remove the stale server.SetLogger(zap.NewNop()) call from
mustLoadRealIntegrationConfig, or replace it with the test’s shared logger setup
before deleting SetLogger. Ensure the integration configuration loading path no
longer depends on the SetLogger API.
🪄 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 Plus

Run ID: 6dae6341-645f-4aaf-967b-8ea446e7968a

📥 Commits

Reviewing files that changed from the base of the PR and between d4ceeee and 11fda25.

📒 Files selected for processing (13)
  • cmd/ragflow_server.go
  • conf/service_conf.yaml
  • docker/.env
  • docker/service_conf.yaml.template
  • internal/common/environments.go
  • internal/handler/system.go
  • internal/ingestion/task/pipeline_real_integration_test.go
  • internal/server/config.go
  • internal/server/config/api_server_config.go
  • internal/server/config/environments.go
  • internal/server/config/general_config.go
  • internal/service/system.go
  • internal/service/user.go
💤 Files with no reviewable changes (1)
  • internal/ingestion/task/pipeline_real_integration_test.go

Comment thread cmd/ragflow_server.go
}

heartbeatReporter := utility.NewScheduledTask("Heartbeat reporter", heartBeatInterval*time.Second, func() {
heartbeatReporter := utility.NewScheduledTask("Heartbeat reporter", heartBeatInterval, func() {

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 | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "Declared Viper and cast versions:"
rg -n 'github.com/spf13/(viper|cast)' go.mod go.sum || true

echo "Heartbeat parser, scheduler, and callers:"
rg -n -C 4 \
  'GetDuration\("heartbeat_interval"\)|GetHeartbeatInterval\(\)|startHeartbeat\(|NewScheduledTask\("Heartbeat reporter"|func NewScheduledTask' \
  . --glob '*.go'

echo "Heartbeat configuration values:"
rg -n -C 2 'heartbeat_interval' conf docker \
  --glob '*.yaml' --glob '*.template' --glob '*.env'

Repository: infiniflow/ragflow

Length of output: 10248


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "Viper/cast source availability in module cache / GOPATH:"
gopath="$(go env GOPATH 2>/dev/null || true)"
echo "gopath=$gopath"
if [ -n "$gopath" ]; then
  find "$gopath/pkg/mod/github.com/spf13" -maxdepth 3 -type f \( -name 'viper.go' -o -name 'cast.go' \) 2>/dev/null | sed -n '1,40p' || true
  for f in $(find "$gopath/pkg/mod/github.com/spf13" -maxdepth 3 -type f \( -name 'viper.go' -o -name 'cast.go' \) 2>/dev/null | sed -n '1,10p'); do
    echo "--- $f ---"
    rg -n 'func .*GetDuration|func ToDuration|ToDuration|ParseDuration|Duration' "$f" -A 25 -B 5 || true
  done
fi

echo "Programmatic cast.GetDuration behavior from repository module cache:"
python3 - <<'PY'
import subprocess, tempfile, textwrap, pathlib
gopath = subprocess.check_output(["go", "env", "GOPATH"], text=True).strip()
try:
    cast_path = next(pathlib.Path(gopath, "pkg/mod/github.com/spf13/[email protected]").glob("*.go"))
    cast_text = cast_path.read_text()
    print("found_cast", cast_path)
    print("ToDuration_present", "ToDuration(" in cast_text)
    print("ToDuration_definition")
    for i,line in enumerate(cast_text.splitlines(), 1):
        if "func ToDuration(" in line:
            start=max(1,i-5); end=min(len(cast_text.splitlines()), i+20)
            print("\n".join(f"{n}: {cast_text.splitlines()[n-1]}" for n in range(start,end+1)))
finally:
    pass
PY

Repository: infiniflow/ragflow

Length of output: 9544


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "Relevant config parsing sections:"
sed -n '1,150p' internal/server/config/general_config.go
sed -n '500,545p' cmd/ragflow_server.go
sed -n '86,125p' internal/utility/scheduled_task.go

echo "Search for heartbeat env/key names and schema validation:"
rg -n -C 3 'HEARTBEAT|heartbeat_interval|RAGFLOW .*HEARTBEAT|GENERAL__|GetDuration|ErrInvalid|Invalid.*heartbeat|validate.*heartbeat|heartbeat.*interval' . --glob '*.go' --glob '*.yaml' --glob '*.template' --glob '*.env'

echo "Cast import/source references:"
rg -n 'ToDuration|ToDurationE|ParseDuration|StringToTimeDuration|^package cast|^import' "$GOPATH/pkg/mod/github.com/spf13/[email protected]" --glob '*.go' -A 12 -B 3 || true

echo "Behavioral probe of cast.ToDuration for numeric heartbeat values if Go package is importable:"
go run -modfile=<(awk '/require \($|^\tgithub.com\/spf13\/(viper|cast)\s+|^)$/{if(/\tgithub.com\/spf13\/(viper|cast)\s+/){print; p++} if(p>0 && /^)$/ && p==1){print; exit}}' go.mod) '
package main
import (
  "fmt"
  "github.com/spf13/cast"
)
func main() {
  for _, v := range []interface{}{3, 3.5, "3", "3s", "3m"} {
    d := cast.ToDuration(v)
    fmt.Printf("%T(%v) -> %v\n", v, v, d)
  }
}
' || true

echo "Parse duration behavior independent of repo code:"
cat >/tmp/check_duration.go <<'EOF'
package main

import (
  "fmt"
  "strconv"
  "strings"
  "time"
)

// Mirrors cast v1.6.0 ToDuration numeric path behavior: int/int64/uint64
// become duration nanoseconds; duration strings go through time.ParseDuration.
func toDuration(i interface{}) time.Duration {
	switch v := i.(type) {
	case int64:
		return time.Duration(v)
	case int:
		return time.Duration(v)
	case uint64:
		return time.Duration(v)
	case string:
		if strings.HasPrefix(v, "0x") {
			iv := strings.ParseInt(v, 0, 0)
			return time.Duration(int(iv))
		}
		d, err := time.ParseDuration(v)
		if err != nil {
			return minDuration
		}
		return d
	default:
		return minDuration
	}
}

func main() {
	for _, in := range []interface{}{3, 3.5, "3", "3s", "3m"} {
		d := toDuration(in)
		fmt.Printf("%T(%v) -> %v\n", in, in, d)
	}
}
EOF
go run /tmp/check_duration.go

Repository: infiniflow/ragflow

Length of output: 38369


Reject unitless heartbeat_interval values before scheduling.

GetDuration("heartbeat_interval") uses cast.ToDuration, so numeric values are treated as nanoseconds. A bare heartbeat_interval: 3 becomes 3ns, and NewScheduledTask starts a ticker that can keep the server near-busy. Parse duration strings explicitly and reject bare numbers with a startup error, or document and apply a migration; add coverage for duration strings, bare numbers, and RAGFLOW_GENERAL__HEARTBEAT_INTERVAL.

🤖 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 `@cmd/ragflow_server.go` at line 528, Update the heartbeat interval
configuration flow before constructing the “Heartbeat reporter” ScheduledTask to
reject bare numeric values, including RAGFLOW_GENERAL__HEARTBEAT_INTERVAL,
instead of interpreting them as nanoseconds. Parse and accept explicit duration
strings, return a clear startup error for unitless values, and add coverage for
valid duration strings, rejected numbers, and the environment-variable
configuration path.

Source: Coding guidelines

EnvTCADPApiKey = "TCADP_API_KEY"
EnvRAGFlowSecretKey = "RAGFLOW_SECRET_KEY"
EnvRegisterEnabled = "REGISTER_ENABLED"
EnvEnableRegister = "ENABLE_REGISTER"

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 | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

rg -n -C 2 '\bREGISTER_ENABLED\b|\bEnvRegisterEnabled\b|\bENABLE_REGISTER\b|\bEnvEnableRegister\b' .

Repository: infiniflow/ragflow

Length of output: 7815


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

# Inspect Go and Python config/runtime paths around registration keys and defaults.
printf '\n== internal/server/config/environments.go ==\n'
cat -n internal/server/config/environments.go | sed -n '1,110p'

printf '\n== internal/server/config/api_server_config.go around EnableRegister ==\n'
rg -n -C 4 'EnableRegister|EnvEnableRegister|REGISTER_ENABLED' internal/server/config internal/common | sed -n '1,220p'

printf '\n== common/settings.py around REGISTER_ENABLED ==\n'
cat -n common/settings.py | sed -n '85,245p'

printf '\n== Python runtime registration switches ==\n'
rg -n -C 2 '\bsettings\.REGISTER_ENABLED\b|REGISTER_ENABLED' api apps common testcases 2>/dev/null | sed -n '1,240p'

Repository: infiniflow/ragflow

Length of output: 17800


Keep registration configuration consistent across Go and Python.

common/settings.py still reads REGISTER_ENABLED and exposes settings.REGISTER_ENABLED, but the Go config now reads ENABLE_REGISTER. If deployments set only one key, the Go and Python runtimes diverge. Either retire the Python path or add a focused shared/default bridge while removing legacy duplicate documentation and deployment entries.

🧰 Tools
🪛 ast-grep (0.45.0)

[warning] 171-171: A credential is hard-coded as a string literal. Secrets stored in source code, such as passwords, API keys, and tokens, can be leaked through version control or binaries and used by internal or external malicious actors. Rotate the exposed secret and load it at runtime from a secure secret vault, a Hardware Security Module (HSM), or an environment variable if permitted by your company policy (e.g. password := os.Getenv("APP_PASSWORD")).
Context: EnvDisablePasswordLogin = "DISABLE_PASSWORD_LOGIN"
Note: [CWE-798] Use of Hard-coded Credentials.

(hardcoded-credentials-string-literal-go)

📍 Affects 2 files
  • internal/common/environments.go#L171-L171 (this comment)
  • docker/.env#L271-L271
🤖 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/common/environments.go` at line 171, Align registration
configuration across Go and Python by making EnvEnableRegister and
settings.REGISTER_ENABLED use one shared key or retiring the legacy Python
setting, while preserving a consistent default. Update the deployment entry at
docker/.env lines 271-271 accordingly and remove duplicate legacy documentation
or deployment entries; apply the corresponding configuration change at
internal/common/environments.go lines 171-171.

Source: Coding guidelines

Comment on lines +57 to +77
if envVal := common.GetEnv(common.EnvEnableRegister); envVal != "" {
if c.environments.EnableRegister == nil {
c.environments.EnableRegister = new(bool)
}
str := strings.ToLower(envVal)
if str == "true" || str == "1" || str == "yes" {
c.environments.RegisterEnabled = true
*c.environments.EnableRegister = true
} else {
c.environments.RegisterEnabled = false
*c.environments.EnableRegister = false
}
}

// Load DISABLE_PASSWORD_LOGIN from environment variable (default: false)
if envVal := common.GetEnv(common.EnvDisablePasswordLogin); envVal != "" {
if c.environments.DisablePasswordLogin == nil {
c.environments.DisablePasswordLogin = new(bool)
}
str := strings.ToLower(envVal)
if str == "true" || str == "1" || str == "yes" {
c.environments.DisablePasswordLogin = true
*c.environments.DisablePasswordLogin = true
} else {
c.environments.DisablePasswordLogin = false
*c.environments.DisablePasswordLogin = false

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 | 🟠 Major | ⚡ Quick win

Reject invalid boolean values instead of mapping them to false.

The parser assigns false to every value other than true, 1, or yes. A typo such as DISABLE_PASSWORD_LOGIN=flase therefore enables password login without an error. The same behavior hides invalid ENABLE_REGISTER values.

Accept explicit false values such as false, 0, and no. Return an error for unknown values.

🤖 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/environments.go` around lines 57 - 77, The environment
boolean parsing in the EnableRegister and DisablePasswordLogin handling must
distinguish valid true and false values from invalid input. Accept true/1/yes as
true and false/0/no as false, while returning an error for any other value
instead of silently assigning false; preserve the existing pointer
initialization and propagate the parsing error from the surrounding
configuration method.

Signed-off-by: Jin Hai <[email protected]>
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Aug 2, 2026
@JinHai-CN JinHai-CN added the ci Continue Integration label Aug 2, 2026
Signed-off-by: Jin Hai <[email protected]>

@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 `@cmd/ragflow_server.go`:
- Around line 369-376: Update the startup initialization flow around
storage.Init and engine.InitMessageQueue to stop startup immediately when either
required dependency fails, rather than logging and continuing. Ensure
storage.CloseStorage is deferred only after successful storage initialization,
preventing cleanup from dereferencing an uninitialized storage instance;
preserve the existing initialization error context when returning or exiting.

In `@internal/common/logger.go`:
- Line 99: Update the renamed initialization API call sites: keep
common.InitLogger in internal/common/logger.go:99, use InitDocEngine and
InitMessageQueue at the corresponding initialization sites in
internal/engine/global.go:42, internal/engine/global.go:97, and
internal/storage/storage_factory.go:46, and update callers in
cmd/ragflow-cli.go, internal/tokenizer/tokenizer_concurrent_test.go, and
internal/ingestion/task/pipeline_real_integration_test.go from common.Init.
Replace engine.Init in internal/ingestion/testutil/nats_helper.go with the
intended InitDocEngine initializer.

In `@internal/server/config/cache_engine_config.go`:
- Around line 82-86: Update the Redis host parsing flow around net.SplitHostPort
and the port assignment to reject empty, non-numeric, and out-of-range port
values whenever a host:port form is accepted. Do not retain the default port or
continue with configuration when strconv.Atoi fails or the parsed port is
outside the valid TCP port range; return the existing configuration error path
instead.
- Around line 72-80: Update the Redis client address construction in the
relevant engine configuration flow to use net.JoinHostPort with redisConfig.Host
and the port converted via strconv.Itoa, preserving brackets for IPv6 hosts. Add
a regression test covering the [::1,6379] configuration and verify it produces a
valid Redis address.

In `@internal/server/config/general_config.go`:
- Line 49: Update GetEnvironments and Config.Language so configured
general.language remains usable when LANG and LANGUAGE are unset: only assign
environments.Language when an environment value exists, and apply one consistent
language format or map it at the Config.Language boundary. Add focused coverage
for both unset environment variables and a configured general language.
🪄 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 Plus

Run ID: e01339db-fe2d-4932-89af-17eac7608996

📥 Commits

Reviewing files that changed from the base of the PR and between 11fda25 and 819d0cd.

📒 Files selected for processing (7)
  • cmd/ragflow_server.go
  • internal/common/logger.go
  • internal/engine/global.go
  • internal/engine/redis/redis.go
  • internal/server/config/cache_engine_config.go
  • internal/server/config/general_config.go
  • internal/storage/storage_factory.go

Comment thread cmd/ragflow_server.go
Comment on lines +369 to 376
if err = storage.Init(); err != nil {
common.Error("Failed to initialize storage factory", err)
}
defer storage.CloseStorage()

if err = engine.InitMessageQueueEngine(); err != nil {
if err = engine.InitMessageQueue(); err != nil {
common.Error("Failed to initialize message queue engine", err)
}

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 | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

rg -n -A20 -B5 \
  'func Init\(\) error|func CloseStorage\(\) error' \
  internal/storage/storage_factory.go --glob '*.go'

rg -n -A20 -B5 \
  'func InitMessageQueue\(\) error' \
  internal/engine/global.go --glob '*.go'

rg -n -A12 -B4 \
  'storage\.Init\(\)|engine\.InitMessageQueue\(\)|server\.StartServer' \
  cmd/ragflow_server.go

Repository: infiniflow/ragflow

Length of output: 3031


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

sed -n '180,340p' internal/storage/storage_factory.go
sed -n '340,395p' cmd/ragflow_server.go
pgrep -x main >/dev/null 2>&1 && { echo "main process found"; pgrep -l main; } || true

Repository: infiniflow/ragflow

Length of output: 1859


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

sed -n '80,180p' internal/storage/storage_factory.go
sed -n '1,100p' internal/engine/global.go
rg -n "type StorageFactory|var storageFactory|GetStorageFactory|storage :|Close\(.*\)" internal/storage internal/engine --glob '*.go'

Repository: infiniflow/ragflow

Length of output: 11695


Fail fast when storage or message-queue initialization fails.

storage.Init() and engine.InitMessageQueue() are logged and ignored, so startup can continue without required dependencies. An initialization failure leaves storage.storage nil and CloseStorage() dereferences it during shutdown. Treat these failures as fatal or only defer cleanup when the engine is intentionally optional.

🤖 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 `@cmd/ragflow_server.go` around lines 369 - 376, Update the startup
initialization flow around storage.Init and engine.InitMessageQueue to stop
startup immediately when either required dependency fails, rather than logging
and continuing. Ensure storage.CloseStorage is deferred only after successful
storage initialization, preventing cleanup from dereferencing an uninitialized
storage instance; preserve the existing initialization error context when
returning or exiting.

Comment thread internal/common/logger.go
// Numeric fields (MaxSize, MaxBackups, MaxAge) are defaulted to 100/10/30
// when zero. Compress is taken as supplied.
func Init(level string, file FileOutput, serviceName string) error {
func InitLogger(level string, file FileOutput, serviceName string) error {

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

failed=0

for pattern in \
  'common\.Init[[:space:]]*\(' \
  'engine\.Init[[:space:]]*\(' \
  '\bInitMessageQueueEngine\b' \
  '\bInitStorageFactory\b'
do
  if rg -n --glob '*.go' "$pattern" .; then
    failed=1
  fi
done

exit "$failed"

Repository: infiniflow/ragflow

Length of output: 620


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf 'Relevant API definitions:\n'
rg -n 'func Init(Common|Logger|DocEngine|MessageQueue|MessageQueueEngine|StorageFactory|Storage)\(' internal cmd --glob '*.go' || true

printf '\nOld API usages with context:\n'
for f in \
  cmd/ragflow-cli.go \
  internal/tokenizer/tokenizer_concurrent_test.go \
  internal/ingestion/task/pipeline_real_integration_test.go \
  internal/ingestion/testutil/nats_helper.go
do
  echo "--- $f"
  rg -n -C 2 'common\.Init\(|engine\.Init\(|InitMessageQueueEngine|InitStorageFactory' "$f" || true
done

printf '\nAll relevant new API usages:\n'
rg -n 'common\.InitLogger\(|engine\.InitDocEngine\(|engine\.InitMessageQueue\(|storage\.Init\(' cmd internal --glob '*.go' || true

Repository: infiniflow/ragflow

Length of output: 1877


Update the remaining callers to the renamed initialization APIs.

cmd/ragflow-cli.go, internal/tokenizer/tokenizer_concurrent_test.go, and internal/ingestion/task/pipeline_real_integration_test.go still call common.Init(...) instead of common.InitLogger(...).

internal/ingestion/testutil/nats_helper.go calls engine.Init() at L65; update that call to match the renamed document-engine initializer if it is the intended path.

Update these call sites to compile and use InitDocEngine()/InitMessageQueue() instead of legacy or unknown init names.

📍 Affects 3 files
  • internal/common/logger.go#L99-L99 (this comment)
  • internal/engine/global.go#L42-L42
  • internal/engine/global.go#L97-L97
  • internal/storage/storage_factory.go#L46-L46
🤖 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/common/logger.go` at line 99, Update the renamed initialization API
call sites: keep common.InitLogger in internal/common/logger.go:99, use
InitDocEngine and InitMessageQueue at the corresponding initialization sites in
internal/engine/global.go:42, internal/engine/global.go:97, and
internal/storage/storage_factory.go:46, and update callers in
cmd/ragflow-cli.go, internal/tokenizer/tokenizer_concurrent_test.go, and
internal/ingestion/task/pipeline_real_integration_test.go from common.Init.
Replace engine.Init in internal/ingestion/testutil/nats_helper.go with the
intended InitDocEngine initializer.

Comment on lines +72 to +80
host, portStr, err := net.SplitHostPort(hostStr)
if err != nil {
return fmt.Errorf("error address format of Redis: %s", hostStr)
}

if host == "" {
return fmt.Errorf("empty host of Redis configuration")
}
c.cacheEngine.Redis.Host = host

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== candidate files =="
fd -a 'cache_engine_config\.go|redis\.go$|redis.*go$' . | sed 's#^\./##'

echo
echo "== cache_engine_config snippet =="
if [ -f internal/server/config/cache_engine_config.go ]; then
  nl -ba internal/server/config/cache_engine_config.go | sed -n '1,130p'
fi

echo
echo "== redis.go matches =="
if [ -f internal/engine/redis/redis.go ]; then
  nl -ba internal/engine/redis/redis.go | sed -n '1,180p'
fi

echo
echo "== searches for redis address formatting and tests =="
rg -n 'SplitHostPort|JoinHostPort|fmt\.Sprintf\("%s:%d"|Addr:|Address:|::1|IPv6|Redis' -S --glob '*.go' internal .github 2>/dev/null | head -200

Repository: infiniflow/ragflow

Length of output: 424


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== cache_engine_config.go =="
sed -n '1,140p' internal/server/config/cache_engine_config.go

echo
echo "== redis.go =="
sed -n '1,180p' internal/engine/redis/redis.go

echo
echo "== redis tests relevant =="
sed -n '1,220p' internal/engine/redis/redis_test.go

echo
echo "== addresses in Go files =="
grep -RIn 'SplitHostPort\|JoinHostPort\|fmt\.Sprintf\("%s:%d"\)\|Addr:' internal --include '*.go' || true
grep -RIn '::1\|IPv6\|RedisAddress\|redis-address' . --include '*.go' --include '*.yaml' --include '*.yml' --include '*.toml' --include '*.md' || true

echo
echo "== Go net behavior probe =="
if command -v go >/dev/null 2>&1; then
  cat >/tmp/ipv6probe.go <<'GO'
package main

import (
	"fmt"
	"net"
	"strconv"
)

func main() {
	hostStr := "[::1]:6379"
	host, portStr, err := net.SplitHostPort(hostStr)
	if err != nil {
		fmt.Printf("SplitHostPort error: %v\n", err)
		return
	}
	fmt.Printf("SplitHostPort host=%q port=%q\n", host, portStr)
	old := fmt.Sprintf("%s:%s", host, "6379")
	fmt.Printf("old Addr=%q parsed=%v\n", old, net.JoinCall(old))

	fmt.Printf("JoinHostPort Addr=%q parsed=%v\n", net.JoinHostPort(host, "6379"), net.JoinCall(net.JoinHostPort(host, "6379")))
}
GO
  go run /tmp/ipv6probe.go
else
  python3 - <<'PY'
# Illustrate semantics; Go parse may not be needed beyond source evidence.
host = "[::1]:6379"
idx = host.rindex(':')
split_host, split_port = host[:idx], host[idx+1:]
print("SplitHostPort host:", repr(split_host))
old = f"{split_host}:6379"
print("old Addr:", repr(old), "valid when using net.JoinHostPort:", old == ("::1:6379"))
print("JoinHostPort Addr:", repr(f"{split_host}:6379"))
PY
fi

Repository: infiniflow/ragflow

Length of output: 20481


🌐 Web query:

Go net SplitHostPort brackets IPv6 net.JoinHostPort documentation

💡 Result:

In Go, the net.JoinHostPort and net.SplitHostPort functions manage the inclusion of square brackets around literal IPv6 addresses to disambiguate them from the colon used to separate the port [1][2]. net.JoinHostPort This function combines a host and port into a single string [2]. If the provided host contains a colon—which is characteristic of literal IPv6 addresses—the function automatically encloses the host in square brackets, returning the format "[host]:port" [2]. net.SplitHostPort This function performs the reverse, splitting a network address (such as "host:port", "[host]:port", or "[host%zone]:port") into its host and port components [1][3]. It is designed to handle bracketed IPv6 addresses correctly, stripping the brackets and returning the raw host or host%zone [1]. Important Update As of 2026, there have been updates to how net.SplitHostPort handles brackets [4][5]. Historically, the function would strip brackets from any string regardless of content (e.g., "[hostname]:port" would result in "hostname" and "port"). To align with RFC 3986, which specifies that brackets are only valid for IPv6 addresses, recent changes have been introduced to ensure that bracketed content in net.SplitHostPort is validated as a literal IPv6 address [4][5]. If the content inside the brackets is not a valid IPv6 address, the function may now return an error [4].

Citations:


Preserve IPv6 syntax when Redis builds its address.

net.SplitHostPort("[::1]:6379") stores the host as ::1 without brackets, so internal/engine/redis, Lines 121 formats it as ::1:6379, which is not a valid host:port address for the Redis client. Rebuild it with net.JoinHostPort(redisConfig.Host, strconv.Itoa(redisConfig.Port)) before creating the client.

Add a regression case for [::1,6379].

🤖 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/cache_engine_config.go` around lines 72 - 80, Update
the Redis client address construction in the relevant engine configuration flow
to use net.JoinHostPort with redisConfig.Host and the port converted via
strconv.Itoa, preserving brackets for IPv6 hosts. Add a regression test covering
the [::1,6379] configuration and verify it produces a valid Redis address.

Comment on lines +82 to 86
if portStr != "" {
var port int
if port, err = strconv.Atoi(portStr); err == nil {
c.cacheEngine.Redis.Port = port
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== file context =="
cat -n internal/server/config/cache_engine_config.go | sed -n '1,140p'

echo
echo "== surrounding config usages =="
rg -n "cacheEngine.Redis|Redis\.Host|Redis\.Port|Parse.*Cache|cache_engine|CACHE" internal server . --glob '!vendor/**' --glob '!node_modules/**' | head -200

echo
echo "== deterministic behavior probe =="
python3 - <<'PY'
import re
def host_port(host_port_str):
    # Mimic only the shown parser enough to demonstrate empty/non-numeric behavior;
    # exact source parsing may differ, so this check is not authoritative.
    pass
# Use Python's standard lib parser for comparison:
for s in ["localhost", "localhost:", "localhost:abc", "localhost:6379", "localhost:-1", "localhost:65536"]:
    try:
        import urllib.parse
        u = urllib.parse.urlparse("redis://" + s)
        print(repr(s), "host=", repr(u.hostname), "port=", repr(u.port), "netloc=", repr(u.netloc))
    except Exception as e:
        print(repr(s), "error", type(e).__name__, str(e))
PY

Repository: infiniflow/ragflow

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate exact file =="
git ls-files | grep -Fx 'internal/server/config/cache_engine_config.go' || true

echo
echo "== file context =="
sed -n '1,140p' internal/server/config/cache_engine_config.go | cat -n

echo
echo "== focused config redis usages =="
rg -n "cacheEngine\.Redis|Redis\.Host|Redis\.Port|strsplit|Split\(host_port|Parse" internal/server config --glob '*.go' --glob '!**/node_modules/**' | head -200

echo
echo "== exact git diff around file if available =="
git diff -- internal/server/config/cache_engine_config.go | sed -n '1,220p' || true

Repository: infiniflow/ragflow

Length of output: 8213


Reject invalid Redis ports once host:port is accepted.

When the host contains a port specifier, net.SplitHostPort accepts values like localhost:abc; the code then ignores strconv.Atoi failure and keeps the default 6379, which can connect to an unintended endpoint. Reject missing, non-numeric, and out-of-range ports after net.SplitHostPort succeeds.

🤖 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/cache_engine_config.go` around lines 82 - 86, Update
the Redis host parsing flow around net.SplitHostPort and the port assignment to
reject empty, non-numeric, and out-of-range port values whenever a host:port
form is accepted. Do not retain the default port or continue with configuration
when strconv.Atoi fails or the parsed port is outside the valid TCP port range;
return the existing configuration error path instead.

c.general.QueueEngine = "nats"
c.general.AnalyticEngine = "clickhouse"
c.general.Language = "english"
c.general.Language = "en"

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 | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

rg -n -A20 -B5 \
  'func GetLanguage|c\.environments\.Language = GetLanguage|func \(c \*Config\) Language' \
  internal/server/config --glob '*.go'

rg -n 'Language\(\)|GetLanguage|general.*language' \
  internal/server/config --glob '*_test.go'

Repository: infiniflow/ragflow

Length of output: 2752


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "== general_config.go relevant sections =="
sed -n '1,80p;115,130p' internal/server/config/general_config.go
echo
echo "== environments.go relevant sections =="
sed -n '135,167p' internal/server/config/environments.go
echo
echo "== config tests mentioning Language/Env =="
rg -n -C 3 'Language\(|GetLanguage|EnvLang|LANGUAGE|general.*language' internal/server/config --glob '*_test.go' || true
echo
echo "== Language() callers =="
rg -n '\.Language\(\)' --glob '*.{go,py,ts,tsx}' .

Repository: infiniflow/ragflow

Length of output: 3851


Make the language fallback reachable and use one canonical policy.

GetEnvironments() always writes c.environments.Language = GetLanguage(), so Config.Language() returns "English" or "Chinese" before c.general.Language can be used; a configured general.language is ignored. Only populate c.environments.Language when LANG or LANGUAGE is set, and either use one format across both paths or map the values at the Config.Language() boundary. Add focused coverage for unset environment variables and a configured general language.

🤖 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/general_config.go` at line 49, Update GetEnvironments
and Config.Language so configured general.language remains usable when LANG and
LANGUAGE are unset: only assign environments.Language when an environment value
exists, and apply one consistent language format or map it at the
Config.Language boundary. Add focused coverage for both unset environment
variables and a configured general language.

@codecov

codecov Bot commented Aug 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (d4ceeee) to head (0beda90).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #17684   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

☔ 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.

Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN
JinHai-CN merged commit b2521eb into infiniflow:main Aug 2, 2026
5 checks passed
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