Skip to content

fix: add configurable HTTP timeout for LLM API calls - #238

Merged
lizhengfeng101 merged 3 commits into
alibaba:mainfrom
zy84338719:fix/llm-http-timeout
Jun 30, 2026
Merged

lizhengfeng101 merged 3 commits into
alibaba:mainfrom
zy84338719:fix/llm-http-timeout

Conversation

@zy84338719

Copy link
Copy Markdown
Contributor

Problem

The LLM HTTP client has no user-configurable request timeout. When the LLM API becomes unresponsive (rate limiting, network issues, server overload), the ocr scan process hangs indefinitely with 0% CPU, holding an ESTABLISHED TCP connection that never completes.

Reproduction: Run ocr scan against an LLM API that occasionally hangs. The process blocks forever until manually killed.

Root cause in internal/llm/client.go:195: NewLLMClient creates ClientConfig without setting Timeout (defaults to 0). While NewOpenAIClient/NewAnthropicClient have a 5-minute fallback, there is no way for users to configure this.

Fixes #237

Changes

  • Add Timeout field to ResolvedEndpoint struct
  • Add OCR_LLM_TIMEOUT environment variable (value in seconds)
  • Add timeout_sec field to config.json llm and provider sections
  • Pass timeout from ResolvedEndpoint to ClientConfig in NewLLMClient

Usage

# Environment variable
export OCR_LLM_TIMEOUT=120  # 2 minutes per LLM call

# Or in ~/.opencodereview/config.json
{
  "llm": {
    "url": "https://api.example.com/v1",
    "timeout_sec": 120
  }
}

The default remains 5 minutes when not explicitly configured. All existing behavior is preserved.

The LLM HTTP client had no user-configurable request timeout. When the
LLM API becomes unresponsive (e.g., rate limiting, network issues), the
ocr process hangs indefinitely with 0% CPU, holding an ESTABLISHED TCP
connection that never completes.

Changes:
- Add Timeout field to ResolvedEndpoint struct
- Add OCR_LLM_TIMEOUT environment variable (value in seconds)
- Add timeout_sec field to config.json llm and provider sections
- Pass timeout from ResolvedEndpoint to ClientConfig in NewLLMClient

The default timeout remains 5 minutes when not explicitly configured.
Users can now set a shorter timeout via:
  - Environment: OCR_LLM_TIMEOUT=120
  - Config file: {"llm": {"timeout_sec": 120}}

Fixes alibaba#237
Copilot AI review requested due to automatic review settings June 28, 2026 08:49
@github-actions

Copy link
Copy Markdown
Contributor

✅ OpenCodeReview: No comments generated. Looks good to me.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Adds user-configurable HTTP request timeouts for LLM API calls by extending endpoint resolution/config parsing and wiring the resolved timeout into the LLM client factory, aiming to prevent ocr scan from hanging indefinitely on stalled LLM requests.

Changes:

  • Introduce ResolvedEndpoint.Timeout (time.Duration) and parse timeout from env/config (OCR_LLM_TIMEOUT, timeout_sec).
  • Support timeout_sec in both legacy llm config and provider entries.
  • Propagate the resolved timeout into ClientConfig via NewLLMClient.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 6 comments.

