Skip to content

Go: implement system healthz API - #15307

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
tmimmanuel:go/system-healthz-api
May 28, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
tmimmanuel:go/system-healthz-api

Conversation

@tmimmanuel

Copy link
Copy Markdown
Contributor

Summary

  • Add Go REST support for GET /api/v1/system/healthz.
  • Return Python-compatible ok/nok dependency fields for DB, Redis, document engine, and storage.
  • Return HTTP 200 only when all checks pass; otherwise return HTTP 500 with _meta failure details.
  • Add focused service coverage for the unhealthy dependency response when Go dependencies are not initialized.

Scope

This is a small, isolated slice of #15240. It avoids current open connector PRs (#15274, #15300, #15265, #15264), tenant/member PRs (#15295, #15301, #15276), MCP PRs (#15281, #15253, #15254, #15260, #15261, #15262), and the memory-message PR (#15256).

Refs #15240

Tests

go test -vet=off ./internal/service -run TestSystemServiceHealthzReportsUnhealthyDependencies -count=1
go test -vet=off -run '^$' ./internal/service ./internal/router\ngo build ./internal/handler ./internal/service ./internal/router\ngit diff --check\n```\n\nNote: I did not use `go test ./internal/handler` because the current upstream snapshot has an unrelated `internal/handler/connector_test.go` compile error referencing `service.UpdateConnectorRequest`; production handler code is covered by `go build` above.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 27, 2026
@coderabbitai

coderabbitai Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR implements a system health check endpoint that reports the status of core dependencies. A new /api/v1/system/healthz endpoint is added, backed by service-level checks for database, Redis cache, document engine, and storage, with response codes reflecting overall health.

Changes

Health Check System

Layer / File(s) Summary
Service health check contract and helpers
internal/service/system.go
Imports are updated to support the health check logic. HealthzMeta type defines per-dependency metadata structure. okNok and timedHealthCheck utility functions convert boolean status to "ok"/"nok" strings and measure check execution time with optional error capture.
Service health check implementation and validation
internal/service/system.go, internal/service/system_test.go
SystemService.Healthz(ctx) sequentially checks database (via PingContext), Redis (via client health), document engine (via Ping), and storage (via Health). Per-dependency statuses are aggregated into HealthzResponse, error metadata is populated for failed checks, and overall allOK boolean is computed. Test validates that unhealthy uninitialized dependencies report "nok" status with non-empty failure metadata.
HTTP handler and route registration
internal/handler/system.go, internal/router/router.go
SystemHandler.Healthz handler calls the service method and returns HTTP 200 for healthy or 500 for unhealthy states. Unprotected GET route /api/v1/system/healthz is registered under apiNoAuth group.

Sequence Diagram

sequenceDiagram
  participant Client
  participant Healthz as Healthz Method
  participant DB as Database
  participant Redis as Redis Cache
  participant DocEngine as Document Engine
  participant Storage as Storage
  
  Client->>Healthz: Healthz(ctx)
  Healthz->>DB: PingContext
  DB-->>Healthz: ok/error
  Healthz->>Redis: Health Check
  Redis-->>Healthz: ok/error
  Healthz->>DocEngine: Ping
  DocEngine-->>Healthz: ok/error
  Healthz->>Storage: Health
  Storage-->>Healthz: ok/error
  Healthz-->>Client: HealthzResponse, allOK
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

size:M

Suggested reviewers

  • Haruko386

Poem

🐰 A health check hops in with timely grace,
Four dependencies checked at steady pace,
DB, Redis, Engine, Storage too—
All singing "ok" in Python's hue! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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
Title check ✅ Passed The title clearly and specifically describes the main change: implementing a system healthz API endpoint in Go.
Description check ✅ Passed The description covers the problem being solved and includes detailed implementation scope, but does not explicitly mark the type of change despite the template requiring it.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

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

🧹 Nitpick comments (1)
internal/service/system_test.go (1)

16-18: ⚡ Quick win

Strengthen _meta contract assertions per dependency.

Current check only verifies _meta is non-empty. It’s safer to assert keys for db, redis, doc_engine, and storage so regressions in failure-detail coverage are caught.

✅ Suggested test hardening
-	if len(result.Meta) == 0 {
-		t.Fatal("expected failure metadata")
-	}
+	for _, k := range []string{"db", "redis", "doc_engine", "storage"} {
+		if _, ok := result.Meta[k]; !ok {
+			t.Fatalf("expected failure metadata for %s, got: %+v", k, result.Meta)
+		}
+	}
🤖 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_test.go` around lines 16 - 18, The test currently
only checks that result.Meta is non-empty; update the assertion in
internal/service/system_test.go to verify that result.Meta contains the specific
keys "db", "redis", "doc_engine", and "storage". Locate the test using
result.Meta and replace the generic len(result.Meta) == 0 check with explicit
existence checks (e.g., lookup or map key assertions) for each of those keys so
the test fails if any dependency metadata is missing. Ensure the assertions fail
with clear messages referencing the missing key names.
🤖 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 `@internal/service/system.go`:
- Around line 98-100: The healthz response currently assigns raw err.Error()
into meta.Error which can leak internals; instead set meta.Error to a generic
sanitized message (e.g., "internal error" or "unavailable") before returning
from the healthz handler, and log the original err on the server side (use the
existing logger in this package) for diagnostics; replace the direct meta.Error
= err.Error() assignment (and return) with a sanitized message plus a
server-side log that includes err so callers of /api/v1/system/healthz do not
receive internal details.

