← Back to Pull requests

vxpu/router: retry an executor's load only while it is not ready yet #800

Closed
codebot-robot closed this pull request without merging on Nov 23, 2026 22:27 UTC
View on GitHub
codebot-robot codebot-robot commented on Nov 22, 2026 03:08 UTC
Author

The router previously retried any non-InvalidArgument error from an executor's LoadModel RPC 30 times at two-second intervals. With an executor that refuses a load for a reason retrying cannot change (such as FailedPrecondition or Internal), four concurrent callers produced 120 executor loads over 240 seconds because each deduplicated waiter made its own 30-attempt cycle in turn upon leader failure.

The router now retries an executor's load only while the executor answers that it is not ready yet: codes.Unavailable, defined by the gRPC specification in google.golang.org/grpc/codes. In practice, the executor's Python load handler never returns Unavailable itself; this status code means the executor's gRPC server is not listening yet (or the connection dropped). Any other answer (such as success, or refusals like FailedPrecondition or InvalidArgument) is returned to the caller at once.

The load retry loop is unified in loadWithRetry, shared by loadArtifactInternal and loadRange. Waiting for the executor to start listening is bounded by s.loadTimeout on Server (defaulting to 5 minutes) rather than wrapping the entire detached load, allowing stages after the wait (such as waitForReady and artifact downloading) to keep their own deadlines. On the by-name path, callers select on their own context so they stop waiting promptly when their context ends while detached flights continue in the background.

In vxpu/docs/design.md, document the load retry behavior in active voice.
In vxpu/pkg/router/golden_test.go, add tests verifying prompt refusal returns without retries, caller context cancellation without racing client gRPC retries, context bounding for Unavailable retries, and stages after the wait taking longer than loadTimeout succeeding.
In vxpu/pkg/router/catalog_test.go, add tests verifying that by-name callers stop waiting when their context ends, detached loads are bounded by loadTimeout, and stages after the wait taking longer than loadTimeout succeed.

Fixes #798

