Skip to content

Commit 35fe081

Browse files
fix(proxy): fix "stuck Indexing…" bug via peek_ready + watchdog
- `proxy_if_live` and `get_json_if_live` used a two-step `ready_repos()` + `acquire` pattern that, on a dead `Ready` entry, transitioned the registry to `Spawning` and discarded the elected driver — orphaning the entry permanently. - Replace both callsites with `peek_ready`, which atomically returns a live worker or reaps the dead entry to absent, and never elects a spawn. - Add `since: Instant` to `WorkerState::Spawning` so orphaned in-flight spawns (driver dropped mid-flight) can be aged out. - Define `SPAWN_ORPHAN_AFTER` as 3× `SPAWN_READY_TIMEOUT` — structurally safe because every live driver resolves its entry before `SPAWN_READY_TIMEOUT` expires. - Boot a 15-second watchdog task in `build_router_app` that calls `Registry::reap` to converge stale `Ready` and over-age `Spawning` entries without waiting for a request. - Add `ReadyWorker::kill_and_wait` for superseded workers that still hold the RocksDB exclusive LOCK after `publish_ready` detects an ABA race, preventing deadlock on re-elected spawns.
1 parent 985e1f0 commit 35fe081

4 files changed

Lines changed: 522 additions & 33 deletions

File tree

‎src/router/mod.rs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,31 @@ pub async fn build_router_app(opts: RouterBootOptions) -> Result<Router> {
180180
});
181181
}
182182

183+
// Registry SELF-HEAL watchdog. The router learns a worker died only when a
184+
// request next probes its entry; under scale-to-zero a repo can sit idle for
185+
// a long time after its worker idle-exits, leaving a stale `Ready` entry —
186+
// and a `Spawning` entry can orphan if a spawn driver is dropped mid-flight.
187+
// This periodic sweep drops both (dead `Ready` → absent, over-age `Spawning`
188+
// → absent + wake awaiters) so the registry converges to the truth without
189+
// waiting for a request. Cheap: a single write-locked `retain` over a map
190+
// that holds at most one entry per repo, on a coarse timer. (The orphan-age
191+
// cutoff `SPAWN_ORPHAN_AFTER` can never reap a live in-flight spawn — see its
192+
// docs.)
193+
{
194+
let registry = state.proxy.registry.clone();
195+
tokio::spawn(async move {
196+
// Coarse cadence: orphans are rare and self-heal is not latency-
197+
// sensitive (read routes already reap dead `Ready` on access via
198+
// `peek_ready`; this is the backstop). Tick well under the orphan
199+
// cutoff so a true orphan is cleared within ~one cutoff window.
200+
let tick = std::time::Duration::from_secs(15);
201+
loop {
202+
tokio::time::sleep(tick).await;
203+
registry.reap(spawn::SPAWN_ORPHAN_AFTER).await;
204+
}
205+
});
206+
}
207+
183208
let app = Router::new()
184209
// ── Global endpoints served NATIVELY (no worker, no DB) ──────────────
185210
.route("/", get(serve_index))

‎src/router/proxy.rs‎

Lines changed: 30 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -97,19 +97,16 @@ pub async fn acquire_and_proxy(ctx: &ProxyCtx, repo: &str, req: Request) -> Resp
9797
/// the spawn path). A worker present but mid-request still proxies (fresh data);
9898
/// absent → cold.
9999
pub async fn proxy_if_live(ctx: &ProxyCtx, repo: &str, req: Request) -> Option<Response> {
100-
// Cheap residency check — does NOT spawn. Mirrors the registry's ready set.
101-
if !ctx.registry.ready_repos().await.iter().any(|r| r == repo) {
102-
return None;
103-
}
104-
// A worker is live: fetch its handle (Ready path of acquire is spawn-free
105-
// when the entry is already Ready) and proxy. If it raced to death between
106-
// the check and here, obtain_worker would re-spawn — so guard against that
107-
// by only proceeding on the Ready fast-path; on any miss, fall back to cold.
108-
match ctx.registry.acquire(repo).await {
109-
super::registry::Acquire::Ready(w) => Some(proxy_to(ctx, &w, req).await),
110-
// The worker died in the race window; do NOT spawn for a view route —
111-
// serve cold instead (the caller's None branch).
112-
_ => None,
100+
// NON-MUTATING liveness check. `peek_ready` returns a live worker or `None`,
101+
// reaping a dead `Ready` entry to absent as a side effect — but NEVER
102+
// electing a spawn. (The old `ready_repos()` + `acquire` pair was the
103+
// "stuck Indexing… after idle" bug: `acquire` on a dead `Ready` transitions
104+
// the entry to `Spawning` and returns `SpawnElected`, which this spawn-free
105+
// route discarded — orphaning the entry in `Spawning` forever.)
106+
match ctx.registry.peek_ready(repo).await {
107+
Some(w) => Some(proxy_to(ctx, &w, req).await),
108+
// No live worker (absent, mid-spawn, or just-reaped dead) → serve cold.
109+
None => None,
113110
}
114111
}
115112

@@ -155,14 +152,10 @@ pub async fn forward_json_to_worker(
155152
/// object directly, not an MCP `{result}` envelope). Used by `get_index_status`
156153
/// to read a live worker's authoritative status without spawning.
157154
pub async fn get_json_if_live(ctx: &ProxyCtx, repo: &str, path: &str) -> Option<serde_json::Value> {
158-
// Spawn-free: only proceed if a worker is already Ready.
159-
if !ctx.registry.ready_repos().await.iter().any(|r| r == repo) {
160-
return None;
161-
}
162-
let worker = match ctx.registry.acquire(repo).await {
163-
super::registry::Acquire::Ready(w) => w,
164-
_ => return None, // raced to death — serve cold, don't spawn
165-
};
155+
// Spawn-free liveness via `peek_ready` (reaps a dead `Ready` to absent, never
156+
// elects a spawn). Replaces the old `ready_repos()` + `acquire` pair that
157+
// orphaned dead entries into `Spawning` on a status poll.
158+
let worker = ctx.registry.peek_ready(repo).await?;
166159
let url = format!("http://127.0.0.1:{}{}", worker.port, path);
167160
let resp = ctx.client.get(&url).send().await.ok()?;
168161
if !resp.status().is_success() {
@@ -182,10 +175,23 @@ pub(crate) async fn obtain_worker(ctx: &ProxyCtx, repo: &str) -> Result<Arc<Read
182175
// awaiters; on failure abandon so another request can retry.
183176
match spawn_worker(&ctx.exe, repo, &ctx.worker_args, &ctx.job).await {
184177
Ok(worker) => {
185-
ctx.registry
178+
// publish_ready returns false if this spawn was SUPERSEDED
179+
// — the orphan watchdog reaped our `Spawning` entry (we
180+
// were slow) and a waiter may have re-elected a fresh
181+
// spawn. Our worker is now reachable by nobody yet holds
182+
// the RocksDB LOCK, so we MUST kill it (else it would
183+
// deadlock the re-elected spawn's open_db), then loop to
184+
// re-acquire the new state (Ready, or a fresh Spawning).
185+
if ctx
186+
.registry
186187
.publish_ready(repo, worker.clone(), &ready)
187-
.await;
188-
return Ok(worker);
188+
.await
189+
{
190+
return Ok(worker);
191+
}
192+
warn!(repo = %repo, "spawn superseded (entry reaped/re-elected); killing orphan worker and re-acquiring");
193+
worker.kill_and_wait().await;
194+
continue;
189195
}
190196
Err(e) => {
191197
ctx.registry.abandon_spawn(repo, &ready).await;

0 commit comments

Comments
 (0)