Repository navigation
fix: add configurable HTTP timeout for LLM API calls - #238
Conversation
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
|
✅ OpenCodeReview: No comments generated. Looks good to me. |
There was a problem hiding this comment.
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_secin both legacyllmconfig and provider entries. - Propagate the resolved timeout into
ClientConfigviaNewLLMClient.
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.
| 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) | ||
| } |
| 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 | ||
| } | ||
| } |
| var timeout time.Duration | ||
| if entry.TimeoutSec > 0 { | ||
| timeout = time.Duration(entry.TimeoutSec) * time.Second | ||
| } | ||
|
|
| var timeout time.Duration | ||
| if cfg.Llm.TimeoutSec > 0 { | ||
| timeout = time.Duration(cfg.Llm.TimeoutSec) * time.Second | ||
| } |
| 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"` | ||
| } |
| 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
left a comment
There was a problem hiding this comment.
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
-
No test for provider config
timeout_sec:tryProviderConfiggained timeout parsing at line 344–348, but there's no corresponding test. The legacyllmpath is covered byTestResolveEndpoint_ConfigTimeoutSec; the provider path should have parity. -
No test for env-over-config precedence:
TestResolveEndpoint_EnvTimeoutGlobalOverridetests env timeout with OCR env vars (which carry no config timeout). There's no test proving thatOCR_LLM_TIMEOUToverrides atimeout_secalready set in the config file — that's the key precedence guarantee.
| // 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) { |
There was a problem hiding this comment.
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
errorand surface it inResolveEndpointWithModelOverride(consistent with config-file behavior) - Log a warning so the user gets feedback
- At minimum, document the silent-fallback behavior
| if int64(sec) > maxSec { | ||
| return 0, false | ||
| } | ||
| return time.Duration(sec) * time.Second, true |
There was a problem hiding this comment.
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.
| } | ||
|
|
||
| // Note: OCR_LLM_TIMEOUT is applied globally in ResolveEndpointWithModelOverride, | ||
| // not here, so it works regardless of which strategy resolves the endpoint. |
There was a problem hiding this comment.
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.
f7bdf34 to
ff333f3
Compare
- 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
ff333f3 to
b51b904
Compare
* 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
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 scanprocess hangs indefinitely with 0% CPU, holding an ESTABLISHED TCP connection that never completes.Reproduction: Run
ocr scanagainst an LLM API that occasionally hangs. The process blocks forever until manually killed.Root cause in
internal/llm/client.go:195:NewLLMClientcreatesClientConfigwithout settingTimeout(defaults to 0). WhileNewOpenAIClient/NewAnthropicClienthave a 5-minute fallback, there is no way for users to configure this.Fixes #237
Changes
Timeoutfield toResolvedEndpointstructOCR_LLM_TIMEOUTenvironment variable (value in seconds)timeout_secfield toconfig.jsonllm and provider sectionsResolvedEndpointtoClientConfiginNewLLMClientUsage
The default remains 5 minutes when not explicitly configured. All existing behavior is preserved.