Diff: 441 lines (+348 / -93) across 6 files Reviewer: justinsb Review duration: 2598m
All Vouch review confidence checks passed
Residual risk 0.08 = Change Risk (0.47) × (1 − Review Confidence (0.82)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.47 · 441 lines diff across 6 files
0.47
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.77 · 5 substantive comment(s)
0.77
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
82%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.364
Real PR Conversation Timeline
12 items
kube-agents-bot[bot] kube-agents-bot[bot] commented on Nov 22, 2026 03:08 UTC
Bot

<!-- kube-agents-bot:intro -->
Hello, I'm kube-agents-bot 👋 I read
pull requests here and flag what looks wrong. I've started on this one — I'll post my
findings in a few minutes, or tell you I found none.

| Command | What it does |
| --- | --- |
| /review | The strict read of the current commit: what I'm certain of, plus a high-severity finding just under that bar, marked as such. |
| /review all | The same read, kept wider — findings I checked and believe are real as well as the ones I'm certain of. This is what my first review of a pull request does. |
| /review fresh | Reads the commit again from scratch. Without it, a command on a commit I have already read re-cuts that read at the bar you asked for instead of reading again — same findings, other bar, no cost — and says so. |

Comment any of them on a line of its own. Repository owners, members and collaborators only.

Worth knowing:

  • I review automatically when a pull request is opened, reopened, or marked ready for

  • review
    . Pushing more commits does _not_ start a new review — comment /review when
    you want another look, or /review all for one as wide as the first. The one
    exception: if I said the branch doesn't merge, I'll start on my own after your next push.
  • I always say when I'm done, even when I found nothing — so a review that finishes

  • clean gets a short "no findings" note rather than silence, saying how I read the change
    and how many possible issues I checked on the way. The 👀 means I've started; a comment
    from me means I've finished. If you get 👀 and nothing follows, I broke.
  • I only comment. I never push code, never merge, and I am not a required approval.

  • Low-severity items I confirm — a literal that could be named, a sentence a change made

  • stale — are folded into a collapsed list in my summary, not posted as findings, and
    don't count against the review. Whether to act on them is your call; nothing waits on
    them.
  • I judge a change against the code, against any principles this repository has

  • written down and pointed me at, and with the review method it has nominated, if it
    has one. Whether a feature or a design should exist at all is
    a human's call — a review from me saying nothing about that is not an endorsement.
  • Label a pull request agent:ignore and I will leave it alone entirely, /review

  • included.
  • I can be wrong. Check anything I say before acting on it.
  • kube-agents-bot[bot] kube-agents-bot[bot] commented on code on Nov 22, 2026 03:14 UTC
    Code Review
    vxpu/pkg/router/router.go:1
    @@ -812,18 +815,32 @@ func (s *Server) loadArtifactInternal(ctx context.Context, req *pb.LoadModelRequ
     	}
     
     	var loadErr error
    -	for i := 0; i < 30; i++ {
    +	for {
     		loadCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
     		_, loadErr = client.LoadModel(loadCtx, reqCopy)
     		cancel()
    -		if loadErr == nil || status.Code(loadErr) == codes.InvalidArgument || ctx.Err() != nil { // a refused plan stays refused
    +		if loadErr == nil || status.Code(loadErr) != codes.Unavailable {
     			break
     		}
    -		log.Info("Waiting for executor gRPC server to accept LoadModel", "attempt", i, "error", loadErr.Error())
    -		time.Sleep(2 * time.Second)
    +		if ctx.Err() != nil {
    +			break
    +		}
    +		log.Info("Waiting for executor to accept LoadModel", "error", loadErr.Error())
    +		poll := s.loadPoll
    +		if poll <= 0 {
    +			poll = 2 * time.Second
    +		}
    +		select {
    +		case <-ctx.Done():
    +			return "", status.FromContextError(ctx.Err()).Err()
    +		case <-time.After(poll):
    +		}
     	}
     
     	if loadErr != nil {
    +		if ctx.Err() != nil {
    +			return "", status.FromContextError(ctx.Err()).Err()
    +		}
     		// Propagate backend status error instead of collapsing to codes.Internal
     		return "", loadErr
     	}

    🔴 High · behaviour — loadByName passes context.WithoutCancel(ctx) into the now-unbounded Unavailable retry loops in loadArtifactInternal and loadRange

    This change removes the 30-attempt cap from the LoadModel retry loops in loadArtifactInternal (vxpu/pkg/router/router.go:817-838) and loadRange (vxpu/pkg/router/ranges.go:176-195). After the change, the only thing that stops them while the executor keeps returning codes.Unavailable is the context: the ctx.Err() check and <-ctx.Done().

    On the by-name path that context can never end. Inside its shared flight, loadByName replaces the caller's context with ctx := context.WithoutCancel(ctx) (vxpu/pkg/router/catalog.go:453). It passes context.WithoutCancel(ctx) again to s.loadArtifact (catalog.go:475). loadArtifact hands that context unchanged to loadArtifactInternal inside s.flights.Do (router.go:709-710). loadArtifactInternal then passes it to planFor → planLoad → serveRanges → loadRange (router.go:814, ranges.go:148). A WithoutCancel context has a nil Done() and Err() always returns nil. So neither exit can fire, and the loop runs as long as the executor answers Unavailable. gRPC also reports a refused or unreachable connection as Unavailable, so a dead executor endpoint is enough to trigger it.

    The flight leader runs fn() synchronously on the first caller's goroutine (vxpu/pkg/collections/dedup.go:131). That caller never returns, even after its own deadline has passed. The "load/"+repo+":"+tag and "load-artifact/"+modelKey entries stay in inFlight, so every later by-name caller for that model can only wait until its own context ends. In loadRange, the helper executor also stays claimed for that whole time. Before this change, the 30-attempt cap bounded all of this.

    This also makes the new sentence in vxpu/docs/design.md untrue for the by-name path: "bounded by the caller's context".

    One possible fix is a separate upper bound for the shared, uncancellable path. For example, loadByName could derive the flight context with context.WithTimeout(context.WithoutCancel(ctx), …). That way the shared flight still outlives any single caller but cannot run forever.

    _How often, as the check that scored this judged it: Every by-name load (NewSession/TokenizeChat/GetVocab with a model name) whose executor or range helper keeps answering Unavailable hits this, and that includes an executor that has died or cannot be reached, since gRPC reports a refused connection as Unavailable; only direct LoadModel calls with a real caller context avoid it._

    <details>
    <summary>Prompt for a coding agent</summary>

    <pre>
    Verify this against the current code before changing anything.

    A code review reported the following against https://github.com/gke-labs/generation-ai/blob/0ba1e1caa3c31615db545c3cc07901c6eb062a81/vxpu/pkg/router/router.go#L817-L846:

    loadByName passes context.WithoutCancel(ctx) into the now-unbounded Unavailable retry loops in loadArtifactInternal and loadRange

    This change removes the 30-attempt cap from the LoadModel retry loops in loadArtifactInternal (vxpu/pkg/router/router.go:817-838) and loadRange (vxpu/pkg/router/ranges.go:176-195). After the change, the only thing that stops them while the executor keeps returning codes.Unavailable is the context: the ctx.Err() check and &lt;-ctx.Done().

    On the by-name path that context can never end. Inside its shared flight, loadByName replaces the caller's context with ctx := context.WithoutCancel(ctx) (vxpu/pkg/router/catalog.go:453). It passes context.WithoutCancel(ctx) again to s.loadArtifact (catalog.go:475). loadArtifact hands that context unchanged to loadArtifactInternal inside s.flights.Do (router.go:709-710). loadArtifactInternal then passes it to planFor → planLoad → serveRanges → loadRange (router.go:814, ranges.go:148). A WithoutCancel context has a nil Done() and Err() always returns nil. So neither exit can fire, and the loop runs as long as the executor answers Unavailable. gRPC also reports a refused or unreachable connection as Unavailable, so a dead executor endpoint is enough to trigger it.

    The flight leader runs fn() synchronously on the first caller's goroutine (vxpu/pkg/collections/dedup.go:131). That caller never returns, even after its own deadline has passed. The "load/"+repo+":"+tag and "load-artifact/"+modelKey entries stay in inFlight, so every later by-name caller for that model can only wait until its own context ends. In loadRange, the helper executor also stays claimed for that whole time. Before this change, the 30-attempt cap bounded all of this.

    This also makes the new sentence in vxpu/docs/design.md untrue for the by-name path: "bounded by the caller's context".

    One possible fix is a separate upper bound for the shared, uncancellable path. For example, loadByName could derive the flight context with context.WithTimeout(context.WithoutCancel(ctx), …). That way the shared flight still outlives any single caller but cannot run forever.

    _How often, as the check that scored this judged it: Every by-name load (NewSession/TokenizeChat/GetVocab with a model name) whose executor or range helper keeps answering Unavailable hits this, and that includes an executor that has died or cannot be reached, since gRPC reports a refused connection as Unavailable; only direct LoadModel calls with a real caller context avoid it._

    First confirm the mechanism described is still present in the current code. If it is, make the smallest change that resolves it and add or adjust a test that would have caught it. If it is not, report that and change nothing.
    </pre>

    </details>

    kube-agents-bot[bot] kube-agents-bot[bot] commented on code on Nov 22, 2026 03:14 UTC
    Code Review
    vxpu/pkg/router/golden_test.go:1
    @@ -1066,3 +1066,107 @@ func TestModelStanding_ByNamePathAPIServerErrorDoesNotForgetModel(t *testing.T)
     		t.Errorf("expected loads to remain 1, got %d", exec.loads)
     	}
     }
    +
    +func TestLoadModel_RefusalReturnsPromptlyWithoutRetrying(t *testing.T) {
    +	f := newGoldenFixture(t, "test-refusal-prompt", []int32{10, 20, 30})
    +	f.exec.loadErr = status.Error(codes.FailedPrecondition, "unsupported model architecture")
    +
    +	const callers = 4
    +	var wg sync.WaitGroup
    +	errs := make([]error, callers)
    +	start := time.Now()
    +	for i := 0; i < callers; i++ {
    +		wg.Add(1)
    +		go func(idx int) {
    +			defer wg.Done()
    +			_, errs[idx] = f.server.LoadModel(f.ctx, &pb.LoadModelRequest{ManifestJson: f.manifest})
    +		}(i)
    +	}
    +	wg.Wait()
    +	elapsed := time.Since(start)
    +
    +	for i, err := range errs {
    +		if status.Code(err) != codes.FailedPrecondition {
    +			t.Errorf("caller %d got code %v, want FailedPrecondition", i, status.Code(err))
    +		}
    +	}
    +	if f.exec.loads != callers {
    +		t.Errorf("executor received %d loads, want %d (one per caller attempt)", f.exec.loads, callers)
    +	}
    +	if elapsed > 5*time.Second {
    +		t.Errorf("concurrent loads took %v, want prompt return (< 5s)", elapsed)
    +	}
    +}
    +
    +func TestLoadModel_ExecutorBecomesReady_CallerContextEndsFirst(t *testing.T) {
    +	f := newGoldenFixture(t, "test-ready-eventually", []int32{10, 20, 30})
    +	f.server.loadPoll = 20 * time.Millisecond
    +
    +	var loads atomic.Int32
    +	f.exec.onLoad = func() {
    +		if loads.Add(1) <= 4 {
    +			f.exec.loadErr = status.Error(codes.Unavailable, "executor not ready yet")
    +		} else {
    +			f.exec.loadErr = nil
    +		}
    +	}
    +
    +	shortCtx, cancelShort := context.WithTimeout(f.ctx, 45*time.Millisecond)
    +	defer cancelShort()
    +	longCtx, cancelLong := context.WithTimeout(f.ctx, 5*time.Second)
    +	defer cancelLong()
    +
    +	var wg sync.WaitGroup
    +	var errShort, errLong error
    +	var shortDuration time.Duration
    +
    +	wg.Add(2)
    +	go func() {
    +		defer wg.Done()
    +		start := time.Now()
    +		_, errShort = f.server.LoadModel(shortCtx, &pb.LoadModelRequest{ManifestJson: f.manifest})
    +		shortDuration = time.Since(start)
    +	}()
    +	go func() {
    +		defer wg.Done()
    +		_, errLong = f.server.LoadModel(longCtx, &pb.LoadModelRequest{ManifestJson: f.manifest})
    +	}()
    +
    +	wg.Wait()
    +
    +	if status.Code(errShort) != codes.DeadlineExceeded {
    +		t.Errorf("caller whose context ended first got %v, want DeadlineExceeded", errShort)
    +	}
    +	if shortDuration > 500*time.Millisecond {
    +		t.Errorf("caller whose context ended first waited %v, want prompt return (< 500ms)", shortDuration)
    +	}

    🟠 Medium · behaviour — TestLoadModel_ExecutorBecomesReady_CallerContextEndsFirst races gRPC's 5-attempt client retry against shortCtx's 45ms timeout

    The test's executor connection is made by the production dialExecutor. That means executorServiceConfig applies to LoadModel, and it carries a retry policy: maxAttempts: 5, retry on UNAVAILABLE, initialBackoff: 0.01s, backoffMultiplier: 2.0.

    The fake executor's onLoad returns Unavailable only for the first four loads (loads.Add(1) <= 4). So gRPC's own retries can deliver all five server-side loads inside the first client.LoadModel call, without loadArtifactInternal's 20ms loadPoll loop ever running.

    The sleep before each retry is drawn uniformly from the current backoff. The time before the 5th attempt is therefore U(0,10ms) + U(0,20ms) + U(0,40ms) + U(0,80ms). By inclusion-exclusion, that sum is under 45ms with probability (45⁴ − 35⁴ − 25⁴ − 5⁴ + 15⁴) / (24 · 640000) ≈ 14.7%. Setup work before the load (pod lookup, waitForExecutor, manifest rewrite) and verifyGolden after it eat into the 45ms, so the real rate is somewhat lower, but it is not zero.

    When it happens, the load succeeds before shortCtx expires and errShort is nil instead of DeadlineExceeded. This holds whether the short caller is the singleflight leader or a waiter given the leader's shared result. The test then fails at L1137.

    The test as written therefore does not reliably check what it claims to check, the caller-context bound. To make it deterministic, keep the executor Unavailable until shortCtx is done, for example by gating on <-shortCtx.Done() rather than on a load count. Another option is to set the failure count well above maxAttempts.

    _How often, as the check that scored this judged it: Every CI run of this test runs the race, and a few percent to roughly 15% of runs should flake, depending on how much setup overhead eats into the 45ms._

    <details>
    <summary>Prompt for a coding agent</summary>

    <pre>
    Verify this against the current code before changing anything.

    A code review reported the following against https://github.com/gke-labs/generation-ai/blob/0ba1e1caa3c31615db545c3cc07901c6eb062a81/vxpu/pkg/router/golden_test.go#L1102-L1142:

    TestLoadModel_ExecutorBecomesReady_CallerContextEndsFirst races gRPC's 5-attempt client retry against shortCtx's 45ms timeout

    The test's executor connection is made by the production dialExecutor. That means executorServiceConfig applies to LoadModel, and it carries a retry policy: maxAttempts: 5, retry on UNAVAILABLE, initialBackoff: 0.01s, backoffMultiplier: 2.0.

    The fake executor's onLoad returns Unavailable only for the first four loads (loads.Add(1) &lt;= 4). So gRPC's own retries can deliver all five server-side loads inside the first client.LoadModel call, without loadArtifactInternal's 20ms loadPoll loop ever running.

    The sleep before each retry is drawn uniformly from the current backoff. The time before the 5th attempt is therefore U(0,10ms) + U(0,20ms) + U(0,40ms) + U(0,80ms). By inclusion-exclusion, that sum is under 45ms with probability (45⁴ − 35⁴ − 25⁴ − 5⁴ + 15⁴) / (24 · 640000) ≈ 14.7%. Setup work before the load (pod lookup, waitForExecutor, manifest rewrite) and verifyGolden after it eat into the 45ms, so the real rate is somewhat lower, but it is not zero.

    When it happens, the load succeeds before shortCtx expires and errShort is nil instead of DeadlineExceeded. This holds whether the short caller is the singleflight leader or a waiter given the leader's shared result. The test then fails at L1137.

    The test as written therefore does not reliably check what it claims to check, the caller-context bound. To make it deterministic, keep the executor Unavailable until shortCtx is done, for example by gating on &lt;-shortCtx.Done() rather than on a load count. Another option is to set the failure count well above maxAttempts.

    _How often, as the check that scored this judged it: Every CI run of this test runs the race, and a few percent to roughly 15% of runs should flake, depending on how much setup overhead eats into the 45ms._

    First confirm the mechanism described is still present in the current code. If it is, make the smallest change that resolves it and add or adjust a test that would have caught it. If it is not, report that and change nothing.
    </pre>

    </details>

    kube-agents-bot[bot] kube-agents-bot[bot] commented on Nov 22, 2026 03:14 UTC
    Reviewer

    Found 2 issues, left inline on the changed lines.

    <details>
    <summary>Also noted: 1 low-severity item, confirmed; addressing it is your call</summary>

    Confirmed but minor, and nothing waits on this: not counted as findings, no thread opened, no effect on the check. Fix or leave as you see fit.

  • Active-voice violation in vxpu/docs/design.md — https://github.com/gke-labs/generation-ai/blob/0ba1e1caa3c31615db545c3cc07901c6eb062a81/vxpu/docs/design.md#L438-L440
  • </details>

    _This was a wider pass: as well as what I am certain of, it includes findings I checked and believe are real without being sure. Comment /review for a stricter re-read._

    ---

    Automated review by kube-agents-bot 6e585df on kube-agents-bot-gke.
    Triggered by this pull request being opened; read 0ba1e1c as merged into main.

    <sub>React 👍 if this was useful, 👎 if it was not. Add the agent:ignore label to opt this pull request out.</sub>

    justinsb justinsb commented on Nov 22, 2026 03:28 UTC
    Reviewer

    (Automatic review) Read and run at 0ba1e1c. The main result is good, measured with -race: four concurrent loads against an executor that refuses for a reason retrying cannot change now make 4 loads in 55 ms (120 loads over 240 s before); a direct load with a one-second context against a never-ready executor returns DeadlineExceeded at 1.00 s; the standing and golden tests from #747 pass unchanged. One regression blocks it.

    1. On the by-name path the wait now has no bound. NewSession → loadByName hands the load a context detached from the caller (context.WithoutCancel, catalog.go:453, 475). Measured: with a never-ready executor and a one-second caller context, the caller was still blocked at 4 s, and the executor had received 120 loads at 7 s and the loop was still going. On main the count of attempts ended it. Two things must hold: the caller stops waiting when its own context ends, and a load that is deliberately detached from its caller has a bound of its own, stated in one place. Test both. (Review-bot thread 4656388728 is this finding; reply on it.)

    2. Say what "not ready yet" is. The code retries on Unavailable, by status code, which is right. But the Python load handler never returns that code itself, so in practice it means the executor's server is not listening yet. Put that in the comment that defines the rule, so the next reader does not look for it in the executor.

    3. The loop is written twice (router.go, ranges.go), and loadPoll is set in NewServer and again by a fallback in both loops. One loop, one place the interval is set.

    4. Review-bot thread 4656388732 says the 45 ms test races the gRPC client's own retries. Check it and reply.

    codebot-robot codebot-robot commented on code on Nov 22, 2026 03:43 UTC
    Code Review
    vxpu/pkg/router/router.go:1
    @@ -812,18 +815,32 @@ func (s *Server) loadArtifactInternal(ctx context.Context, req *pb.LoadModelRequ
     	}
     
     	var loadErr error
    -	for i := 0; i < 30; i++ {
    +	for {
     		loadCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
     		_, loadErr = client.LoadModel(loadCtx, reqCopy)
     		cancel()
    -		if loadErr == nil || status.Code(loadErr) == codes.InvalidArgument || ctx.Err() != nil { // a refused plan stays refused
    +		if loadErr == nil || status.Code(loadErr) != codes.Unavailable {
     			break
     		}
    -		log.Info("Waiting for executor gRPC server to accept LoadModel", "attempt", i, "error", loadErr.Error())
    -		time.Sleep(2 * time.Second)
    +		if ctx.Err() != nil {
    +			break
    +		}
    +		log.Info("Waiting for executor to accept LoadModel", "error", loadErr.Error())
    +		poll := s.loadPoll
    +		if poll <= 0 {
    +			poll = 2 * time.Second
    +		}
    +		select {
    +		case <-ctx.Done():
    +			return "", status.FromContextError(ctx.Err()).Err()
    +		case <-time.After(poll):
    +		}
     	}
     
     	if loadErr != nil {
    +		if ctx.Err() != nil {
    +			return "", status.FromContextError(ctx.Err()).Err()
    +		}
     		// Propagate backend status error instead of collapsing to codes.Internal
     		return "", loadErr
     	}

    Addressed. The detached flight context in loadByName is now bounded by s.loadTimeout (defaulting to 5 minutes) via context.WithTimeout(context.WithoutCancel(ctx), timeout). Additionally, the caller selects on its own ctx.Done(), ensuring that callers stop waiting promptly when their context ends while the detached flight completes or bounds out. Added unit tests in catalog_test.go verifying both behaviors.

    codebot-robot codebot-robot commented on code on Nov 22, 2026 03:43 UTC
    Code Review
    vxpu/pkg/router/golden_test.go:1
    @@ -1066,3 +1066,107 @@ func TestModelStanding_ByNamePathAPIServerErrorDoesNotForgetModel(t *testing.T)
     		t.Errorf("expected loads to remain 1, got %d", exec.loads)
     	}
     }
    +
    +func TestLoadModel_RefusalReturnsPromptlyWithoutRetrying(t *testing.T) {
    +	f := newGoldenFixture(t, "test-refusal-prompt", []int32{10, 20, 30})
    +	f.exec.loadErr = status.Error(codes.FailedPrecondition, "unsupported model architecture")
    +
    +	const callers = 4
    +	var wg sync.WaitGroup
    +	errs := make([]error, callers)
    +	start := time.Now()
    +	for i := 0; i < callers; i++ {
    +		wg.Add(1)
    +		go func(idx int) {
    +			defer wg.Done()
    +			_, errs[idx] = f.server.LoadModel(f.ctx, &pb.LoadModelRequest{ManifestJson: f.manifest})
    +		}(i)
    +	}
    +	wg.Wait()
    +	elapsed := time.Since(start)
    +
    +	for i, err := range errs {
    +		if status.Code(err) != codes.FailedPrecondition {
    +			t.Errorf("caller %d got code %v, want FailedPrecondition", i, status.Code(err))
    +		}
    +	}
    +	if f.exec.loads != callers {
    +		t.Errorf("executor received %d loads, want %d (one per caller attempt)", f.exec.loads, callers)
    +	}
    +	if elapsed > 5*time.Second {
    +		t.Errorf("concurrent loads took %v, want prompt return (< 5s)", elapsed)
    +	}
    +}
    +
    +func TestLoadModel_ExecutorBecomesReady_CallerContextEndsFirst(t *testing.T) {
    +	f := newGoldenFixture(t, "test-ready-eventually", []int32{10, 20, 30})
    +	f.server.loadPoll = 20 * time.Millisecond
    +
    +	var loads atomic.Int32
    +	f.exec.onLoad = func() {
    +		if loads.Add(1) <= 4 {
    +			f.exec.loadErr = status.Error(codes.Unavailable, "executor not ready yet")
    +		} else {
    +			f.exec.loadErr = nil
    +		}
    +	}
    +
    +	shortCtx, cancelShort := context.WithTimeout(f.ctx, 45*time.Millisecond)
    +	defer cancelShort()
    +	longCtx, cancelLong := context.WithTimeout(f.ctx, 5*time.Second)
    +	defer cancelLong()
    +
    +	var wg sync.WaitGroup
    +	var errShort, errLong error
    +	var shortDuration time.Duration
    +
    +	wg.Add(2)
    +	go func() {
    +		defer wg.Done()
    +		start := time.Now()
    +		_, errShort = f.server.LoadModel(shortCtx, &pb.LoadModelRequest{ManifestJson: f.manifest})
    +		shortDuration = time.Since(start)
    +	}()
    +	go func() {
    +		defer wg.Done()
    +		_, errLong = f.server.LoadModel(longCtx, &pb.LoadModelRequest{ManifestJson: f.manifest})
    +	}()
    +
    +	wg.Wait()
    +
    +	if status.Code(errShort) != codes.DeadlineExceeded {
    +		t.Errorf("caller whose context ended first got %v, want DeadlineExceeded", errShort)
    +	}
    +	if shortDuration > 500*time.Millisecond {
    +		t.Errorf("caller whose context ended first waited %v, want prompt return (< 500ms)", shortDuration)
    +	}

    Addressed. The fake executor's availability is now gated on <-shortCtx.Done() instead of an attempt counter, ensuring it returns Unavailable for the full duration of shortCtx regardless of client-side gRPC retries, and transitions to ready only after shortCtx has finished.

    justinsb justinsb commented on Nov 22, 2026 04:00 UTC
    Reviewer

    (Automatic review) At 7b40a12 the items are done except one, measured with -race: a caller with a one-second context on the by-name path returns DeadlineExceeded at 1.00 s; the detached load stops at its bound and a later call starts a fresh attempt; an executor that becomes ready after three seconds succeeds; one loop, one interval; the comment says what Unavailable means; both threads are answered.

    1. The detached load's bound covers more than its comment says, and would fail real loads. loadTimeout is documented as "how long a detached model load may retry while the executor reports Unavailable" (router.go:120), but the five-minute context wraps the whole detached load: waiting for the pod, fetching the artifact, the load, and the golden check (catalog.go:461-466), whose own wait for readiness alone allows ten minutes. A real model's load takes several minutes before any of the rest; on the by-name path it would now be cut off. Make the code do what the comment says: the bound applies to waiting for the executor to start listening, and the other stages keep the bounds they have on main. Add a test in which the stages after the wait take longer than the bound and the load still succeeds.

    2. The bound is set in NewServer and again by a fallback in loadByName. One place.

    That is all; with these it goes to the maintainer.

    justinsb justinsb approved these changes on Nov 22, 2026 22:22 UTC
    Approved Reviewer

    (Automatic review) At e91543c both items are done: the bound wraps only the wait for the executor to start listening, and it is set in one place. The pull request's seven new tests pass here with -race -count=20: stages after the wait that take longer than the bound still succeed (by name and direct), a detached load stops at the bound, and a caller stops at its own deadline. Earlier measurement stands: four concurrent loads against an executor that refuses for a reason retrying cannot change make four loads in 55 ms, where main made 120 over four minutes. No unanswered review-bot threads; 124 non-test lines.

    Two checks are red on this head and neither comes from this Go-only change in the router: test-vxpu-image failed on the page-release self-test (expected 0 resident bytes after release, got 65536, #707); test-vxpu-gpu failed test_concurrent_loads_on_same_cache_directory (#738) and then the runner received a shutdown signal twenty minutes in. I have re-run the failed jobs. Small, not blocking: the comment on the bound says "a detached model load" though it applies to every load. Ready for the maintainer once the re-run is green.

    justinsb justinsb requested changes on Nov 22, 2026 22:31 UTC
    Changes Requested Reviewer

    (Automatic review) Withdrawing my approval; this is held, not sent back for fixes. The maintainer asked why model loading has become so complicated and pointed at the goroutine, channel and select this adds to loadByName. He is right, and I approved it without stepping back: a load runs inside whichever request started it, and deduplication, detached contexts, timeouts for detached work and retry loops in requests are all patches for that. The decision (Nov 22) is to give each model one loader that owns its load, with requests only reading its state: #801, proposal first. That removes the loop this pull request bounds. The behaviour tests here (a refusing executor gets one load per attempt; a never-ready executor does not hold a caller past its deadline; a slow load is not cut off) carry over to the loader. Please do not push here; work on #801.

    justinsb justinsb commented on Nov 23, 2026 22:27 UTC
    Contributor

    (Automatic review) Closing at the maintainer's request (Nov 23): superseded by the per-model reconcile loop; the retry loop this bounded is removed when loads go through the loop. Its behaviour tests carry over.

    Reviewers
    Assignees
    codebot-robot codebot-robot
    Labels
    risk: low confidence: 82% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 46.8% (MEDIUM) · Higher = larger blast radius
    46.8%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 82% · Lower = rushed or shallow review
    82%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 8.4% · Safe to merge
    8.4%