File Description
internal/llm/resolver.go Adds timeout fields and parsing from environment/config into ResolvedEndpoint.
internal/llm/client.go Wires ResolvedEndpoint.Timeout into ClientConfig.Timeout so downstream clients can apply it.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread internal/llm/resolver.go Outdated
Comment on lines +129 to +134
var timeout time.Duration
if timeoutStr := os.Getenv(envOCRLLMTimeout); timeoutStr != "" {
timeoutSec, err := strconv.Atoi(strings.TrimSpace(timeoutStr))
if err != nil {
return ResolvedEndpoint{}, false, fmt.Errorf("OCR_LLM_TIMEOUT must be an integer (seconds): %w", err)
}
Comment thread internal/llm/resolver.go Outdated
Comment on lines +129 to +138
var timeout time.Duration
if timeoutStr := os.Getenv(envOCRLLMTimeout); timeoutStr != "" {
timeoutSec, err := strconv.Atoi(strings.TrimSpace(timeoutStr))
if err != nil {
return ResolvedEndpoint{}, false, fmt.Errorf("OCR_LLM_TIMEOUT must be an integer (seconds): %w", err)
}
if timeoutSec > 0 {
timeout = time.Duration(timeoutSec) * time.Second
}
}
Comment thread internal/llm/resolver.go Outdated
Comment on lines +308 to +312
var timeout time.Duration
if entry.TimeoutSec > 0 {
timeout = time.Duration(entry.TimeoutSec) * time.Second
}

Comment thread internal/llm/resolver.go Outdated
Comment on lines +362 to +365
var timeout time.Duration
if cfg.Llm.TimeoutSec > 0 {
timeout = time.Duration(cfg.Llm.TimeoutSec) * time.Second
}
Comment thread internal/llm/resolver.go
Comment on lines +150 to 153
TimeoutSec int `json:"timeout_sec,omitempty"` // per-request HTTP timeout in seconds
ExtraBody map[string]any `json:"extra_body,omitempty"`
ExtraHeaders map[string]string `json:"extra_headers,omitempty"`
}
Comment thread internal/llm/client.go
Comment on lines 196 to 204
cfg := ClientConfig{
URL: ep.URL,
APIKey: ep.Token,
Model: ep.Model,
AuthHeader: ep.AuthHeader,
Timeout: ep.Timeout,
ExtraBody: ep.ExtraBody,
ExtraHeaders: ep.ExtraHeaders,
}
- Make OCR_LLM_TIMEOUT a global override (works with any endpoint strategy)
- Add proper overflow detection for timeout values (check before multiply)
- Add validateTimeoutSec helper with negative/overflow guards
- Add comprehensive tests for timeout parsing, validation, and forwarding
- Reject negative timeout_sec in config files with explicit error

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

Review Summary

Clean, well-structured PR. The global override design in ResolveEndpointWithModelOverride is the right call — it ensures OCR_LLM_TIMEOUT works regardless of which resolution strategy fires. Overflow guards and boundary validation are solid.

A few items worth addressing before merge — see inline comments.

Missing test coverage

  1. No test for provider config timeout_sec: tryProviderConfig gained timeout parsing at line 344–348, but there's no corresponding test. The legacy llm path is covered by TestResolveEndpoint_ConfigTimeoutSec; the provider path should have parity.

  2. No test for env-over-config precedence: TestResolveEndpoint_EnvTimeoutGlobalOverride tests env timeout with OCR env vars (which carry no config timeout). There's no test proving that OCR_LLM_TIMEOUT overrides a timeout_sec already set in the config file — that's the key precedence guarantee.

Comment thread internal/llm/resolver.go Outdated
// parseTimeoutEnv reads and validates the OCR_LLM_TIMEOUT environment variable.
// Returns the parsed duration and true if set, or 0 and false if unset/empty.
// Rejects negative values and values that would overflow time.Duration.
func parseTimeoutEnv() (time.Duration, bool) {

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.

Suggestion: avoid silently swallowing invalid values.

parseTimeoutEnv returns (0, false) for invalid input ("abc", "-5"), falling back to the default with no signal to the user. Meanwhile, validateTimeoutSec returns an explicit error for the same invalid inputs in config files.

This inconsistency can be confusing: a user sets OCR_LLM_TIMEOUT=-5, expects it to take effect, and has no way to know it was silently ignored.

Consider one of:

  • Return an error and surface it in ResolveEndpointWithModelOverride (consistent with config-file behavior)
  • Log a warning so the user gets feedback
  • At minimum, document the silent-fallback behavior

Comment thread internal/llm/resolver.go Outdated
if int64(sec) > maxSec {
return 0, false
}
return time.Duration(sec) * time.Second, true

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.

Suggestion: reuse validateTimeoutSec to reduce duplication.

The overflow guard (lines 107–111) and the negative check (lines 104–106) duplicate the same logic in validateTimeoutSec. Consider:

func parseTimeoutEnv() (time.Duration, bool) {
	raw := strings.TrimSpace(os.Getenv(envOCRLLMTimeout))
	if raw == "" {
		return 0, false
	}
	sec, err := strconv.Atoi(raw)
	if err != nil {
		return 0, false
	}
	d, err := validateTimeoutSec(sec)
	if err != nil {
		return 0, false
	}
	return d, true
}

This keeps one source of truth for validation rules and avoids the two functions drifting apart over time.

Note: validateTimeoutSec(0) returns (0, nil), so OCR_LLM_TIMEOUT=0 would still produce (0, true) — preserving current behavior.

Comment thread internal/llm/resolver.go Outdated
}

