Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6364: make the LLM client retry budget explicit, wired, and validated (#7201)

Bohan Jiang24d8c521a68a
diff --git a/.env.example b/.env.example
index 4e435d93c6..9935e72d3c 100644
--- a/.env.example
+++ b/.env.example
@@ -115,6 +115,20 @@ MULTICA_LLM_BASE_URL=
# - Default model used when a request omits `model`. When unset, falls
# back to a small built-in default (gpt-5.6-luna).
MULTICA_LLM_DEFAULT_MODEL=
+# - Transport retry budget for every upstream LLM request. This is the one
+# canonical source; the server logs the effective policy at startup
+# ("llm retry policy").
+# unset use the built-in default of 2 retries
+# 0 disable retries — exactly one request per call
+# 1..5 at most N retries, so at most N+1 requests per call
+# Anything else (negative, non-numeric, above 5) fails the boot rather than
+# being corrected silently. The ceiling is a latency budget: backoff starts
+# at 0.5s and doubles to an 8s cap, so 6 retries would sleep ~21s while the
+# internal callers of this layer time out after 8s and 20s.
+# Retried: connection failures, HTTP 408/409/429 and 5xx. Not retried: every
+# other 4xx. This budget does not cover a stream that breaks mid-response,
+# and it is unrelated to task-level retries.
+MULTICA_LLM_MAX_RETRIES=
MULTICA_DAEMON_CONFIG=
MULTICA_WORKSPACE_ID=
MULTICA_DAEMON_ID=
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index a5105eef17..5fc0c1e674 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -186,6 +186,9 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s
| `MULTICA_LLM_API_KEY` | 空 | OpenAI 互換の API key |
| `MULTICA_LLM_BASE_URL` | 空 | OpenAI 互換の endpoint |
| `MULTICA_LLM_DEFAULT_MODEL` | `gpt-5.6-luna` | リクエストがモデルを指定しない場合に使用 |
+| `MULTICA_LLM_MAX_RETRIES` | `2` | 1 回の呼び出しあたりのリトライ上限。`0` はリトライ無効、`1`〜`5` は最大 N 回 |
+
+`MULTICA_LLM_MAX_RETRIES` はリトライポリシーの唯一の設定元です。未設定ならデフォルトの 2 回、`0` なら 1 回の呼び出しにつきリクエストは 1 回だけ、1〜5 ならリトライは最大その回数までになります。これは割り当てではなく上限です。消費するのはリトライ対象の失敗だけで、成功や呼び出し側自身のデッドラインによって早く終わることもあります。それ以外の値(負数、非数値、5 超過)は静かに補正されるのではなく起動に失敗します。上限はレイテンシ予算です。バックオフは 0.5 秒から始まり 8 秒を上限に倍増するため、これより大きい予算は呼び出し側自身のタイムアウトを超え、リトライ可能な失敗をタイムアウトに変えてしまいます。リトライの対象は接続失敗と HTTP 408、409、429、5xx で、それ以外の 4xx はそのまま返されます。サーバーは起動時に有効なポリシーを `llm retry policy` として記録しますが、その行に資格情報は含まれません。
このレイヤーを使う機能は 2 つあり、どちらも設定した endpoint にチャットの内容を送信します。
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 4ccd48fff6..643c9dd2b5 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -186,6 +186,9 @@ reverse proxy 뒤에 배포한다면 실제 proxy 네트워크를 입력해야
| `MULTICA_LLM_API_KEY` | 비어 있음 | OpenAI 호환 API key |
| `MULTICA_LLM_BASE_URL` | 비어 있음 | OpenAI 호환 endpoint |
| `MULTICA_LLM_DEFAULT_MODEL` | `gpt-5.6-luna` | 요청에 모델이 지정되지 않았을 때 사용 |
+| `MULTICA_LLM_MAX_RETRIES` | `2` | 호출당 재시도 상한. `0`은 재시도 비활성화, `1`–`5`는 최대 N회 |
+
+`MULTICA_LLM_MAX_RETRIES`는 재시도 정책의 유일한 설정 소스입니다. 설정하지 않으면 기본값 2회, `0`이면 호출당 요청을 정확히 한 번만 보내고, 1–5면 재시도를 최대 그 횟수까지만 합니다. 할당량이 아니라 상한입니다. 재시도 대상 실패만 이를 소모하며, 성공하거나 호출자 자신의 데드라인에 걸리면 더 일찍 끝납니다. 그 밖의 값(음수, 숫자가 아닌 값, 5 초과)은 조용히 보정되지 않고 시작에 실패합니다. 상한은 지연 예산입니다. 백오프는 0.5초에서 시작해 8초 상한까지 두 배씩 늘어나므로, 더 큰 예산은 호출자 자신의 타임아웃을 넘겨 재시도 가능한 실패를 타임아웃으로 바꿉니다. 재시도는 연결 실패와 HTTP 408, 409, 429, 5xx를 대상으로 하며 그 외 4xx는 그대로 반환됩니다. 서버는 시작 시 유효한 정책을 `llm retry policy`로 기록하며 해당 줄에는 자격 증명이 포함되지 않습니다.
이 레이어를 사용하는 기능은 두 가지이며, 둘 다 설정한 endpoint로 채팅 내용을 전송합니다.
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 19b9a3bf97..ea502d30be 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -186,6 +186,9 @@ This group configures server-side assist generation, such as conversation titles
| `MULTICA_LLM_API_KEY` | empty | OpenAI-compatible API key |
| `MULTICA_LLM_BASE_URL` | empty | OpenAI-compatible endpoint |
| `MULTICA_LLM_DEFAULT_MODEL` | `gpt-5.6-luna` | Used when a request does not specify a model |
+| `MULTICA_LLM_MAX_RETRIES` | `2` | Retry ceiling per call; `0` disables retries, `1`–`5` cap it at N |
+
+`MULTICA_LLM_MAX_RETRIES` is the single source for the retry policy. Leave it unset for the default of 2, set `0` to send exactly one request per call, or set 1–5 to cap retries at that many. It is a ceiling, not a quota: only retryable failures consume it, and a success or the caller's own deadline can end the call sooner. Any other value — negative, non-numeric, or above 5 — fails startup instead of being corrected silently. The ceiling is a latency budget: backoff starts at 0.5s and doubles to an 8s cap, so a larger budget would outlast the callers' own deadlines and turn a retryable failure into a timeout. Retries cover connection failures and HTTP 408, 409, 429 and 5xx; all other 4xx responses are returned as-is. The server logs the effective policy at startup as `llm retry policy`, with no credentials in the line.
Two features use this layer, and each one sends chat content to the endpoint you configure:
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index dfdab68dd2..95c3c22de1 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -186,6 +186,9 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `MULTICA_LLM_API_KEY` | 空 | OpenAI 兼容 API key |
| `MULTICA_LLM_BASE_URL` | 空 | OpenAI 兼容 endpoint |
| `MULTICA_LLM_DEFAULT_MODEL` | `gpt-5.6-luna` | 请求未指定模型时使用 |
+| `MULTICA_LLM_MAX_RETRIES` | `2` | 单次调用的重试上限;`0` 表示禁用重试,`1`–`5` 表示最多重试 N 次 |
+
+`MULTICA_LLM_MAX_RETRIES` 是重试策略的唯一配置源。不设置时使用默认的 2 次;设为 `0` 表示每次调用只发一个请求;设为 1–5 表示最多重试这么多次。它是上限而不是配额:只有可重试的失败才会消耗它,请求成功或调用方自身的超时都会让调用提前结束。其它取值(负数、非数字、大于 5)会让服务启动失败,而不是被静默纠正。上限是一个延迟预算:退避从 0.5s 开始翻倍,上限 8s,更大的预算会超出调用方自身的超时,把可重试的失败变成超时失败。重试覆盖连接失败以及 HTTP 408、409、429 和 5xx;其余 4xx 直接返回。服务启动时会以 `llm retry policy` 打印生效策略,其中不包含任何凭据。
有两个功能会使用这一层,它们都会把聊天内容发送到你配置的 endpoint:
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 2ca3241017..e15a6368c4 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -117,6 +117,15 @@ services:
# Empty default = headers ignored, RemoteAddr used. Set e.g.
# "127.0.0.1/32" when running behind a same-host reverse proxy.
MULTICA_TRUSTED_PROXIES: ${MULTICA_TRUSTED_PROXIES:-}
+ # Server-side LLM layer, backing internal helpers such as chat title
+ # generation. Both the API key and the base URL empty = layer disabled,
+ # and callers fall back silently rather than failing. MULTICA_LLM_MAX_RETRIES
+ # is the retry budget: unset = 2, 0 = disabled, 1-5 = an exact ceiling.
+ # Anything else fails the boot instead of being silently corrected.
+ MULTICA_LLM_API_KEY: ${MULTICA_LLM_API_KEY:-}
+ MULTICA_LLM_BASE_URL: ${MULTICA_LLM_BASE_URL:-}
+ MULTICA_LLM_DEFAULT_MODEL: ${MULTICA_LLM_DEFAULT_MODEL:-}
+ MULTICA_LLM_MAX_RETRIES: ${MULTICA_LLM_MAX_RETRIES:-}
# Lark / Feishu bot integration. MULTICA_LARK_SECRET_KEY is the
# opt-in: unset = integration disabled. Mainland 飞书 and international
# Lark are auto-detected per installation and served side by side, so
diff --git a/scripts/selfhost-config.test.sh b/scripts/selfhost-config.test.sh
index 9ffbb28088..7b4fe7159f 100755
--- a/scripts/selfhost-config.test.sh
+++ b/scripts/selfhost-config.test.sh
@@ -33,6 +33,7 @@ tmp_dir="$(mktemp -d)"
trap 'rm -f "$tmp_env"; rm -rf "$tmp_dir"' EXIT
sed 's/^FRONTEND_PORT=.*/FRONTEND_PORT=3100/' .env.example >"$tmp_env"
printf '\nBACKEND_PORT=9100\[email protected]\n' >>"$tmp_env"
+printf 'MULTICA_LLM_API_KEY=llm-key-from-env\nMULTICA_LLM_BASE_URL=http://gateway.example/v1\nMULTICA_LLM_DEFAULT_MODEL=model-from-env\nMULTICA_LLM_MAX_RETRIES=3\n' >>"$tmp_env"
config="$(
docker compose \
@@ -48,6 +49,24 @@ require_config "$config" 'GOOGLE_REDIRECT_URI: http://localhost:3100/auth/callba
require_config "$config" 'MULTICA_APP_URL: http://localhost:3100'
require_config "$config" 'SMTP_FROM_EMAIL: [email protected]'
+# The backend environment is an explicit allowlist, so a variable documented in
+# .env.example but missing here silently never reaches the container: the
+# operator configures it, the server never sees it, and nothing reports the gap.
+# Assert the values actually land, then assert the allowlist has not drifted
+# behind the documentation the next time an LLM knob is added.
+require_config "$config" 'MULTICA_LLM_API_KEY: llm-key-from-env'
+require_config "$config" 'MULTICA_LLM_BASE_URL: http://gateway.example/v1'
+require_config "$config" 'MULTICA_LLM_DEFAULT_MODEL: model-from-env'
+require_config "$config" 'MULTICA_LLM_MAX_RETRIES: "3"'
+
+while IFS= read -r llm_var; do
+ if ! grep -Eq "^[[:space:]]+${llm_var}: \\\$\{${llm_var}:-" docker-compose.selfhost.yml; then
+ echo "$llm_var is documented in .env.example but not mapped into the backend"
+ echo "service in docker-compose.selfhost.yml, so self-hosted deployments cannot set it."
+ exit 1
+ fi
+done < <(grep -oE '^MULTICA_LLM_[A-Z_]+' .env.example)
+
for script in scripts/dev.sh scripts/check.sh; do
if ! grep -Fq '. scripts/local-env.sh' "$script"; then
echo "$script must source scripts/local-env.sh for shared local env derivation."
diff --git a/server/cmd/server/llm_retry_config_test.go b/server/cmd/server/llm_retry_config_test.go
new file mode 100644
index 0000000000..f70373677a
--- /dev/null
+++ b/server/cmd/server/llm_retry_config_test.go
@@ -0,0 +1,100 @@
+package main
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/pkg/llm"
+)
+
+// TestParseLLMMaxRetriesAccepted pins the states an operator is allowed to
+// configure. The nil-versus-override distinction is the whole point: it is what
+// lets pkg/llm tell "unset, use the default" apart from "explicitly disabled".
+func TestParseLLMMaxRetriesAccepted(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ raw string
+ want *int // nil means "unset"
+ }{
+ {name: "unset", raw: "", want: nil},
+ {name: "whitespace is unset", raw: " ", want: nil},
+ {name: "zero disables retries", raw: "0", want: ptr(0)},
+ {name: "positive value", raw: "3", want: ptr(3)},
+ {name: "surrounding whitespace is tolerated", raw: " 3 ", want: ptr(3)},
+ {name: "the ceiling itself is valid", raw: "5", want: ptr(maxLLMRetriesLimit)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := parseLLMMaxRetries(tc.raw)
+ if err != nil {
+ t.Fatalf("parseLLMMaxRetries(%q) failed: %v", tc.raw, err)
+ }
+ switch {
+ case tc.want == nil && got != nil:
+ t.Fatalf("parseLLMMaxRetries(%q) = %d, want unset (nil)", tc.raw, got.Value())
+ case tc.want != nil && got == nil:
+ t.Fatalf("parseLLMMaxRetries(%q) = nil, want %d", tc.raw, *tc.want)
+ case tc.want != nil && got.Value() != *tc.want:
+ t.Fatalf("parseLLMMaxRetries(%q) = %d, want %d", tc.raw, got.Value(), *tc.want)
+ }
+ })
+ }
+}
+
+// TestParseLLMMaxRetriesRejected is the half the original report asked for:
+// every invalid value must fail configuration validation instead of being
+// silently coerced back to a default that looks configured.
+func TestParseLLMMaxRetriesRejected(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ raw string
+ wantMessage string
+ }{
+ {name: "non-numeric", raw: "two", wantMessage: "must be an integer"},
+ {name: "float", raw: "1.5", wantMessage: "must be an integer"},
+ {name: "trailing garbage", raw: "3x", wantMessage: "must be an integer"},
+ {name: "negative", raw: "-1", wantMessage: "must not be negative"},
+ {name: "above the ceiling", raw: "6", wantMessage: "must be at most 5"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := parseLLMMaxRetries(tc.raw)
+ if err == nil {
+ t.Fatalf("parseLLMMaxRetries(%q) accepted the value (= %v), want a validation error", tc.raw, got)
+ }
+ if got != nil {
+ t.Fatalf("parseLLMMaxRetries(%q) returned %d alongside an error; a rejected value must not be usable", tc.raw, got.Value())
+ }
+ if !strings.Contains(err.Error(), tc.wantMessage) {
+ t.Fatalf("parseLLMMaxRetries(%q) error = %q, want it to mention %q", tc.raw, err, tc.wantMessage)
+ }
+ if !strings.Contains(err.Error(), strings.TrimSpace(tc.raw)) {
+ t.Fatalf("parseLLMMaxRetries(%q) error = %q, want it to echo the offending value", tc.raw, err)
+ }
+ })
+ }
+}
+
+// TestParsedLLMMaxRetriesReachesTheClient closes the loop from env string to
+// the budget the SDK will actually enforce — the wiring that did not exist at
+// all before MUL-6364, which is why the field was configurable in name only.
+func TestParsedLLMMaxRetriesReachesTheClient(t *testing.T) {
+ parsed, err := parseLLMMaxRetries("0")
+ if err != nil {
+ t.Fatalf("parseLLMMaxRetries failed: %v", err)
+ }
+
+ budget := llm.New(llm.Config{APIKey: "k", MaxRetries: parsed}).RetryBudget()
+ if budget.MaxRetries != 0 || budget.Source != llm.RetrySourceConfig {
+ t.Fatalf("RetryBudget() = %+v, want retries disabled and sourced from config", budget)
+ }
+
+ unset, err := parseLLMMaxRetries("")
+ if err != nil {
+ t.Fatalf("parseLLMMaxRetries failed: %v", err)
+ }
+ budget = llm.New(llm.Config{APIKey: "k", MaxRetries: unset}).RetryBudget()
+ if budget.MaxRetries != llm.DefaultMaxRetries || budget.Source != llm.RetrySourceDefault {
+ t.Fatalf("RetryBudget() = %+v, want the default budget", budget)
+ }
+}
+
+func ptr(n int) *int { return &n }
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index ac57c5553c..95844fc771 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -2,6 +2,7 @@ package main
import (
"context"
+ "fmt"
"log/slog"
"net/http"
"os"
@@ -23,6 +24,7 @@ import (
"github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/featureflag"
+ "github.com/multica-ai/multica/server/pkg/llm"
"github.com/redis/go-redis/v9"
)
@@ -118,6 +120,46 @@ func envNonNegativeInt(name string, def int) int {
return v
}
+// maxLLMRetriesLimit caps MULTICA_LLM_MAX_RETRIES. The ceiling is a latency
+// budget, not a taste call: SDK backoff is 0.5s doubling to an 8s cap, so 6
+// retries spend ~21s and 10 spend ~48s sleeping before the last attempt. Every
+// internal caller of pkg/llm runs under a far tighter deadline (8s for chat
+// quick actions, 20s for title generation), so a budget past 5 cannot finish —
+// it only converts a retryable upstream failure into a deadline-exceeded one.
+const maxLLMRetriesLimit = 5
+
+// parseLLMMaxRetries turns the raw MULTICA_LLM_MAX_RETRIES value into the
+// tri-state llm.Config.MaxRetries expects: nil for unset (use the default),
+// llm.Retries(0) to disable retries, llm.Retries(N) for a ceiling of N.
+//
+// Unlike the envFooInt helpers above it returns an error instead of warning and
+// falling back to a default. A retry budget silently corrected to something the
+// operator did not ask for is the failure this knob exists to remove
+// (MUL-6364): a typo'd "3x" or a negative must stop the boot, not quietly
+// restore the default and look configured.
+func parseLLMMaxRetries(raw string) (*llm.RetryOverride, error) {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return nil, nil
+ }
+ v, err := strconv.Atoi(raw)
+ if err != nil {
+ return nil, fmt.Errorf("must be an integer, got %q", raw)
+ }
+ if v > maxLLMRetriesLimit {
+ return nil, fmt.Errorf("must be at most %d, got %d", maxLLMRetriesLimit, v)
+ }
+ // llm.Retries owns the lower bound. It is the boundary that makes a negative
+ // budget unrepresentable, and this is the only place the server builds one,
+ // so the deployment-specific ceiling above and the type-level floor here
+ // cannot disagree.
+ override, err := llm.Retries(v)
+ if err != nil {
+ return nil, fmt.Errorf("must not be negative, got %d (use 0 to disable retries)", v)
+ }
+ return override, nil
+}
+
func envPositiveInt64(name string, def int64) int64 {
raw := os.Getenv(name)
if raw == "" {
@@ -431,6 +473,15 @@ func main() {
// shutdown so any pending bumps are flushed before we exit.
heartbeatScheduler := handler.NewBatchedHeartbeatScheduler(queries, handler.DefaultHeartbeatBatchInterval)
+ // Validate the LLM retry budget before the router exists: an operator who
+ // typed a value we cannot honor should see the boot stop, the same way a
+ // malformed feature-flag file does above.
+ llmMaxRetries, err := parseLLMMaxRetries(os.Getenv("MULTICA_LLM_MAX_RETRIES"))
+ if err != nil {
+ slog.Error("invalid MULTICA_LLM_MAX_RETRIES", "error", err)
+ os.Exit(1)
+ }
+
r, h := NewRouterWithOptions(pool, hub, bus, analyticsClient, storeRedis, RouterOptions{
HTTPMetrics: httpMetrics,
BusinessMetrics: businessMetrics,
@@ -441,6 +492,7 @@ func main() {
DaemonWakeup: daemonWakeup,
FeatureFlags: flags,
HeartbeatScheduler: heartbeatScheduler,
+ LLMMaxRetries: llmMaxRetries,
})
srv := &http.Server{
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 07ef98e7e4..79a28ecd06 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -42,6 +42,7 @@ import (
composiosdk "github.com/multica-ai/multica/server/pkg/composio"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/featureflag"
+ "github.com/multica-ai/multica/server/pkg/llm"
)
var defaultOrigins = []string{
@@ -193,6 +194,13 @@ type RouterOptions struct {
// BatchedHeartbeatScheduler here so the caller can also drive Run/Stop;
// tests leave this nil and get the legacy synchronous behavior.
HeartbeatScheduler handler.HeartbeatScheduler
+ // LLMMaxRetries carries the parsed MULTICA_LLM_MAX_RETRIES budget. Unlike
+ // its three MULTICA_LLM_* siblings it is injected rather than read here,
+ // because an invalid value must fail the boot and only main() can exit —
+ // terminating the process from inside a router constructor would also kill
+ // any test that happened to have the variable set. nil means unset, which
+ // is what tests and NewRouter get.
+ LLMMaxRetries *llm.RetryOverride
}
func buildChannelSupervisor(
@@ -343,6 +351,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
LLMAPIKey: strings.TrimSpace(os.Getenv("MULTICA_LLM_API_KEY")),
LLMBaseURL: strings.TrimSpace(os.Getenv("MULTICA_LLM_BASE_URL")),
LLMDefaultModel: strings.TrimSpace(os.Getenv("MULTICA_LLM_DEFAULT_MODEL")),
+ LLMMaxRetries: opts.LLMMaxRetries,
ServerVersion: normalizeServerVersion(version),
}
h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 45dc5fecdd..9b20c057ce 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -122,9 +122,16 @@ type Config struct {
// - LLMAPIKey -> MULTICA_LLM_API_KEY
// - LLMBaseURL -> MULTICA_LLM_BASE_URL (OpenAI or any compatible gateway)
// - LLMDefaultModel -> MULTICA_LLM_DEFAULT_MODEL (used when a request omits `model`)
+ // - LLMMaxRetries -> MULTICA_LLM_MAX_RETRIES (transport retry budget)
LLMAPIKey string
LLMBaseURL string
LLMDefaultModel string
+ // LLMMaxRetries is the parsed MULTICA_LLM_MAX_RETRIES budget. nil means
+ // unset (llm.DefaultMaxRetries applies); llm.Retries(0) disables retries.
+ // The type carries the validation: it can only be built through llm.Retries,
+ // and cmd/server additionally fails the boot on an out-of-range value before
+ // one reaches this struct. See llm.Config.MaxRetries for the full semantics.
+ LLMMaxRetries *llm.RetryOverride
// ServerVersion is the build version of the running API binary (the same
// value main.go stamps via -X main.version and reports on /metrics).
// Surfaced through /api/config so self-hosted operators can confirm which
@@ -377,7 +384,21 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
APIKey: cfg.LLMAPIKey,
BaseURL: cfg.LLMBaseURL,
DefaultModel: cfg.LLMDefaultModel,
+ MaxRetries: cfg.LLMMaxRetries,
})
+ // Report the effective retry policy so an operator can confirm from the
+ // boot log alone what a misbehaving upstream will cost, instead of inferring
+ // it from an env var whose semantics used to be unguessable (MUL-6364).
+ // Read off the client, not off cfg, so the line cannot drift from what the
+ // SDK actually enforces. Counts and an enum only — never the key or the base
+ // URL, since a self-hosted gateway URL routinely embeds a token.
+ llmRetry := llmClient.RetryBudget()
+ slog.Info("llm retry policy",
+ "max_retries", llmRetry.MaxRetries,
+ "source", llmRetry.Source,
+ "request_timeout", llmRetry.RequestTimeout,
+ "enabled", llmClient.Enabled(),
+ )
taskSvc := service.NewTaskService(queries, txStarter, hub, bus, daemonHub)
taskSvc.Analytics = analyticsClient
diff --git a/server/pkg/llm/client.go b/server/pkg/llm/client.go
index 1f38b9cf92..ecffc0160d 100644
--- a/server/pkg/llm/client.go
+++ b/server/pkg/llm/client.go
@@ -74,6 +74,7 @@ package llm
import (
"context"
"errors"
+ "fmt"
"net/http"
"strings"
"time"
@@ -114,20 +115,110 @@ type Config struct {
// DefaultModel is used when a request omits the model. Maps to
// MULTICA_LLM_DEFAULT_MODEL. When empty, FallbackModel is used.
DefaultModel string
- // MaxRetries overrides the SDK default (2). A negative value is treated as
- // zero (no retries).
- MaxRetries int
+ // MaxRetries is the transport-level retry budget applied to every request
+ // this client makes. Maps to MULTICA_LLM_MAX_RETRIES. Build one with
+ // Retries; nil means unset, and DefaultMaxRetries applies.
+ //
+ // - nil — unset; DefaultMaxRetries applies.
+ // - Retries(0) — retries disabled; exactly one upstream request.
+ // - Retries(N) — at most N retries, so at most N+1 upstream requests.
+ //
+ // It is a pointer to a validated type rather than a bare int for two
+ // reasons (MUL-6364). A bare int made 0 indistinguishable from the zero
+ // value, so asking for no retries silently produced the SDK default
+ // instead; and it let a negative — which option.WithMaxRetries panics on —
+ // reach this layer, where the only options were to panic or to quietly
+ // substitute some other budget. Retries is the sole constructor and rejects
+ // negatives, so neither state is representable here at all.
+ //
+ // What this budget retries is decided by the SDK: connection-level failures
+ // (no response at all), HTTP 408, 409, 429 and any 5xx, plus any response
+ // carrying `x-should-retry: true`. Every other 4xx — 400, 401, 403, 404 —
+ // is returned to the caller unretried. Backoff starts at 0.5s and doubles
+ // to an 8s cap with up to 25% jitter subtracted, unless the response
+ // carries a Retry-After header, which wins.
+ //
+ // It is NOT the parameter-compatibility retry inside GenerateJSON (which is
+ // independent and bounded separately), and it does not cover a stream that
+ // breaks after ChatStream has already returned. Choose a value against the
+ // caller's own deadline: backoff alone costs ~1.5s at 2 retries and ~21s at
+ // 6, so a budget larger than the caller's timeout only converts a
+ // recoverable failure into a deadline-exceeded one.
+ MaxRetries *RetryOverride
// HTTPClient, when set, replaces the SDK's default transport. Primarily a
// test seam.
HTTPClient option.HTTPClient
}
+// DefaultMaxRetries is the retry budget used when Config.MaxRetries is unset.
+// It mirrors the openai-go default at the version we pin, but New always passes
+// it explicitly so the effective policy is ours to report and can never drift
+// silently with an SDK bump.
+const DefaultMaxRetries = 2
+
+// RetryOverride is a validated retry budget for Config.MaxRetries. Its only
+// field is unexported and Retries is its only constructor, so an invalid budget
+// cannot be represented at this boundary — New therefore has no correction
+// branch to take, and needs none. #7154 asked that invalid values fail
+// validation rather than be silently coerced; making them unbuildable is the
+// strongest available form of that.
+type RetryOverride struct{ n int }
+
+// Retries returns an override of at most n retries per call. It rejects a
+// negative n instead of correcting it: option.WithMaxRetries panics on one, and
+// there is no honest correction to make — "fewer than zero retries" is a
+// mistake, not a request to disable them. Retries(0) is how you disable them.
+func Retries(n int) (*RetryOverride, error) {
+ if n < 0 {
+ return nil, fmt.Errorf("llm: max retries must not be negative, got %d (use 0 to disable retries)", n)
+ }
+ return &RetryOverride{n: n}, nil
+}
+
+// Value reports the configured budget. The zero value of RetryOverride reports
+// 0, which is consistent: an override that was never built through Retries
+// carries no retries either.
+func (r *RetryOverride) Value() int {
+ if r == nil {
+ return 0
+ }
+ return r.n
+}
+
+// Retry policy sources, as reported by RetryBudget.Source.
+const (
+ // RetrySourceDefault means Config.MaxRetries was unset.
+ RetrySourceDefault = "default"
+ // RetrySourceConfig means Config.MaxRetries was set explicitly, including
+ // an explicit 0.
+ RetrySourceConfig = "config"
+)
+
+// RetryBudget describes a Client's effective transport retry policy. It exists
+// so a deployment can report what it will actually do rather than re-derive it
+// from raw configuration — re-deriving is how the unset-versus-zero ambiguity
+// went unnoticed in the first place. Every field is a scalar or a fixed enum,
+// so logging the whole struct can never leak an API key or a gateway URL.
+type RetryBudget struct {
+ // MaxRetries is the ceiling on retries after a failed request, so N means
+ // at most N+1 upstream requests per call. Only retryable failures consume
+ // it; a success or the caller's deadline can end the call sooner.
+ MaxRetries int
+ // Source is RetrySourceDefault or RetrySourceConfig.
+ Source string
+ // RequestTimeout bounds the whole non-streaming call chain, retries and
+ // backoff included, when the caller's context has no earlier deadline of
+ // its own. Every current internal caller sets a tighter one.
+ RequestTimeout time.Duration
+}
+
// Client is a configured, reusable LLM caller. It is safe for concurrent use;
// the underlying SDK client holds no per-request state.
type Client struct {
sdk openai.Client
defaultModel string
enabled bool
+ retry RetryBudget
}
// New builds a Client from cfg. It never returns an error: an unconfigured
@@ -142,13 +233,21 @@ func New(cfg Config) *Client {
if base := strings.TrimSpace(cfg.BaseURL); base != "" {
opts = append(opts, option.WithBaseURL(base))
}
- if cfg.MaxRetries != 0 {
- retries := cfg.MaxRetries
- if retries < 0 {
- retries = 0
- }
- opts = append(opts, option.WithMaxRetries(retries))
+ retry := RetryBudget{
+ MaxRetries: DefaultMaxRetries,
+ Source: RetrySourceDefault,
+ RequestTimeout: defaultRequestTimeout,
}
+ if cfg.MaxRetries != nil {
+ // No validation and no clamping here on purpose: RetryOverride can only
+ // hold a value Retries already accepted, so there is no invalid budget
+ // left for this layer to silently correct.
+ retry.MaxRetries = cfg.MaxRetries.Value()
+ retry.Source = RetrySourceConfig
+ }
+ // Always set it explicitly, even for the default, so the budget the SDK
+ // enforces and the one RetryBudget reports are the same number.
+ opts = append(opts, option.WithMaxRetries(retry.MaxRetries))
if cfg.HTTPClient != nil {
opts = append(opts, option.WithHTTPClient(cfg.HTTPClient))
}
@@ -164,9 +263,19 @@ func New(cfg Config) *Client {
// A deployment is "configured" if it gave us either a key or a base
// URL. A bare base URL (no key) is valid for keyless local gateways.
enabled: strings.TrimSpace(cfg.APIKey) != "" || strings.TrimSpace(cfg.BaseURL) != "",
+ retry: retry,
}
}
+// RetryBudget returns the effective transport retry policy, for startup
+// diagnostics. Safe to log whole: it carries no credentials or URLs.
+func (c *Client) RetryBudget() RetryBudget {
+ if c == nil {
+ return RetryBudget{}
+ }
+ return c.retry
+}
+
// Enabled reports whether the client was given any credentials or base URL.
// Handlers use this to short-circuit with a 503 before doing any work.
func (c *Client) Enabled() bool { return c != nil && c.enabled }
@@ -205,6 +314,10 @@ func (c *Client) Chat(ctx context.Context, params openai.ChatCompletionNewParams
//
// Unlike Chat, no default timeout is imposed: the stream's lifetime is owned by
// the caller (typically an HTTP handler bound to the client connection).
+//
+// Config.MaxRetries covers only the POST that opens the stream. Once this
+// returns, a stream that breaks mid-response is the caller's to handle: the SDK
+// cannot replay chunks it has already delivered.
func (c *Client) ChatStream(ctx context.Context, params openai.ChatCompletionNewParams) (*ssestream.Stream[openai.ChatCompletionChunk], error) {
if !c.Enabled() {
return nil, ErrNotConfigured
@@ -308,6 +421,13 @@ func (c *Client) GenerateJSON(ctx context.Context, model, systemPrompt, userProm
// modern fields. Negotiate only when the upstream explicitly identifies an
// unsupported parameter: validation fails before generation, and each field
// can be removed or replaced at most once under the shared deadline.
+ //
+ // This loop is a parameter-compatibility negotiation, NOT an error retry,
+ // and it is deliberately independent of Config.MaxRetries: it fires only on
+ // a 400 the SDK never retries, and its bound stays 2 whatever the transport
+ // budget is. The two do compose, though — each attempt below carries its own
+ // transport budget, so one call can cost up to two negotiation requests plus
+ // MaxRetries+1 on the final attempt.
var completion *openai.ChatCompletion
for compatibilityRetries := 0; ; compatibilityRetries++ {
var err error
diff --git a/server/pkg/llm/client_test.go b/server/pkg/llm/client_test.go
index 086bc53640..5b68707321 100644
--- a/server/pkg/llm/client_test.go
+++ b/server/pkg/llm/client_test.go
@@ -13,6 +13,19 @@ import (
"github.com/openai/openai-go/v3/shared"
)
+// retries builds a Config.MaxRetries value, failing loudly on a budget Retries
+// rejects. Tests that assert an exact upstream request count pass retries(0) to
+// take SDK retries out of the picture; before MUL-6364 that required the
+// negative -1, because a plain 0 was indistinguishable from unset and quietly
+// restored the default budget.
+func retries(n int) *RetryOverride {
+ override, err := Retries(n)
+ if err != nil {
+ panic(err)
+ }
+ return override
+}
+
// stubUpstream returns an httptest server that mimics the OpenAI
// chat-completions endpoint. handler receives the decoded request body.
func stubUpstream(t *testing.T, handler func(w http.ResponseWriter, body map[string]any)) *httptest.Server {
@@ -178,7 +191,7 @@ func TestGenerateJSONFallsBackToLegacyMaxTokens(t *testing.T) {
_, _ = io.WriteString(w, `{"id":"cmpl-1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"{\"actions\":[]}"},"finish_reason":"stop"}]}`)
})
- c := New(Config{APIKey: "k", BaseURL: srv.URL, MaxRetries: -1})
+ c := New(Config{APIKey: "k", BaseURL: srv.URL, MaxRetries: retries(0)})
if _, err := c.GenerateJSON(context.Background(), "legacy-model", "Return JSON.", "Generate actions.", 0.3, 800); err != nil {
t.Fatalf("GenerateJSON failed: %v", err)
}
@@ -215,7 +228,7 @@ func TestGenerateJSONFallsBackFromUnsupportedReasoningEffort(t *testing.T) {
_, _ = io.WriteString(w, `{"id":"cmpl-1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"{\"actions\":[]}"},"finish_reason":"stop"}]}`)
})
- c := New(Config{APIKey: "k", BaseURL: srv.URL, MaxRetries: -1})
+ c := New(Config{APIKey: "k", BaseURL: srv.URL, MaxRetries: retries(0)})
if _, err := c.GenerateJSON(context.Background(), "gpt-5.6-luna", "Return JSON.", "Generate actions.", 0.3, 800); err != nil {
t.Fatalf("GenerateJSON failed: %v", err)
}
@@ -250,7 +263,7 @@ func TestGenerateJSONNegotiatesBothLegacyParameters(t *testing.T) {
}
})
- c := New(Config{APIKey: "k", BaseURL: srv.URL, MaxRetries: -1})
+ c := New(Config{APIKey: "k", BaseURL: srv.URL, MaxRetries: retries(0)})
if _, err := c.GenerateJSON(context.Background(), "gpt-5.6-luna", "Return JSON.", "Generate actions.", 0.3, 800); err != nil {
t.Fatalf("GenerateJSON failed: %v", err)
}
@@ -278,7 +291,7 @@ func TestGenerateJSONDoesNotRetryInvalidTokenLimit(t *testing.T) {
_, _ = io.WriteString(w, `{"error":{"message":"Invalid max_completion_tokens value","type":"invalid_request_error","param":"max_completion_tokens","code":"invalid_value"}}`)
})
- c := New(Config{APIKey: "k", BaseURL: srv.URL, MaxRetries: -1})
+ c := New(Config{APIKey: "k", BaseURL: srv.URL, MaxRetries: retries(0)})
if _, err := c.GenerateJSON(context.Background(), "gpt-5.6-luna", "Return JSON.", "Generate actions.", 0.3, 800); err == nil {
t.Fatal("expected invalid token limit error")
}
diff --git a/server/pkg/llm/retry_test.go b/server/pkg/llm/retry_test.go
new file mode 100644
index 0000000000..2027e138d8
--- /dev/null
+++ b/server/pkg/llm/retry_test.go
@@ -0,0 +1,164 @@
+package llm
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+
+ openai "github.com/openai/openai-go/v3"
+)
+
+// retryingUpstream always fails with a status the SDK retries, and counts how
+// many requests it saw. `Retry-After: 0` keeps the assertions about the retry
+// COUNT from also paying for the backoff curve — the SDK honors the header
+// verbatim, so the test runs in milliseconds instead of seconds.
+func retryingUpstream(t *testing.T, count *int) string {
+ t.Helper()
+ return stubUpstream(t, func(w http.ResponseWriter, _ map[string]any) {
+ *count++
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Retry-After", "0")
+ w.WriteHeader(http.StatusInternalServerError)
+ _, _ = io.WriteString(w, `{"error":{"message":"boom","type":"server_error"}}`)
+ }).URL
+}
+
+// TestMaxRetriesSemantics pins the supported states of Config.MaxRetries
+// against the only thing that matters to an operator: how many times we hit
+// their upstream. Before MUL-6364 an explicit 0 landed in the "unset" row here
+// and a negative was the only way to reach the "disabled" one. The upstream
+// here fails every time, so the budget is always spent in full — with a
+// recoverable upstream the same configuration would stop at the first success.
+func TestMaxRetriesSemantics(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ configured *RetryOverride
+ wantRequests int
+ wantBudget RetryBudget
+ }{
+ {
+ name: "unset uses the documented default",
+ configured: nil,
+ wantRequests: DefaultMaxRetries + 1,
+ wantBudget: RetryBudget{MaxRetries: DefaultMaxRetries, Source: RetrySourceDefault, RequestTimeout: defaultRequestTimeout},
+ },
+ {
+ name: "zero disables retries",
+ configured: retries(0),
+ wantRequests: 1,
+ wantBudget: RetryBudget{MaxRetries: 0, Source: RetrySourceConfig, RequestTimeout: defaultRequestTimeout},
+ },
+ {
+ name: "one caps retries at one",
+ configured: retries(1),
+ wantRequests: 2,
+ wantBudget: RetryBudget{MaxRetries: 1, Source: RetrySourceConfig, RequestTimeout: defaultRequestTimeout},
+ },
+ {
+ name: "positive value is honored as the ceiling",
+ configured: retries(5),
+ wantRequests: 6,
+ wantBudget: RetryBudget{MaxRetries: 5, Source: RetrySourceConfig, RequestTimeout: defaultRequestTimeout},
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ requests := 0
+ c := New(Config{APIKey: "k", BaseURL: retryingUpstream(t, &requests), MaxRetries: tc.configured})
+
+ if got := c.RetryBudget(); got != tc.wantBudget {
+ t.Fatalf("RetryBudget() = %+v, want %+v", got, tc.wantBudget)
+ }
+ if _, err := c.Chat(context.Background(), openai.ChatCompletionNewParams{}); err == nil {
+ t.Fatal("expected the upstream error to surface after the retry budget is spent")
+ }
+ if requests != tc.wantRequests {
+ t.Fatalf("upstream saw %d requests, want %d", requests, tc.wantRequests)
+ }
+ })
+ }
+}
+
+// TestRetriesRejectsNegative is the acceptance criterion from #7154 at the
+// package boundary: an invalid budget fails validation instead of being coerced
+// into a working-looking one. Because Retries is the only constructor, a
+// rejected value cannot go on to configure anything — there is deliberately no
+// fallback here to assert.
+func TestRetriesRejectsNegative(t *testing.T) {
+ for _, n := range []int{-1, -5} {
+ override, err := Retries(n)
+ if err == nil {
+ t.Fatalf("Retries(%d) = %+v, want a validation error", n, override)
+ }
+ if override != nil {
+ t.Fatalf("Retries(%d) returned %+v alongside an error; a rejected budget must not be usable", n, override)
+ }
+ if !strings.Contains(err.Error(), "must not be negative") {
+ t.Fatalf("Retries(%d) error = %q, want it to say the value must not be negative", n, err)
+ }
+ }
+}
+
+// TestRetriesAcceptsNonNegative is the other half: 0 and positive values build
+// an override reporting exactly what was asked for.
+func TestRetriesAcceptsNonNegative(t *testing.T) {
+ for _, n := range []int{0, 1, 5, 100} {
+ override, err := Retries(n)
+ if err != nil {
+ t.Fatalf("Retries(%d) failed: %v", n, err)
+ }
+ if got := override.Value(); got != n {
+ t.Fatalf("Retries(%d).Value() = %d, want %d", n, got, n)
+ }
+ }
+
+ var missing *RetryOverride
+ if got := missing.Value(); got != 0 {
+ t.Fatalf("nil override Value() = %d, want 0", got)
+ }
+}
+
+// TestRetryBudgetOnDisabledClient guards the startup diagnostic: a deployment
+// with no LLM configuration still logs one, so RetryBudget must be readable
+// there rather than describing a client that will never dial anything.
+func TestRetryBudgetOnDisabledClient(t *testing.T) {
+ c := New(Config{})
+ if c.Enabled() {
+ t.Fatal("expected a disabled client")
+ }
+ if got := c.RetryBudget(); got.MaxRetries != DefaultMaxRetries || got.Source != RetrySourceDefault {
+ t.Fatalf("RetryBudget() = %+v, want the default budget", got)
+ }
+
+ var nilClient *Client
+ if got := (nilClient.RetryBudget()); got != (RetryBudget{}) {
+ t.Fatalf("nil Client RetryBudget() = %+v, want the zero value", got)
+ }
+}
+
+// TestMaxRetriesDoesNotBoundCompatibilityRetries keeps the two retry mechanisms
+// in this package separable. The GenerateJSON parameter negotiation fires on a
+// 400 the SDK never retries, so disabling the transport budget entirely must
+// leave it working.
+func TestMaxRetriesDoesNotBoundCompatibilityRetries(t *testing.T) {
+ requests := 0
+ srv := stubUpstream(t, func(w http.ResponseWriter, _ map[string]any) {
+ requests++
+ w.Header().Set("Content-Type", "application/json")
+ if requests == 1 {
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = io.WriteString(w, `{"error":{"message":"Unsupported parameter: max_completion_tokens","type":"invalid_request_error","param":"max_completion_tokens","code":"unsupported_parameter"}}`)
+ return
+ }
+ _, _ = io.WriteString(w, `{"id":"cmpl-1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"{}"},"finish_reason":"stop"}]}`)
+ })
+
+ c := New(Config{APIKey: "k", BaseURL: srv.URL, MaxRetries: retries(0)})
+ if _, err := c.GenerateJSON(context.Background(), "legacy-model", "Return JSON.", "go", 0.3, 800); err != nil {
+ t.Fatalf("GenerateJSON failed: %v", err)
+ }
+ if requests != 2 {
+ t.Fatalf("upstream saw %d requests, want 2 (the negotiation runs with retries disabled)", requests)
+ }
+}