---

Nitpick comments:
In `@internal/service/system_test.go`:
- Around line 16-18: The test currently only checks that result.Meta is
non-empty; update the assertion in internal/service/system_test.go to verify
that result.Meta contains the specific keys "db", "redis", "doc_engine", and
"storage". Locate the test using result.Meta and replace the generic
len(result.Meta) == 0 check with explicit existence checks (e.g., lookup or map
key assertions) for each of those keys so the test fails if any dependency
metadata is missing. Ensure the assertions fail with clear messages referencing
the missing key names.
🪄 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: 62deba2e-e2fe-412a-a113-c0c94cb5e2f1

📥 Commits

Reviewing files that changed from the base of the PR and between 0071e98 and 0e562c9.

📒 Files selected for processing (4)
  • internal/handler/system.go
  • internal/router/router.go
  • internal/service/system.go
  • internal/service/system_test.go

Comment on lines +98 to +100
if err != nil {
meta.Error = err.Error()
return false, meta

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Sanitize _meta.error before returning it from the public healthz endpoint.

Line 99 forwards raw err.Error() into the response. Since /api/v1/system/healthz is unauthenticated (internal/router/router.go, Line 103), this can leak internal infra details.

🔧 Proposed fix
 func timedHealthCheck(check func() error) (bool, HealthzMeta) {
 	start := time.Now()
 	err := check()
 	meta := HealthzMeta{
 		Elapsed: fmt.Sprintf("%.1f", float64(time.Since(start).Microseconds())/1000.0),
 	}
 	if err != nil {
-		meta.Error = err.Error()
+		// Avoid leaking backend internals on public health endpoint.
+		meta.Error = "dependency check failed"
 		return false, meta
 	}
 	return true, meta
 }
🤖 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 98 - 100, The healthz response
currently assigns raw err.Error() into meta.Error which can leak internals;
instead set meta.Error to a generic sanitized message (e.g., "internal error" or
"unavailable") before returning from the healthz handler, and log the original
err on the server side (use the existing logger in this package) for
diagnostics; replace the direct meta.Error = err.Error() assignment (and return)
with a sanitized message plus a server-side log that includes err so callers of
/api/v1/system/healthz do not receive internal details.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@tmimmanuel LGTM
Thank you for you contribution

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label May 28, 2026
@Haruko386 Haruko386 added the ci Continue Integration label May 28, 2026
@Haruko386
Haruko386 marked this pull request as draft May 28, 2026 02:44
@Haruko386
Haruko386 marked this pull request as ready for review May 28, 2026 02:44
@codecov

codecov Bot commented May 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (43cbfd4) to head (0e562c9).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15307   +/-   ##
=======================================
  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 Sentry.
📢 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 085241b into infiniflow:main May 28, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants