[Bug]: Async embedding client cannot self-heal after upstream gateway recovers from 5xx — process restart required
Issue Origin
Observed or reproduced in a real environment
Bug Description
The failure has two phases — the first is legitimate; the second is the bug:
- Phase 1 (external cause): the embedding gateway intermittently returns 502 (a failing upstream instance behind it) → find/search becomes unavailable. This is legitimate: upstream is genuinely down.
- Phase 2 (this bug): after the gateway recovers — direct curl returns 200 on 10/10 — OV's find/search still fails with 502 on 10/10, indefinitely, with no sign of self-healing. The only recovery: restarting the server process (fixed immediately, 5/5).
What sustains the failure has shifted from "upstream down" to "a stale connection pool inside the OV process":
curl : fresh connection per request ──────→ LB ──→ healthy upstream ──→ 200 ✔
OV : reuses pooled keep-alive connections ──→ failing path ──────→ 502 ✘
Key detail: a 502 is a valid HTTP response (the TCP connection stays up), so httpx considers these stale connections healthy, returns them to the pool and keeps reusing them — the pool never refreshes, and the gateway's "recovery" only applies to new connections. Regardless of the exact gateway-side mechanism (per-connection backend affinity is the likely explanation), the OV-side facts are proven and reproducible: LoopScopedAsyncClientCache has no failure-invalidation or rebuild path — business requests, SDK retries and circuit-breaker probes all go through the same stale connections and all fail, until restart.
Steps to Reproduce
- Point
embedding.dense(provider=openai) at a gateway fronted by an LB; startopenviking serve; verify find/search works - Make the gateway return 502 for a while (real upstream flapping, or the mock below)
- Wait until the gateway fully recovers (curl directly: 10/10 → 200)
- Call
POST /api/v1/search/find→ still 502
Expected Behavior
After upstream recovers from 5xx, the client should rebuild the underlying client/connection pool after a bounded number of failures and self-heal without a process restart. When circuit-breaker HALF_OPEN probes keep failing, it should distinguish "upstream still down" from "local transport layer broken" and trigger a client rebuild instead of merely extending the open state.
Actual Behavior
| Test | Timing | Result |
|---|---|---|
curl to gateway /v1/embeddings ×10 |
after gateway recovery | 10/10 HTTP 200 |
OV REST find ×10 |
same window | 10/10 fail (502) |
OV REST find ×5 after process restart |
immediately after restart | 5/5 OK |
The query path and the indexing path each hold their own connection pool; whichever gets pinned fails first (we observed writes succeeding while all queries failed). Only a process restart (= rebuilding all pools) breaks out of it.
Minimal Reproducible Example
<details>
<summary>mock_gateway.py: simulates "connections established during the failure window stay pinned" (expand)</summary>
# Connections established during the failure window keep getting 502
# (simulating LB per-connection affinity to a failing upstream);
# connections created after the window get 200 — i.e. "upstream recovered,
# but stale connections keep failing".
import http.server, time
START, WINDOW, BAD = time.time(), 10, set()
class H(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_POST(self):
cid = id(self.connection) # keep-alive: same connection, same handler
if time.time() - START < WINDOW:
BAD.add(cid)
if cid in BAD:
body, code = b'{"error": "upstream unavailable"}', 502
else:
body, code = b'{"object":"list","data":[{"embedding":[0.1]*8,"index":0}],"model":"mock"}', 200
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
http.server.ThreadingHTTPServer(("127.0.0.1", 9999), H).serve_forever()
</details>
Steps: start the mock → point `ov.conf` at `http://127.0.0.1:9999/v1` (set dimension to 8) → start OV and issue a few finds inside the failure window → after the window: curl (fresh connections) gets 200, OV find keeps failing with 502 → restart OV and it recovers immediately.
Error Logs
Retrying request to /embeddings in 0.8~0.9 seconds # SDK-internal retries reuse the same pinned pool
UNAVAILABLE: Upstream model service unavailable (HTTP 502)
OpenAI API error: Error code: 502 ... 'http://<internal-gateway>/v1/embeddings'
Embedding circuit breaker is open; re-enqueueing messages # probes reuse the failing path too; locked up to 10 min
OpenViking Version
main @ d88967aa (code paths verified identical; reproduced on 0.4.14.dev80 editable install)
Python Version
3.12.10
Operating System
macOS
Model Backend
OpenAI
Additional Context
Root cause (four compounding factors)
openviking/utils/async_client_cache.py:LoopScopedAsyncClientCachecaches the client per event loop for the lifetime of the process — no TTL, no failure invalidation, no rebuild hook.openviking/models/embedder/openai_embedders.py:_client_kwargsonly setsapi_key/base_url;max_retries/timeout/http_clientare not configurable.openviking/service/core.py: the query-path embedder is created once at startup and lives as long as the process (passed toHierarchicalRetrieverviaquery_embedder) — a restart is the only way to rebuild its pool.openviking/utils/circuit_breaker.py: HALF_OPEN probes reuse the same pinned connections and keep failing → reset timeout doubles exponentially up to 600s, extending the outage rather than ending it.
Suggested fixes (by intrusiveness)
- Minimal: on 5xx, invalidate and rebuild the cached client for the current loop (reuse
classify_api_errorand the existingpop_all()/close_all_with_aclose()primitives; add a cooldown to avoid rebuild storms). - Enhancement: allow passing
http_client/ pool settings, or explicitmax_retries/timeoutfor the embedding client. - Breaker integration: after N consecutive HALF_OPEN probe failures, rebuild the client once before probing again.
Related: #4017 (same family, different mechanism — complementary); #2369 (same subsystem, accepted fix); #199 (similar symptom, different root cause — listed to avoid a false duplicate).
Working on a fix: invalidate the loop-scoped async embedding HTTP client after gateway 502/503/504 so retries open a fresh connection instead of reusing a stale keep-alive pool entry.
Thanks for reporting this and for the detailed reproduction.
After looking at the failure mode, we do not plan to fix this by rebuilding OpenViking embedding clients on HTTP 5xx responses. A 502/503/504 is still a valid HTTP response. If a gateway or load balancer keeps a keep-alive connection pinned to an unhealthy backend after the backend has recovered, that connection should be closed or drained by the gateway/LB layer, or the gateway should adjust its keep-alive/backend-affinity behavior so clients naturally open a fresh path.
OpenViking cannot reliably distinguish a normal upstream 5xx from a protocol-valid connection that is locally stale because of gateway routing. Invalidating client pools on 5xx would be a workaround in the wrong layer and could add unnecessary client churn during real upstream outages.
Closing this as not planned from the OpenViking side. The recommended fix is in the embedding gateway/LB connection-draining and keep-alive handling.