OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[Bug]: Async embedding client cannot self-heal after upstream gateway recovers from 5xx — process restart required

Open hachimin-wh opened this issue 3 months ago • 2 comments

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:

  1. 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.
  2. 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

  1. Point embedding.dense (provider=openai) at a gateway fronted by an LB; start openviking serve; verify find/search works
  2. Make the gateway return 502 for a while (real upstream flapping, or the mock below)
  3. Wait until the gateway fully recovers (curl directly: 10/10 → 200)
  4. 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)

  1. openviking/utils/async_client_cache.py: LoopScopedAsyncClientCache caches the client per event loop for the lifetime of the process — no TTL, no failure invalidation, no rebuild hook.
  2. openviking/models/embedder/openai_embedders.py: _client_kwargs only sets api_key/base_url; max_retries/timeout/http_client are not configurable.
  3. openviking/service/core.py: the query-path embedder is created once at startup and lives as long as the process (passed to HierarchicalRetriever via query_embedder) — a restart is the only way to rebuild its pool.
  4. 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)

  1. Minimal: on 5xx, invalidate and rebuild the cached client for the current loop (reuse classify_api_error and the existing pop_all()/close_all_with_aclose() primitives; add a cooldown to avoid rebuild storms).
  2. Enhancement: allow passing http_client / pool settings, or explicit max_retries/timeout for the embedding client.
  3. 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).

hachimin-wh avatar Aug 19 '26 06:08 hachimin-wh

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.

ktz03 avatar Aug 19 '26 09:08 ktz03

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.

qin-ctx avatar Aug 19 '26 09:08 qin-ctx