// Note: OCR_LLM_TIMEOUT is applied globally in ResolveEndpointWithModelOverride,
// not here, so it works regardless of which strategy resolves the endpoint.

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.

Nit: this comment restates what is already clear from reading ResolveEndpointWithModelOverride (lines 79–84). The comment at the override site itself (line 79–81) is the useful one; this one could be dropped to reduce noise.

@CLAassistant

CLAassistant commented Jun 29, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@zy84338719
zy84338719 force-pushed the fix/llm-http-timeout branch 2 times, most recently from f7bdf34 to ff333f3 Compare June 29, 2026 11:07
- parseTimeoutEnv now returns errors instead of silent fallback for invalid values (negative, non-integer, overflow)
- Reuse validateTimeoutSec in parseTimeoutEnv to eliminate duplicated validation logic
- Remove redundant comment in tryOCREnv
- Add missing tests:
  - TestResolveEndpoint_ProviderConfigTimeoutSec
  - TestResolveEndpoint_ProviderConfigNegativeTimeoutSec
  - TestResolveEndpoint_EnvTimeoutOverridesConfigTimeout
  - TestResolveEndpoint_EnvTimeoutOverridesProviderTimeout
  - TestResolveEndpoint_InvalidEnvTimeoutWithConfig
  - TestResolveEndpoint_NegativeEnvTimeoutWithConfig
@zy84338719
zy84338719 force-pushed the fix/llm-http-timeout branch from ff333f3 to b51b904 Compare June 29, 2026 11:08
@lizhengfeng101
lizhengfeng101 merged commit eae8635 into alibaba:main Jun 30, 2026
1 check passed
Githab-capibara added a commit to Githab-capibara/open-code-review that referenced this pull request Sep 17, 2026
* fix: add configurable HTTP timeout for LLM API calls

The LLM HTTP client had no user-configurable request timeout. When the
LLM API becomes unresponsive (e.g., rate limiting, network issues), the
ocr process hangs indefinitely with 0% CPU, holding an ESTABLISHED TCP
connection that never completes.

Changes:
- Add Timeout field to ResolvedEndpoint struct
- Add OCR_LLM_TIMEOUT environment variable (value in seconds)
- Add timeout_sec field to config.json llm and provider sections
- Pass timeout from ResolvedEndpoint to ClientConfig in NewLLMClient

The default timeout remains 5 minutes when not explicitly configured.
Users can now set a shorter timeout via:
  - Environment: OCR_LLM_TIMEOUT=120
  - Config file: {"llm": {"timeout_sec": 120}}

Fixes alibaba#237

* fix: address Copilot review feedback

- Make OCR_LLM_TIMEOUT a global override (works with any endpoint strategy)
- Add proper overflow detection for timeout values (check before multiply)
- Add validateTimeoutSec helper with negative/overflow guards
- Add comprehensive tests for timeout parsing, validation, and forwarding
- Reject negative timeout_sec in config files with explicit error

* fix: address review feedback for timeout configuration

- parseTimeoutEnv now returns errors instead of silent fallback for invalid values (negative, non-integer, overflow)
- Reuse validateTimeoutSec in parseTimeoutEnv to eliminate duplicated validation logic
- Remove redundant comment in tryOCREnv
- Add missing tests:
  - TestResolveEndpoint_ProviderConfigTimeoutSec
  - TestResolveEndpoint_ProviderConfigNegativeTimeoutSec
  - TestResolveEndpoint_EnvTimeoutOverridesConfigTimeout
  - TestResolveEndpoint_EnvTimeoutOverridesProviderTimeout
  - TestResolveEndpoint_InvalidEnvTimeoutWithConfig
  - TestResolveEndpoint_NegativeEnvTimeoutWithConfig
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: LLM HTTP client has no configurable request timeout, causing scan to hang indefinitely

5 participants