Skip to content

Go: merge duplicate codes - #16783

Merged
JinHai-CN merged 10 commits into
infiniflow:mainfrom
JinHai-CN:fix530
Jul 10, 2026
Merged

JinHai-CN merged 10 commits into
infiniflow:mainfrom
JinHai-CN:fix530

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

Summary

  1. merge heartbeat function.
  2. introduce all environments

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

coderabbitai Bot commented Jul 9, 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
📝 Walkthrough

Walkthrough

This PR adds shared environment helpers and migrates environment-variable reads across server, configuration, services, agents, sandboxes, parsers, CLI, ingestion, tokenizer, and tests to shared constants and accessors. It also includes minor local variable assignment cleanups.

Changes

Environment access centralization

Layer / File(s) Summary
Shared environment helpers
internal/common/environments.go
Adds GetEnv, GetEnvSmall, and exported Env* constants.
Server and administrative configuration
internal/server/config.go, internal/admin/service.go, internal/service/system.go, cmd/ragflow_server.go
Uses shared environment access for server settings, environment listings, language, MinIO, and tokenizer dictionary paths.
Service, agent, sandbox, and CLI configuration
internal/service/*.go, internal/agent/**, internal/cli/**
Migrates feature flags, provider settings, runtime options, storage values, home directories, proxies, and tool configuration.
Parser and model configuration
internal/deepdoc/**, internal/parser/parser/**, internal/entity/models/**
Migrates DeepDoc, PDF backend, TEI, and related API configuration lookups.
Ingestion, tokenizer, and tests
internal/ingestion/**, internal/tokenizer/**, internal/deepdoc/parser/pdf/**, internal/engine/elasticsearch/kg_test.go
Migrates test and setup environment access, including tokenizer paths, batch settings, OCR selection, and integration-service configuration.
Local assignment cleanup
internal/ingestion/compilation/extractor/ner.go, internal/parser/parser/pdf_parser_opendataloader.go, internal/service/file.go
Reuses existing err and local variables instead of short declarations in selected paths.

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

Possibly related issues

Possibly related PRs

Suggested reviewers: yingfeng, yuzhichang

Poem

Env vars hop into one tidy burrow,
Constants guide them straight, not narrow.
Parsers and sandboxes follow the trail,
Tokenizers find their paths without fail.
A rabbit cheers: shared access prevails! 🐇

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description has the required Summary section, but it is too terse and includes unclear or unrelated points. Expand the summary with the PR goal, background context, and a clear explanation of the actual changes.
Docstring Coverage ⚠️ Warning Docstring coverage is 57.97% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is related to the refactor, but it is too generic to clearly describe the main change. Use a specific title like “Centralize environment variable access in Go”.
✅ Passed checks (2 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.

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 changed the title Merge duplicate codes Go: merge duplicate codes Jul 9, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 9, 2026 12:46
@JinHai-CN JinHai-CN added the ci Continue Integration label Jul 9, 2026
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code labels Jul 9, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft July 9, 2026 12:47
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 9, 2026 12:47
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: 12

Caution

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

⚠️ Outside diff range comments (2)
internal/service/system.go (2)

478-485: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Lowercasing inconsistency between system service and admin service for DB_TYPE, DEVICE, and STORAGE_IMPL.

This file uses common.GetEnvSmall (lowercases) while internal/admin/service.go uses common.GetEnv (no lowercasing) for the same variables. Both ListEnvironments functions serve the same type of data through different endpoints, so they should return consistent values. For example, DB_TYPE=MySQL yields "mysql" here but "MySQL" in the admin service. Additionally, the STORAGE_IMPL default is "MINIO" (uppercase), so the output casing is inconsistent within this file itself (lowercase when set, uppercase when defaulted).

🔧 Proposed fix: align with admin service by using `GetEnv`
-	dbType := common.GetEnvSmall(common.EnvDBType)
+	dbType := common.GetEnv(common.EnvDBType)
 	if dbType == "" {
 		dbType = "mysql"
 	}
-	device := common.GetEnvSmall(common.EnvDevice)
+	device := common.GetEnv(common.EnvDevice)
 	if device == "" {
 		device = "cpu"
 	}
-	storageImpl := common.GetEnvSmall(common.EnvStorageImpl)
+	storageImpl := common.GetEnv(common.EnvStorageImpl)
 	if storageImpl == "" {
 		storageImpl = "MINIO"
 	}

Also applies to: 488-495, 498-505

🤖 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/service/system.go` around lines 478 - 485, The ListEnvironments
handling in system service is normalizing some values to lowercase via
common.GetEnvSmall, which makes DB_TYPE, DEVICE, and STORAGE_IMPL inconsistent
with internal/admin/service.go and even inconsistent within the STORAGE_IMPL
fallback path. Update the environment reads in the ListEnvironments logic to use
common.GetEnv for these variables, and keep the default values in the same
casing as the returned values so both service endpoints expose consistent
casing.

468-474: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Preserve DEFAULT_SUPERUSER_EMAIL casing internal/service/system.go:468
common.GetEnvSmall lowercases the configured email, changing the value reported by ListEnvironments and diverging from the other DEFAULT_SUPERUSER_EMAIL reads. Use common.GetEnv here so the displayed address matches the configured one.

🤖 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/service/system.go` around lines 468 - 474, `ListEnvironments` is
lowercasing `DEFAULT_SUPERUSER_EMAIL` by using `common.GetEnvSmall`, so update
the `defaultSuperuserEmail` lookup in `internal/service/system.go` to use
`common.GetEnv` instead and keep the existing fallback to `[email protected]`;
this preserves the configured casing while keeping the `result` entry and
surrounding `DEFAULT_SUPERUSER_EMAIL` handling unchanged.
🧹 Nitpick comments (2)
internal/server/config.go (1)

555-560: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider using GetEnvSmall instead of strings.ToLower(common.GetEnv(...)).

Both MinIO host and region lines manually lowercase the result of common.GetEnv, which is exactly what common.GetEnvSmall does. Using GetEnvSmall would be more consistent with the rest of the file (e.g., lines 479, 521, 535).

♻️ Proposed refactor
-	minioHost := strings.ToLower(common.GetEnv(common.EnvMinioHost))
+	minioHost := common.GetEnvSmall(common.EnvMinioHost)
 	if minioHost != "" {
 		globalConfig.StorageEngine.Minio.Host = minioHost
 	}
 
-	minioRegion := strings.ToLower(common.GetEnv(common.EnvMinioRegion))
+	minioRegion := common.GetEnvSmall(common.EnvMinioRegion)
🤖 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 555 - 560, Replace the manual
lowercasing in the MinIO config setup with the existing helper used elsewhere in
this file. In the config-loading logic around the MinIO host and region
assignments, use common.GetEnvSmall instead of
strings.ToLower(common.GetEnv(...)) for both values, keeping the same nil/empty
checks and assignments in the surrounding Minio host/region handling.
internal/deepdoc/parser/pdf/tool/config.go (1)

35-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use common.EnvBatchCompareCSV constant instead of raw string literal for consistency.

Line 35 still passes the raw string "BATCH_COMPARE_CSV" to envStr, while all other env vars in LoadConfig were migrated to use common.Env* constants. The constant common.EnvBatchCompareCSV exists and maps to "BATCH_COMPARE_CSV".

♻️ Proposed fix
-		CSVOutput:     envStr("BATCH_COMPARE_CSV", filepath.Join(td, "output", fmt.Sprintf("compare_%s.csv", time.Now().Format("20060102_150405")))),
+		CSVOutput:     envStr(common.EnvBatchCompareCSV, filepath.Join(td, "output", fmt.Sprintf("compare_%s.csv", time.Now().Format("20060102_150405")))),
🤖 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/deepdoc/parser/pdf/tool/config.go` at line 35, `LoadConfig` is still
using the raw `"BATCH_COMPARE_CSV"` env key for `CSVOutput`; update that
`envStr` call to use `common.EnvBatchCompareCSV` like the other `common.Env*`
constants in this function. Keep the existing fallback path logic unchanged and
just swap the env name reference in `config.go` so the config stays consistent.
🤖 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 403-419: The heartbeat reporter is being stopped too early because
`startHeartBeat()` defers `heartbeatReporter.Stop()` inside a regular function,
so the cleanup runs as soon as the function returns. Update `startHeartBeat` to
return a cleanup/stop function (or move the defer back to each caller such as
the `runIngestor`-style call sites) so `heartbeatReporter.Start()` remains
active for the process lifetime and `local.SetAdminStatus` can be updated by
`SendHeartbeat`.

In `@internal/common/environments.go`:
- Around line 33-191: The build is failing because the migration to
common.GetEnv left a stale os import in internal/deepdoc/client.go. Update the
DeepDoc client code that reads env vars (near the EnvDeepDocURL/EnvOSSDeepDocURL
usage) to rely only on the shared helper, then remove the unused os import so
the package typechecks again.
- Line 95: Rename the SSH password environment constant to match the other SSH
symbols: update EnvSSPassword to EnvSSHPassword in the environments constants so
it is consistent with the related SSH identifiers. Also update any references to
this constant throughout the codebase to use the new name and keep the same
value.

In `@internal/deepdoc/client.go`:
- Around line 32-33: Remove the unused os import from client.go in the
internal/deepdoc package so the import list only contains symbols actually
referenced by the file, leaving common intact and ensuring the package compiles
cleanly.

In `@internal/deepdoc/parser/pdf/compare_test.go`:
- Line 9: Remove the unused os import from internal/deepdoc/client.go so the
internal/deepdoc package compiles cleanly and the package tests can run; update
the import block in the client code to drop os and keep only the imports
actually referenced by the client/parser logic.

In `@internal/deepdoc/parser/pdf/parser_pipeline_integration_test.go`:
- Line 69: The test is referencing an undeclared environment toggle, so fix the
`GetEnv` call in `parser_pipeline_integration_test.go` to use a valid symbol
from `common/environments.go`. Either add the missing `EnvUpdateGolden` constant
in `common` if that is the intended flag, or switch the test to the existing
`EnvUpdateGoldenJSON` constant so the build compiles and the toggle name matches
the current environment definitions.

In `@internal/deepdoc/parser/pdf/text_dump_test.go`:
- Line 27: The `internal/deepdoc/client.go` cleanup left an unused `os` import
behind after switching env lookups to `common.GetEnv`, which breaks typecheck.
Remove the `"os"` import from the imports block in `client.go`, and make sure
any remaining environment access in that file continues to use `common.GetEnv`
so there are no other `os` references left.

In `@internal/engine/elasticsearch/kg_test.go`:
- Line 77: The test setup in kg_test.go is using the wrong environment variable
symbol, causing a compile failure because common.EnvESHosts does not exist.
Update the EnvESHosts reference in the Elasticsearch test code to
common.EnvESHost, matching the declared ES_HOST constant and keeping the
existing GetEnv call unchanged.

In `@internal/parser/parser/pdf_parser_mineru.go`:
- Around line 21-24: The MinerU API server env lookup in pdf_parser_mineru.go is
no longer backward compatible because EnvMineruApiServerURL now maps to
MINERU_APISERVER_URL while existing deployments may still rely on
MINERU_APISERVER. Update the apiServer initialization path in the MinerU parser
logic to accept the old variable as a fallback, or consistently migrate the
validation/error text in ParseResult to reference the new name; keep the
behavior aligned with common.GetEnv and the parser error message so both names
are handled clearly.

In `@internal/parser/parser/pdf_parser_opendataloader.go`:
- Around line 22-25: The OpenDataLoader parser currently only reads
common.EnvOpenDataLoaderApiServerURL, so update the baseURL resolution in
parser/pdf_parser_opendataloader.go to accept the legacy
OPENDATALOADER_APISERVER value as a fallback in the same lookup path. Adjust the
ParseResult error in the parser setup to reflect the actual supported env vars,
and keep the behavior centralized in the parser initialization logic so
deployments using either name continue to work.

In `@internal/parser/parser/pdf_parser_tcadp.go`:
- Line 24: The baseURL fallback in pdf_parser_tcadp.go is using the wrong
environment constant; update the TCADPAPIServer fallback in the parser logic to
read the server URL via common.EnvTCADPApiServerURL instead of
common.EnvTCADPApiKey. Keep the apiKey fallback unchanged, and make sure the
fallback paths in the TCADP parser match the intent shown by
parser.TCADPAPIServer and the existing error message in the TCADP parsing flow.

In `@internal/utility/path.go`:
- Around line 23-36: GetProjectRoot and FindConfFileInProject should preserve
backward compatibility by checking the legacy environment variables as fallbacks
after the new ones. Update the env lookup logic in internal/utility/path.go to
recognize both the current keys (RAG_PROJECT_BASE_URL and RAG_DEPLOY_BASE_URL)
and the old keys (RAG_PROJECT_BASE and RAG_DEPLOY_BASE), using the existing
helpers in common so existing deployments still resolve correctly.

---

Outside diff comments:
In `@internal/service/system.go`:
- Around line 478-485: The ListEnvironments handling in system service is
normalizing some values to lowercase via common.GetEnvSmall, which makes
DB_TYPE, DEVICE, and STORAGE_IMPL inconsistent with internal/admin/service.go
and even inconsistent within the STORAGE_IMPL fallback path. Update the
environment reads in the ListEnvironments logic to use common.GetEnv for these
variables, and keep the default values in the same casing as the returned values
so both service endpoints expose consistent casing.
- Around line 468-474: `ListEnvironments` is lowercasing
`DEFAULT_SUPERUSER_EMAIL` by using `common.GetEnvSmall`, so update the
`defaultSuperuserEmail` lookup in `internal/service/system.go` to use
`common.GetEnv` instead and keep the existing fallback to `[email protected]`;
this preserves the configured casing while keeping the `result` entry and
surrounding `DEFAULT_SUPERUSER_EMAIL` handling unchanged.

---

Nitpick comments:
In `@internal/deepdoc/parser/pdf/tool/config.go`:
- Line 35: `LoadConfig` is still using the raw `"BATCH_COMPARE_CSV"` env key for
`CSVOutput`; update that `envStr` call to use `common.EnvBatchCompareCSV` like
the other `common.Env*` constants in this function. Keep the existing fallback
path logic unchanged and just swap the env name reference in `config.go` so the
config stays consistent.

In `@internal/server/config.go`:
- Around line 555-560: Replace the manual lowercasing in the MinIO config setup
with the existing helper used elsewhere in this file. In the config-loading
logic around the MinIO host and region assignments, use common.GetEnvSmall
instead of strings.ToLower(common.GetEnv(...)) for both values, keeping the same
nil/empty checks and assignments in the surrounding Minio host/region handling.
🪄 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: 451d9f64-f7ec-4da0-8cf2-952273a46473

📥 Commits

Reviewing files that changed from the base of the PR and between 5c8b51c and 2a86a0e.

📒 Files selected for processing (67)
  • cmd/ragflow_server.go
  • internal/admin/service.go
  • internal/agent/audio/model_provider_synthesizer.go
  • internal/agent/canvas/node_body.go
  • internal/agent/canvas/timeout.go
  • internal/agent/component/stagehand_runtime.go
  • internal/agent/component/stagehand_runtime_integration_test.go
  • internal/agent/runtime/selector.go
  • internal/agent/sandbox/aliyun.go
  • internal/agent/sandbox/e2b.go
  • internal/agent/sandbox/e2b_test.go
  • internal/agent/sandbox/local.go
  • internal/agent/sandbox/local_test.go
  • internal/agent/sandbox/manager.go
  • internal/agent/sandbox/self_managed.go
  • internal/agent/sandbox/ssh.go
  • internal/agent/tool/exesql_trino_stub.go
  • internal/agent/tool/keenable.go
  • internal/agent/tool/ssrf.go
  • internal/agent/tool/tavily.go
  • internal/cli/cli.go
  • internal/cli/filesystem/skill_hub/source/interface.go
  • internal/cli/filesystem/skill_install.go
  • internal/common/environments.go
  • internal/deepdoc/client.go
  • internal/deepdoc/parser/pdf/batch_smoke_test.go
  • internal/deepdoc/parser/pdf/compare_test.go
  • internal/deepdoc/parser/pdf/helpers_test.go
  • internal/deepdoc/parser/pdf/ocr_merge_test.go
  • internal/deepdoc/parser/pdf/parser_pipeline_integration_test.go
  • internal/deepdoc/parser/pdf/pipeline_parity_test.go
  • internal/deepdoc/parser/pdf/table_rotate_integration_test.go
  • internal/deepdoc/parser/pdf/text_dump_test.go
  • internal/deepdoc/parser/pdf/tool/compare.go
  • internal/deepdoc/parser/pdf/tool/compare_test.go
  • internal/deepdoc/parser/pdf/tool/config.go
  • internal/engine/elasticsearch/kg_test.go
  • internal/entity/models/builtin.go
  • internal/entity/models/gitee_test.go
  • internal/handler/memory.go
  • internal/harness/core/interrupt.go
  • internal/ingestion/compilation/extractor/ner.go
  • internal/ingestion/component/tokenizer_test.go
  • internal/ingestion/pipeline/real_storage_integration_test.go
  • internal/ingestion/pipeline/template_integration_test.go
  • internal/ingestion/pipeline/test_helpers.go
  • internal/ingestion/task/dataflow_e2e_test.go
  • internal/ingestion/task/dataflow_real_pipeline_integration_test.go
  • internal/parser/parser/pdf_parser_common.go
  • internal/parser/parser/pdf_parser_docling.go
  • internal/parser/parser/pdf_parser_mineru.go
  • internal/parser/parser/pdf_parser_opendataloader.go
  • internal/parser/parser/pdf_parser_paddleocr.go
  • internal/parser/parser/pdf_parser_somark.go
  • internal/parser/parser/pdf_parser_tcadp.go
  • internal/server/config.go
  • internal/service/chat_session.go
  • internal/service/connector.go
  • internal/service/document.go
  • internal/service/file.go
  • internal/service/memory.go
  • internal/service/model_service.go
  • internal/service/system.go
  • internal/service/user.go
  • internal/storage/minio_test.go
  • internal/tokenizer/tokenizer.go
  • internal/utility/path.go
💤 Files with no reviewable changes (1)
  • internal/storage/minio_test.go

Comment thread cmd/ragflow_server.go Outdated
Comment on lines +403 to +419
func startHeartBeat() {
if err := service.AdminServiceClient.InitHTTPClient(); err != nil {
common.Warn("Failed to initialize heartbeat service", zap.Error(err))
} else {
// Start heartbeat reporter with 30 seconds interval
heartbeatReporter := utility.NewScheduledTask("Heartbeat reporter", 3*time.Second, func() {
if err = service.AdminServiceClient.SendHeartbeat(); err == nil {
local.SetAdminStatus(0, "")
} else {
local.SetAdminStatus(1, err.Error())
//logger.Warn(fmt.Sprintf(err.Error()))
}
})
heartbeatReporter.Start()
defer heartbeatReporter.Stop()
}
}

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

Critical: defer heartbeatReporter.Stop() stops the heartbeat immediately when startHeartBeat() returns.

startHeartBeat() is called as a regular function (not a goroutine) at lines 545, 607, and 900. When it returns, all deferred calls execute — so heartbeatReporter.Stop() runs immediately after Start(), killing the reporter before any heartbeat can be sent. In the original inline code, defer was in the caller's scope (e.g., runIngestor), so it executed at process shutdown. This regression means local.SetAdminStatus is never updated, leaving admin status at "not available" (status 1), which will cause downstream auth handlers (internal/handler/auth.go, internal/handler/user.go) to reject requests with http.StatusServiceUnavailable.

🔒 Proposed fix: return a cleanup function for the caller to defer
-func startHeartBeat() {
+func startHeartBeat() func() {
 	if err := service.AdminServiceClient.InitHTTPClient(); err != nil {
 		common.Warn("Failed to initialize heartbeat service", zap.Error(err))
+		return func() {}
 	} else {
 		// Start heartbeat reporter with 30 seconds interval
 		heartbeatReporter := utility.NewScheduledTask("Heartbeat reporter", 3*time.Second, func() {
-			if err = service.AdminServiceClient.SendHeartbeat(); err == nil {
+			if err := service.AdminServiceClient.SendHeartbeat(); err == nil {
 				local.SetAdminStatus(0, "")
 			} else {
 				local.SetAdminStatus(1, err.Error())
 				//logger.Warn(fmt.Sprintf(err.Error()))
 			}
 		})
 		heartbeatReporter.Start()
-		defer heartbeatReporter.Stop()
+		return heartbeatReporter.Stop
 	}
 }

Callers would then use:

-	startHeartBeat()
+	defer startHeartBeat()()
📝 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 startHeartBeat() {
if err := service.AdminServiceClient.InitHTTPClient(); err != nil {
common.Warn("Failed to initialize heartbeat service", zap.Error(err))
} else {
// Start heartbeat reporter with 30 seconds interval
heartbeatReporter := utility.NewScheduledTask("Heartbeat reporter", 3*time.Second, func() {
if err = service.AdminServiceClient.SendHeartbeat(); err == nil {
local.SetAdminStatus(0, "")
} else {
local.SetAdminStatus(1, err.Error())
//logger.Warn(fmt.Sprintf(err.Error()))
}
})
heartbeatReporter.Start()
defer heartbeatReporter.Stop()
}
}
func startHeartBeat() func() {
if err := service.AdminServiceClient.InitHTTPClient(); err != nil {
common.Warn("Failed to initialize heartbeat service", zap.Error(err))
return func() {}
} else {
// Start heartbeat reporter with 30 seconds interval
heartbeatReporter := utility.NewScheduledTask("Heartbeat reporter", 3*time.Second, func() {
if err := service.AdminServiceClient.SendHeartbeat(); err == nil {
local.SetAdminStatus(0, "")
} else {
local.SetAdminStatus(1, err.Error())
//logger.Warn(fmt.Sprintf(err.Error()))
}
})
heartbeatReporter.Start()
return heartbeatReporter.Stop
}
}
🤖 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 403 - 419, The heartbeat reporter is
being stopped too early because `startHeartBeat()` defers
`heartbeatReporter.Stop()` inside a regular function, so the cleanup runs as
soon as the function returns. Update `startHeartBeat` to return a cleanup/stop
function (or move the defer back to each caller such as the `runIngestor`-style
call sites) so `heartbeatReporter.Start()` remains active for the process
lifetime and `local.SetAdminStatus` can be updated by `SendHeartbeat`.

Comment thread internal/common/environments.go Resolved
Comment thread internal/common/environments.go Outdated
EnvSSHHost = "SSH_HOST"
EnvSSHPort = "SSH_PORT"
EnvSSHUsername = "SSH_USERNAME"
EnvSSPassword = "SSH_PASSWORD"

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for any references to the typo'd constant name across the PR branch
rg -n 'EnvSSPassword' --type=go

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the relevant file and nearby constant names
FILE="internal/common/environments.go"

printf '\n== File outline ==\n'
ast-grep outline "$FILE" --view expanded || true

printf '\n== Relevant lines ==\n'
sed -n '1,180p' "$FILE" | cat -n

printf '\n== Search for SSH-related env constants ==\n'
rg -n 'EnvSSH|EnvSSPassword|SSH_PASSWORD' internal/common -g '*.go'

Repository: infiniflow/ragflow

Length of output: 23028


Rename EnvSSPassword to EnvSSHPassword for consistency with the other SSH constants.

🧰 Tools
🪛 ast-grep (0.44.1)

[warning] 95-95: 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: EnvSSHPrivateKey = "SSH_PRIVATE_KEY"
Note: [CWE-798] Use of Hard-coded Credentials.

(hardcoded-credentials-string-literal-go)

🤖 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 95, Rename the SSH password
environment constant to match the other SSH symbols: update EnvSSPassword to
EnvSSHPassword in the environments constants so it is consistent with the
related SSH identifiers. Also update any references to this constant throughout
the codebase to use the new name and keep the same value.

Comment thread internal/deepdoc/client.go Resolved
Comment thread internal/utility/path.go
Comment on lines +23 to +36
"ragflow/internal/common"
"runtime"
)

// GetProjectRoot returns the project root directory
func GetProjectRoot() string {
// Try environment variable first
if confDir := os.Getenv("RAGFLOW_CONF_DIR"); confDir != "" {
if confDir := common.GetEnv(common.EnvRAGFlowConfDir); confDir != "" {
return confDir
}
if d := os.Getenv("RAG_PROJECT_BASE"); d != "" {
if d := common.GetEnv(common.EnvRAGProjectBaseURL); d != "" {
return d
}
if d := os.Getenv("RAG_DEPLOY_BASE"); d != "" {
if d := common.GetEnv(common.EnvRAGDeployBaseURL); d != "" {

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
# Check git history for the old env var names in path.go
git log --all -p -- internal/utility/path.go | rg -n 'os\.Getenv\(' | head -20

Repository: infiniflow/ragflow

Length of output: 956


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '## path.go\n'
sed -n '1,140p' internal/utility/path.go

printf '\n## env consts\n'
rg -n 'EnvRAG(Project|Deploy)Base(URL)?|RAG_PROJECT_BASE|RAG_DEPLOY_BASE|RAGFLOW_CONF_DIR' internal -S

Repository: infiniflow/ragflow

Length of output: 4275


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '1,240p' internal/common/environments.go

printf '\n## GetEnv usages\n'
rg -n 'func GetEnv|GetEnv\(' internal/common internal -S

Repository: infiniflow/ragflow

Length of output: 29471


Keep the legacy env vars as fallbacks

GetProjectRoot and FindConfFileInProject now read only RAG_PROJECT_BASE_URL / RAG_DEPLOY_BASE_URL. Existing deployments that still set RAG_PROJECT_BASE / RAG_DEPLOY_BASE will stop being recognized and may fall back to filesystem guessing. Add backward-compatible checks for the old keys too.

🧰 Tools
🪛 golangci-lint (2.12.2)

[error] 32-32: : # ragflow/internal/deepdoc [ragflow/internal/deepdoc.test]
internal/deepdoc/client.go:32:2: "os" imported and not used

(typecheck)

🤖 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/utility/path.go` around lines 23 - 36, GetProjectRoot and
FindConfFileInProject should preserve backward compatibility by checking the
legacy environment variables as fallbacks after the new ones. Update the env
lookup logic in internal/utility/path.go to recognize both the current keys
(RAG_PROJECT_BASE_URL and RAG_DEPLOY_BASE_URL) and the old keys
(RAG_PROJECT_BASE and RAG_DEPLOY_BASE), using the existing helpers in common so
existing deployments still resolve correctly.

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.

🧹 Nitpick comments (1)
internal/ingestion/compilation/extractor/ner.go (1)

312-312: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Avoid mutating the function parameter text.

Changing text := to text = avoids shadowing but now mutates the ExtractEntities parameter. This is safe today since text isn't referenced after the loop, but future code added after the loop would silently receive stale entity text instead of the original input. Use a distinct local variable instead.

♻️ Proposed refactor
-		text = re.Text
-		if isCJK {
-			text = strings.ReplaceAll(text, " ", "")
-		}
-		key := strings.ToLower(text) + "|" + strconv.Itoa(re.Start)
+		entityText := re.Text
+		if isCJK {
+			entityText = strings.ReplaceAll(entityText, " ", "")
+		}
+		key := strings.ToLower(entityText) + "|" + strconv.Itoa(re.Start)

And update the Entity literal at line 326 to use entityText:

-		entities = append(entities, Entity{
-			Text:       text,
+		entities = append(entities, Entity{
+			Text:       entityText,
🤖 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/ingestion/compilation/extractor/ner.go` at line 312, Avoid
reassigning the ExtractEntities input parameter text inside the entity loop; use
a separate local variable such as entityText in ner.go. Update the assignment
from re.Text to that new variable, and make sure the Entity literal uses
entityText instead of text so the original input remains unchanged for any later
code in ExtractEntities.
🤖 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.

Nitpick comments:
In `@internal/ingestion/compilation/extractor/ner.go`:
- Line 312: Avoid reassigning the ExtractEntities input parameter text inside
the entity loop; use a separate local variable such as entityText in ner.go.
Update the assignment from re.Text to that new variable, and make sure the
Entity literal uses entityText instead of text so the original input remains
unchanged for any later code in ExtractEntities.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f8a287cc-a66d-40e9-b1c0-b281f4862d37

📥 Commits

Reviewing files that changed from the base of the PR and between 2a86a0e and 922c94c.

📒 Files selected for processing (2)
  • internal/common/environments.go
  • internal/ingestion/compilation/extractor/ner.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/common/environments.go

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

Caution

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

⚠️ Outside diff range comments (1)
internal/parser/parser/pdf_parser_tcadp.go (1)

24-31: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Past critical issue fixed; error message on line 27 still references old env var name.

The baseURL fallback (line 24) now correctly uses common.EnvTCADPApiServerURL and the apiKey fallback (line 31) correctly uses common.EnvTCADPApiKey, resolving the previously flagged copy-paste error. However, the error message on line 27 still references TCADP_APISERVER (the old env var name) instead of TCADP_APISERVER_URL (the new name after migration to common.EnvTCADPApiServerURL). Users debugging missing configuration will be misled by the stale name.

💚 Proposed fix for stale env var name in error message
 		return ParseResult{Err: fmt.Errorf("parser: TCADP requires tcadp_apiserver or TCADP_APISERVER")}
+		return ParseResult{Err: fmt.Errorf("parser: TCADP requires tcadp_apiserver or TCADP_APISERVER_URL")}
🤖 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/parser/parser/pdf_parser_tcadp.go` around lines 24 - 31, Update the
missing-configuration error returned by the TCADP parser in the relevant parse
function to reference the current environment variable name, replacing
“TCADP_APISERVER” with “TCADP_APISERVER_URL” while retaining the existing parser
option name.
🤖 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.

Outside diff comments:
In `@internal/parser/parser/pdf_parser_tcadp.go`:
- Around line 24-31: Update the missing-configuration error returned by the
TCADP parser in the relevant parse function to reference the current environment
variable name, replacing “TCADP_APISERVER” with “TCADP_APISERVER_URL” while
retaining the existing parser option name.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 69e0b0ea-6ec0-41f5-aa0e-397e29b1f093

📥 Commits

Reviewing files that changed from the base of the PR and between e95fd27 and 3142b25.

📒 Files selected for processing (6)
  • internal/agent/sandbox/ssh.go
  • internal/common/environments.go
  • internal/deepdoc/parser/pdf/tool/config.go
  • internal/parser/parser/pdf_parser_mineru.go
  • internal/parser/parser/pdf_parser_opendataloader.go
  • internal/parser/parser/pdf_parser_tcadp.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/agent/sandbox/ssh.go
  • internal/deepdoc/parser/pdf/tool/config.go
  • internal/parser/parser/pdf_parser_mineru.go
  • internal/parser/parser/pdf_parser_opendataloader.go

Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN
JinHai-CN merged commit add7b94 into infiniflow:main Jul 10, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code 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