Skip to content

fix(routing): size the streaming engine wait on the request's own un-cached prefill - #1637

Open
B-A-M-N wants to merge 22 commits into
HarvardMadSys:devfrom
B-A-M-N:bamn/routing/prefill-offload-deadlines
Open

B-A-M-N wants to merge 22 commits into
HarvardMadSys:devfrom
B-A-M-N:bamn/routing/prefill-offload-deadlines

Conversation

@B-A-M-N

@B-A-M-N B-A-M-N commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

What

Sizes the streaming engine-wait deadline on the request's own un-cached prefill
instead of a fixed constant, and keeps the wait bounded and calibrated.

The fixed 0.8 s engine deadline measured on staging cancels valid cold
prefills: a large prompt that simply needs more than 0.8 s of GPU prefill gets
an EngineWaitExpired cancellation and is offloaded to a remote provider —
paying remote-token cost to redo, more slowly, work the local engine was about
to finish. This PR replaces the constant with a per-request budget:

  • _engine_wait_tokens computes the deadline from the strict un-cached
    estimate for this endpoint and this conversation — hint tokens count
    only when the endpoint actually holds this conversation's prefix (fingerprint
    match, prompt anchor hold); anything else charges in full. The strict
    semantics already live in uncached_estimate on dev; no selection-side
    changes are involved, and the branch was built and qualified independently of
    the locality-selection PR.
  • The wait is an offset from the moment prefill starts, not a wall-clock
    cap from request arrival, so queue time no longer eats the engine budget
    (engine_wait and queue_wait stay separately attributable — an offload
    caused by queue pressure must keep being counted as a queue offload).
  • Tail calibration from measured staging cold-prefill times replaces the
    nominal per-token rate, so the largest expected prefills get enough budget
    without loosening the bound for everyone else.
  • Cancellation before first token still exists and is still bounded; it just
    fires when the engine is genuinely stalled, not when the prompt was merely
    large. The bounded-wait invariants (deadline never negative, never
    unbounded, queue-vs-engine attribution preserved) are regression-tested at
    the router level.

Branch repair (this head)

The previous head (b5e3a3dc) did not contain a merge of dev: its working
tree had been overwritten with an upstream snapshot, so the branch carried
1,258 changed files / 215,319 additions against a scope of six files, its
merge base was 84bda1a2, and no CI had run on it.

This head repairs that without a force-push:

  • The engine-wait change was reconstructed on current dev (c8dc56c5) and
    merged into this branch as a fast-forward (b5e3a3dc..cff9f47c). The
    branch keeps its history, dev is genuinely an ancestor, and the diff
    against dev is now the six files the feature touches:
    routing/engine_wait.py, routing/offload.py, routing/routers.py,
    serving/config/app_config_registry.py, and the two routing test modules.
  • Two corrections to the earlier head:
    • The extension setting is read with the repository's boolean parser.
      Reading it as "anything that is not the string 0 is on" made the stored
      spelling false — and any value an administrator mistyped — switch the
      behaviour on. The registry entry is now a plain boolean for the same
      reason: a flag reads as value != "0", so the console and the runtime
      would otherwise disagree. An unusable value keeps the default, which is
      off.
    • The ceiling tests state the condition they depend on. They passed
      only because another test's teardown left the extension reading "on"
      through that same mis-parse, so they were asserting against leaked state.

The behaviour change still ships dark: the extension is off until an operator
turns it on with the setting, and setting it back to off restores the
configured base wait without a restart or a route edit.

Tests

  • tests/unit/routing/test_engine_wait_routing.py — warm continuation,
    stale hint (full budget restored), unrelated conversation on the same key
    (full charge), large-prompt ceiling, queue-wait attribution, bounded-wait
    invariants.
  • tests/unit/routing/test_offload_routing.py — offload cause accounting
    under the offset-form wait, the calibrated tail, the boolean setting's
    spellings (0/1/false/true/on/off/yes/no), malformed values
    (fail closed), a missing value, and the live rollback.

Local qualification on this exact tree: make lint clean; make test
13,662 passed, 5 skipped, 0 failed.

Exact-head GitHub Actions run 42800037401
passed every job, including the CI Gate, the four test shards, the PostgreSQL
integration shard, Backend Quality, Frontend Quality, both Docker builds, Site
UI Containers, Tutorial E2E, Security Scan and change classification.

Three failures in tests/unit/ops/test_classify_changes.py appear when the
suite runs with this machine's global git hook (~/.githooks) active: the
hook rejects the ci@example.com identity the test uses in its temporary
repositories. They reproduce identically on pristine dev with no branch
changes and all pass with the hook bypassed, so they are an artifact of this
machine's configuration, not of this branch.

Verification status

The results above are local checks on this branch. They are not staging
qualification. This PR has not been run against staging, so it makes no claim
about real cache reuse, offload behavior, latency, or throughput.

The dated staging review document named in earlier drafts is not included in
this PR. The comparison it described was a prepared plan, not a completed
staging experiment. Staging qualification remains outstanding and requires an
authorized deployment and comparison before rollout. The extension is not
enabled anywhere by this PR.

Compatibility

No storage, migration, or required-configuration changes; revert restores the
fixed 0.8 s deadline.

Measured, authorized client-side evidence for the glm-5.3-flash prefix-reuse
question: the route has two provider endpoints (vllm, ollama); the cache-capable
one never reuses below ~4.2k prefix tokens and caps reuse at prompt - ~4.1k;
normal routing reaches it for only 44-50% of eligible requests; production
reuses 98.7% of the same 2.6k-token prompt. Records what is external to this
repository and which admin-only fact is still missing.
Pins the observed alternation to runs rather than independent draws, which is
the shape of a lost pin re-drawn onto the cache-blind endpoint.
The offload route's engine wait was a flat `wait_seconds` (0.8 s on staging)
applied to the quantity "prefill + time-to-first-token". That quantity grows
with the prompt's un-cached length, so the deadline fired hardest exactly when
the engine was doing the most legitimate work: a cold prefill of a long prompt.
On expiry the attempt is cancelled, which closes the stream and aborts the
request inside the engine; the prefill already done is discarded and the prompt
is prefilled from scratch on the offload route, which shares no KV with the
engine that was answering. That is duplicated work and a guaranteed cache miss,
and it is the mechanism behind the observed "complete non-caching" on the
offloaded fraction of staging traffic.

Make the wait a function of the work it bounds:

- `OffloadPolicy.engine_wait_seconds(uncached_tokens)` keeps `wait_seconds` as
  the floor (a warm continuation prefills only its delta and is unaffected),
  scales with the un-cached estimate above `OFFLOAD_PREFILL_CREDIT_TOKENS`
  (4096), and is capped at `OFFLOAD_MAX_WAIT_SECONDS` (8 s) so a wedged engine
  still fails over.
- `FixedRouter._watch_for` builds the watch from that value; the primary and
  fallback streaming attempts both pass the endpoint's
  `PrefillLoadTracker.uncached_estimate`.

Unchanged: the gateway queue-wait trigger, `engine_queue_limit`/`EngineHold`,
the last-resort path, `FallbackOrder`'s retry of a cut-short route, circuit
breaker and cancellation semantics, and `max_input_tokens`. Offloading is not
disabled and no endpoint is pinned.

Independent of the `include_usage_in_stream` capability commit: no shared file,
and it can be cherry-picked to its own branch.

Tests: the policy value (floor, proportionality, ceiling, no shortening above
the ceiling); a long cold prefill served locally with `cancelled == 0`; a short
prompt still offloading at the base wait; and a fallback stream watched under
its own budget. Reverting the deadline to a flat base makes the two cold-prefill
tests fail with `route_offload reason="engine_wait"`.

Not pushed, not deployed; no staging configuration changed.
Adds the console-read routing table (three candidates, `ollama.com` as the
offload route with its 0.8s trigger), the full offload lifecycle trace with
precise answers about when the timer starts, what pauses it, what a first token
is, and that the gateway does cancel a prefill that was about to complete, plus
the two corrections implemented on this branch and the state of the ~4.1k-token
head that remains open.
Ran the decisive experiments against both deployments instead of leaving the
~4.1k-token head open:

- second of two identical requests, staging pinned to vllm and production
  unpinned, at 1819/4519/9119/18319 tokens: production reports exactly the same
  cached values as staging (0, 0, 4608, 13824) with the same ~4.5k tail;
- changing only the head of the prompt drops cached to 0, changing only the tail
  leaves it unchanged -- head-anchored block-hash prefix matching, physically
  real;
- TTFT halves when the prefix is reused (1517 -> 720 ms; 1519 -> 787 ms);
- max_tokens is irrelevant (8 vs 512 vs 1), so the un-reused tail is not a
  generation-side reservation;
- the tail is not constant (2375-4511 depending on the run), so the boundary is
  capacity/scheduling dependent rather than a configured threshold.

Corrects F3 and the recommendation: the earlier "production reuses 2560/2595"
reading does not reproduce (production at 2809 tokens also reports 0), so it was
a different route instance rather than a deployment-wide property. No gateway
change can make a prompt shorter than one engine prefill chunk reuse; the two
levers the gateway owns are already implemented.
The engine wait said `max(base, base * uncached / credit)`, which gives a prompt
of exactly one credit -- 4.1k tokens -- the base and nothing more. Replayed over
the measured staging prefills (pinned vLLM), that rule cancels 3 of 27 successful
requests: twelve cold 2.6k requests completed in 0.49-0.97 s under the 0.80 s
floor, so two of them crossed it, and at 9.1k the 1.78 s budget sat ten
milliseconds under a measured 1.79 s. The deadline was sized on a mean, and the
cancellations happen in the tail.

The new wait *offsets* the base instead of scaling it:
`base * (1 + uncached / credit)`. The base is the fixed allowance (queueing,
scheduling, first decode) and each credit of un-cached prefill buys another base
wait of it. At the 0.8 s staging base that budget is above every measured
sample, with headroom from 1.36x at the 2.6k tail to 2.45x at 18.3k, and none of
the 27 cancels. 8 s stays the ceiling: about the extrapolated cold prefill of a
100k-token prompt, and well under the contended remote TTFT already observed
(30-49 s). The constant is a conservative bound rather than a fitted rate --
9.1k and 18.3k both land at ~1.5-1.8 s, which looks like a scheduling quantum.

Evidence scope (the review's P1a, on the wait path). The budget was sized on the
loose caller-scoped hint, so a sibling conversation on the same API key read as
warm and got a *shorter* wait -- exactly the cancellation this change exists to
remove. `_engine_wait_tokens` now requires the conversation fingerprint, and
charges a request it cannot identify in full; the ceiling bounds the cost of
that conservatism. Both the primary and fallback watch sites use it.

Queue waiting is unchanged and still bounded by the configured `wait_seconds`:
the tracked test holds the limiter slot and shows a 100k-token prompt leaving
the gateway queue at 0.05 s while its engine budget would have been ~1.27 s.

Tests: value tests for the offset form against the measured prefill times
including the 2.6k tail; behavioural tests for a warm continuation (sized on its
delta), a stale hint (forget_endpoint restores the full budget), an unrelated
conversation on the same key (full budget, not the sibling's), a large prompt
(ceiling), and the unchanged queue wait. Mutation (loose evidence) fails the
unrelated-conversation test.

Verified: tests/unit/routing 1413 passed, 2 skipped; make lint clean.
The review record still described the first revision of both corrections and
one reading the new measurements withdrew.

Corrected in place:

- The "production reuses 98.7 % of a 2.6k prefix" reading is marked superseded.
  Re-running it against both live deployments gives `cached = 0` at 1 819 and
  2 809 tokens and identical values on both at 9 119 / 18 319, so the short
  prefix boundary is the engine's, not staging's. The consequence and
  "what is external" sections were rewritten to match; the earlier claim that
  eligibility was a deployment difference is withdrawn.
- The engine-wait section now documents the offset form
  (`base * (1 + uncached / credit)`) with the measured prefill table that
  motivates it, the evidence requirement on the wait path, and the audit of
  what was deliberately left alone (queue wait, ceiling, breakers).
- The locality section documents the two independent gates: strict evidence
  (fingerprint + anchor, skipped rather than guessed without one) and authority
  (`LOCALITY_MIN_WEIGHT_SHARE`, 90/10 stays on the 90).
- The recommendation no longer proposes reweighting `zai`: a first turn has no
  prefix anywhere, so ordinary weighted selection is correct for it.
- New section: the controlled staging comparison that must be run after
  deployment, with the three prerequisites that block it, the three phases, the
  metric/pass-condition table, and the reproduce command. It states explicitly
  that no improvement is measured.

Docs only; the code and tests are in the two preceding commits.
…ured tail

The earlier record stated the case for the offset form from the mean prefill
time (0.86 s at 4.5k) and a marginal cost of ~83 us/token. Both were wrong: at
4.5k the old proportional budget was 0.88 s, i.e. still above the mean, and the
sample does not fit a straight line.

What the measured samples actually show, and what the rule was mis-sized
against, is the tail:

- twelve cold 2.6k requests completed in 0.49-0.97 s under a 0.80 s floor, so
  2/12 successful prefills would have been cancelled by the old rule;
- at 9.1k the 1.78 s budget sat ten milliseconds under a measured 1.79 s;
- replaying both rules over all 27 measured successful prefills, the old rule
  cancels 3 and the new one 0.

The doc now carries that replay table, states the tightest headroom honestly
(1.36x at the 2.6k tail, against 1.44x at 9.1k and 2.45x at 18.3k), and notes
that 9.1k and 18.3k both land at ~1.5-1.8 s, which looks like a scheduling
quantum rather than token-proportional cost. The constant is documented as a
conservative bound, not a measured rate.

Code and test docstrings updated to match; the test now also asserts the 2.6k
tail sample it previously left out.
The staging comparison stays prepared-not-run, but the policy comparison did
not have to wait for it: the real FixedRouter, PrefillLoadTracker and
OffloadPolicy were driven against simulated engines calibrated to the measured
9.1k cold tail (1.79 s) and the measured 1.8 s remote TTFT.

Result, at the policy level only: the old proportional wait cancels the seed
prefill 10 ms before it finishes, which prevents the prefix from ever forming,
so all four requests of a warm conversation go cold to the remote route (4/4
offloaded, ~3.6 s each); the offset wait serves the seed locally and the three
continuations at ~21 ms. Under a deep engine queue both rules shed the same 7
of 8, but the longer budget departs them ~0.8 s later -- the old rule was
better at shedding load fast, and that cost is now recorded.

Selection-layer probes: distinct conversations with no affinity split 6/2
(cache-blind), a burst under one shared API key converges via the pre-existing
affinity pin, and 16 concurrent 11k prefills collapse through the elephant
gate. In one process the locality term is the pin's backup, not its
replacement.
dev advanced to 9b48afd (HarvardMadSys#1627 cache-count profiles, HarvardMadSys#1628 Next.js) and
HarvardMadSys#1632 joined the route-editing family; no file overlap with this branch.
HarvardMadSys#1609/HarvardMadSys#1616 carry CHANGES_REQUESTED, HarvardMadSys#1462/HarvardMadSys#1502 keep their open threads.

Capability loader vs the runtime admin paths: YAML routes re-derive the
flag, runtime routes copy the template's value (kind default pinned as
declared), and an edit that repoints a route at a different kind keeps
the copied value instead of the new kind's default -- the capability
schema HarvardMadSys#1630 is reshaping is the right home for that; recorded, not
patched across their open PRs. Restore falls back to template or kind
default because the row persists only the four declared capabilities.

Hot-path composition with HarvardMadSys#1462/HarvardMadSys#1461, measured: fingerprint and anchor
hashing run before the routing transaction; inside it only the per-warm-
candidate anchor re-verification remains, bounded (~3 ms worst case at
500k tokens), no provider I/O anywhere in the critical section.
…e scratch commands

Two review corrections before publication. The rollback row for the
usage-capability PR claimed reverting it stops sending stream_options
unless a route declares it; in fact those six usage-capable kinds
resume dev's original unconditional include_usage default on revert,
and the per-route explicit override (including false) is removed with
the PR. And the two Reproduce sections pointed at .tmp-probe scratch
that is deliberately not committed: they are now labeled as historical
local procedures, with independently executable unit-level and
deployment-level verification recorded in their place.
@B-A-M-N

B-A-M-N commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Advancing this for review, but it should not go to production before staging evidence.

What passed in the checks I ran. The per-request sizing is correct: the deadline comes from the strict un-cached estimate for this endpoint and this conversation (routers.py around 2150-2180), the wait is capped on every path (engine_wait_seconds = base x (1 + un-cached/4096), capped at 8s), and an expired wait raises EngineWaitExpired without opening the circuit breaker.

The one thing that needs staging evidence. A wedged-but-healthy engine now holds a cold large prompt for up to 8s instead of failing over after ~0.8s - roughly a 10x worst-case time-to-first-token regression, and a deliberate one: the old constant cancelled valid cold prefills and paid remote-token cost to redo, more slowly, work the local engine was about to finish. That trade is only right if the wait is calibrated against real traffic, so I would hold the rollout until staging shows acceptable latency and offload behavior. A minor note in the same area: OFFLOAD_MAX_WAIT_SECONDS is not env-tunable.

Merge order. #1636 and #1637 both touch the routing neighborhood around _dispatch_priority and are semantically coupled through uncached_estimate; merge #1636 first, then re-check that neighborhood before #1637 lands.

@1a1a11a 1a1a11a left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of 72510be

Stretching the first-token wait for a large cold prefill fixes a real problem: at the 0.8 s base, big cold prefills were being cancelled. The formula and the rollout story need some work, though. The author's own note ("hold rollout until staging evidence"; "not env-tunable") also still applies.

Should fix

  1. The prefill allowance scales with the configured base wait.
    • offload.py:224 computes base * (1 + uncached / 4096). That assumes 4096 tokens per wait_seconds, which matches the measurements only when the base is 0.8 s.
    • With an admin-set 0.3 s base, an 18.3k-token cold prefill measured at 1.79 s gets 1.64 s and is cancelled, which is the original bug.
    • With a 2 s base, the 8 s cap is reached at about 12k tokens.
    • base + uncached / rate, with the rate expressed in tokens per second, keeps the allowance independent of the base.
  2. There is no off switch, and the logged wait is not the real one.
    • OFFLOAD_PREFILL_CREDIT_TOKENS and OFFLOAD_MAX_WAIT_SECONDS (offload.py:137, 149) are module constants.
    • The admin's wait_seconds is documented as the first-token wait (:159). It now silently becomes up to 10× longer on a stalled engine that still looks healthy, and the only rollback is a revert.
    • The route_offload log (routers.py:1029) still reports the base wait rather than the effective one, so staging telemetry will understate the deadline.
  3. One test is flaky.
    • test_a_warm_continuation_keeps_the_base_wait (test_engine_wait_routing.py:584) uses a 0.05 s engine delay against a wait of about 0.114 s.
    • Under pytest -n 8 it failed 2 of 5 runs on this head ('reserved' == 'engine'), and once on a tree combining dev with #1635, #1636 and #1637.
  4. Deployment details are in shipped docs.
    • docs/agents/reviews/2026-10-22-staging-cache-locality-routing.md (914 lines) records deployment-specific information:
      • the staging route topology and upstream base URLs;
      • that the staging key resolves to an admin account;
      • the results of probing roughly 40 X-Route-Pin provider names.
    • AGENTS.md §1 says a deployment's hosts, accounts and operational notes belong in its overlay (distributions/<name>/), and review records go in docs/reviews/ (§8). The doc also links a file that doesn't exist.
    • I suggest moving it out of this PR. The logic change itself is only about 70 lines.

Nits

  1. The description over-claims in two places.
    • "Queue time no longer eats the budget" is not new: engine_wait.py on_queued/on_sent already does that at the merge-base.
    • The hint proves which conversation this is, not that its prefix is still in the engine's cache. A continuation whose prefix was evicted within the 20 min hint TTL still gets only the base wait. That is no worse than dev, but the description implies otherwise.
  2. Plausible side effect: longer engine waits hold engine_queue_limit slots longer, which may increase queue-wait offloads for short requests. This is worth watching in the staging evidence.

CI and local checks

  • CI: green, and there are no other reviews yet.
  • Local: the PR merges cleanly into current dev, and alongside #1635 and #1636. 112 tests passed. Reverting the routers.py wiring makes 6 of them fail.

Generated by Claude Code

@B-A-M-N

B-A-M-N commented Oct 25, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the review findings on head 488ac8eb:

  • Engine wait now uses an additive base + uncached / ROUTING_OFFLOAD_PREFILL_RATE_TOKENS_PER_SEC allowance (default 2,560 tokens/s), so changing the base wait no longer changes prefill calibration. The measured tail is covered at 0.3s, 0.8s, and 2s bases, with an explicit equal-allowance assertion.
  • Added bounded/configurable controls: ROUTING_OFFLOAD_ENGINE_WAIT_EXTENSION=0 is the no-restart rollback, and rate/max engine wait are configurable with invalid/non-positive values ignored.
  • route_offload now emits engine_wait_seconds and engine_wait_uncached_tokens, and FirstTokenWatch carries effective/base wait plus uncached tokens, separating queue/base policy from effective engine deadline.
  • Replaced the flaky warm-continuation timing margin with a 0.25s engine delay well below its >0.32s deadline while retaining the cold comparison.
  • Removed the deployment-specific 914-line review document from the PR; it is retained outside the repo pending relocation to the deployment overlay.

Focused checks: 119 passed across test_engine_wait_routing.py and test_offload_routing.py; changed-file ruff format/check passed. This still requires controlled staging evidence before production rollout.

@B-A-M-N

B-A-M-N commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

Re-review requested on corrected head 58da2dea: reconciled with current dev@84bda1a2; focused test_engine_wait/test_offload_routing/test_hybrid_composition suite passes 174/174; Ruff format/check clean.

@1a1a11a 1a1a11a left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: request changes. The telemetry the earlier review asked for logs the wrong attempt. The behaviour change is also on by default while staging evidence is still outstanding.

Mergeability / CI. CI is green, and the PR merges cleanly into dev (69 commits behind). I found no semantic clash with #1720 or #1692.

Findings

  1. [major] route_offload logs a wait that was never applied.

    • Where: the streaming fallback in routers.py (around lines 2826-2840), and the path around line 2656.
    • Cause: engine_wait_seconds and the uncached-token count are computed for the offload target (fallback_uncached_tokens). That attempt is explicitly not watched (queue_deadline=None), so the numbers don't describe the abandoned attempt.
    • Probe: the warm primary's wait was 0.325 s on 576 tokens, but the log says 8.0 s on 24,576 tokens. The same misleading numbers are logged for queue-wait and last-resort offloads.
    • FirstTokenWatch.base_wait_seconds and uncached_prefill_tokens are only read by tests.
    • Fix: the rollout depends on this telemetry. Carry the base wait, effective wait and uncached tokens on EngineWaitExpired, log them from the failed attempt, and add a test on the log fields.
  2. [minor] The change is on by default.

    • A wedged-but-healthy engine now holds cold prompts of 18k tokens or more for up to 8 s, instead of 0.8 s.
    • The single global rate is calibrated from one staging model. The measured 9.1k and 18.3k prompts both took 1.79 s, so the allowance is about 4× the measured time.
    • Fix: default ROUTING_OFFLOAD_ENGINE_WAIT_EXTENSION to off until there is staging evidence.
  3. [minor] The new settings aren't registered. They are not in app_config_registry.py, unlike their ROUTING_PREFILL_* siblings. So there is no Admin → Settings entry or validation, and the "no-restart rollback" depends on a raw DB row.

  4. [minor] User-facing text is stale. The OffloadPolicy.wait_seconds docstring and the admin OffloadRoutePanel.tsx text still say a stream is offloaded after wait_seconds without a first token.

  5. [nit] The description and comments are out of date.

    • "Tail calibration replaces the nominal per-token rate": the code is a nominal per-token rate.
    • "Offset from when prefill starts": the clock starts when the request leaves the gateway, and the restart on on_sent predates this PR.
    • Some test comments cite the old formula ("~1.27 s", "~0.11 s").
    • The flaky-test margin barely grew, from 64 ms to 75 ms.

Earlier review.

  • Fixed: base scaling (now additive), and the deployment doc (removed).
  • Partly fixed: the off switch was added but isn't registered; logging was added, but for the wrong attempt.
  • Not fixed: the description's over-claims, and the engine_queue_limit side effect, which still needs checking in staging.

How this was checked.

  • PR tests plus related files: 336 passed, three runs in a row.
  • Merged into dev: 364 passed. Combined with #1636: 328 passed.
  • Reverting the routers.py wiring makes 6 router tests fail, so the tests cover it.
  • The timing test passed 8 of 8 runs at -n 4. Ruff is clean.

Generated by Claude Code

@1a1a11a 1a1a11a left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes, per the review above:

  1. Log the wait, base and uncached tokens of the attempt that actually expired. Carry them on EngineWaitExpired, and add a test on the log fields.
  2. Default ROUTING_OFFLOAD_ENGINE_WAIT_EXTENSION to off until there is staging evidence.
  3. Register the new settings in app_config_registry.py.

Generated by Claude Code

@1a1a11a 1a1a11a left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: still request changes, and two new problems appear once it's rebased onto dev. There are no commits since the Nov 6 review, so its three items stand:

  1. route_offload logs the offload target's wait and uncached tokens, not those of the attempt that expired.
  2. The extension is on by default.
  3. The new settings aren't in app_config_registry.py.

Mergeability / CI. CI was green at 58da2dea. The PR is now 94 commits behind dev and conflicts in routers.py (4 hunks, mechanical). The findings below come from resolving that merge.

Findings

  1. [major, on rebase] The warm path stops working on any endpoint without priority_scheduling.

    • Since #1738, dev stores a prompt anchor only for priority-scheduling endpoints: _PromptAnchor.for_endpoint returns None for the rest (routers.py:894 on dev).
    • _engine_wait_tokens (routers.py:2173) passes messages, and uncached_estimate counts a hint with no anchor as fully uncached. After the rebase, every warm continuation therefore gets the cold wait, up to 8 s.
    • Probe (two turns through the router):
      • On the PR head, the second turn counted 577 uncached tokens and got a 0.325 s wait.
      • Merged with dev, it counted 24,577 tokens and got 8.0 s.
      • Merged, but with priority_scheduling: true, it counted 577 again.
    • The PR's warm-path test misses this because its _remember helper (test_engine_wait_routing.py:562) writes the anchor itself.
    • Fix: compute the anchor wherever a first-token watch is armed, as dev does for priority endpoints. Add a warm-path test that goes through the router's own lease instead of writing the hint by hand.
  2. [minor, on rebase] An extra full-prompt pass breaks a dev test and runs when nothing needs it.

    • Merged with dev, test_prompt_anchor_on_demand.py::test_a_priority_scheduling_route_is_unchanged[stream] fails: it sees 2 anchor checks instead of 1. Putting dev's routers.py back makes it pass.
    • _engine_wait_tokens also runs on every stream attempt, even when no watch will be armed (no offload policy). Compute it only when a watch exists.

What checks out.

  • Missing evidence: with no affinity key, fingerprint or anchor, an expired hint, or a different fingerprint, the whole prompt counts. The wait is longer but still capped.
  • Extremes: 0 uncached tokens gives the base wait. A huge prompt gives 8 s, or the base if that is larger. The rate has a floor of 1 token/s.
  • Non-streaming: it has no first-token watch, so it is unaffected.

How this was checked.

  • PR head, test_engine_wait_routing, test_offload_routing, test_prefill_load and test_endpoint_health: 230 passed, 1 skipped.
  • Merged into dev:
    • the same files: 226 passed;
    • tests/unit/routing + tests/unit/serving at -n 8: 3070 passed, 1 failed (finding 2).
  • Plus the two-turn probe above.

Generated by Claude Code

B-A-M-N and others added 3 commits November 10, 2026 00:55
Merged current upstream/dev (b97bf49) into the branch. The conflicts
were mechanical: upstream added the use_affinity argument and moved the
engine-wait helpers.

Co-Authored-By: Hermes Agent <noreply@hermes.local>
…cached prefill

The engine wait a request runs under is sized on the work it actually has
to do: a cold prompt prefills, and a wait that does not cover the prefill
cancels a legitimate request mid-prefill and re-sends it cold elsewhere.
The budget is the configured base plus the un-cached prefill at a
calibrated rate, capped so a wedged engine still fails over in a known
time.

This branch replaces an earlier head whose tree had been overwritten with
an upstream snapshot: it carried 1,258 changed files and 215,319
additions against a scope of six files, and its ancestry did not contain
the upstream dev it claimed to merge. The change is rebuilt on current
upstream dev, so the diff is the six files the feature actually touches.

Two corrections to the earlier head:

- The extension setting is read with the repository's boolean parser.
  Reading it as "anything that is not the string "0" is on" made the
  stored spelling "false" -- and any value an administrator mistyped --
  switch the behaviour on. The registry entry is a plain boolean for the
  same reason: a flag reads as `value != "0"`, so the console and the
  runtime would disagree. An unusable value now keeps the default, which
  is off.

- The ceiling tests state the condition they depend on. They passed only
  because another test's teardown left the extension reading "on" through
  the same mis-parse, so they were asserting against leaked state.

The behaviour change still ships dark: the extension is off until an
operator turns it on with the setting, and setting it back to off
restores the configured base wait without a restart or a route edit.
The previous head's tree had been overwritten with an upstream snapshot,
so the branch carried 1,258 changed files against a scope of six files and
its ancestry did not contain the dev it claimed to merge.

This merges the dev-based reconstruction of the engine-wait change into
the branch. The result is a fast-forward: the branch keeps its history,
dev is genuinely an ancestor, and the diff against dev is the six files
the feature touches.

The merge resolves to the dev-based tree rather than the snapshot: the
snapshot was never an intended change, only the accident that replaced
the working tree.
@B-A-M-N

B-A-M-N commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Re-review requested — the branch was repaired, and it is now a narrow diff.

The previous head b5e3a3dc had replaced the branch tree with an upstream snapshot: 1,258 changed files and 215,319 additions, with no genuine dev ancestry. The engine-wait feature is only six files, so that was not the change under review.

What this head is. cff9f47c is a two-parent merge: the old head, and a commit rebuilt on current dev carrying only the feature's six files. dev is now a genuine ancestor, and the diff against dev is 6 files / 854 additions. Nothing was force-pushed — the branch advanced by a fast-forward.

One real bug, fixed. The extension's setting was read as "anything that is not the literal string 0", so a stored "false" activated it. It now goes through the repository's own parse_bool, and the registry entry is a normal boolean with default="false" instead of a flag entry. "0", "1", "false", "true", malformed values and a missing value are each tested; an invalid value falls back to the default rather than enabling the extension.

Tests. make test: 13,662 passed, 0 failures. Lint clean. CI on this exact head: run 42800037401, all jobs green.

Behaviour preserved. EngineWaitExpired carries the base and effective wait and the uncached-token values; route_engine_wait_expired records the expired attempt's data; the extension defaults disabled; expensive estimation is limited to attempts with a watch; prompt-anchor generation is reconciled with on-demand behaviour. The added live-reload test proves the setting can be changed at runtime and rolled back without a restart.

Nothing has been deployed and the extension is not enabled — staging comparison remains a separate rollout gate.

@1a1a11a 1a1a11a left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at cff9f47 (last reviewed 58da2de). The branch repair worked: it's back to a 6-file diff against dev, so I reviewed that whole diff rather than a compare against the old head.

Earlier findings, all addressed:

  • Telemetry now describes the attempt that expired. _await_first_token logs route_engine_wait_expired with the effective wait, the base wait and the uncached tokens, and carries them on EngineWaitExpired. There's a test on the log fields.
  • The extension is off by default (OFFLOAD_ENGINE_WAIT_EXTENSION = False) and is read with parse_bool, so a stored "false" no longer turns it on. Good catch.
  • All three settings are registered in app_config_registry.py and reload through on_change.
  • Warm path after the rebase: anchors.need() now computes the anchor on any endpoint when the primary arms a watch. test_a_warm_continuation_through_the_router_keeps_the_short_wait goes through the router's own lease, not a hand-written hint.
  • For the primary attempt, the uncached estimate is only computed when a watch is planned.

CI is passing on the checks that have finished. What's left is small:

  1. route_offload now has engine_wait_seconds / engine_wait_uncached_tokens fields that are always null. No caller passes the new _log_offload kwargs, yet the docstring says they report the effective deadline of the abandoned attempt. Since the rollout depends on this telemetry, I'd either drop them (the route_engine_wait_expired record is the source of truth) or fill them from the EngineWaitExpired that caused the offload. Otherwise the dashboards will have a misleading empty column.
  2. The fallback path is only half-gated. need() is set only from the primary plan, so a fallback that arms a watch on a non-priority endpoint, after a primary that had none, stores its lease without an anchor, and the next turn there is charged cold. Also, fallback_watch_planned ignores whether _queue_deadline returns None, so the estimate still runs for attempts that never get a watch. Both are minor and fail toward a longer, capped wait.
  3. Nit: ROUTING_OFFLOAD_MAX_ENGINE_WAIT_SECONDS and ..._PREFILL_RATE_TOKENS_PER_SEC are registered as type="int", while the code parses and documents floats (8.0, 2560.0). The admin UI will reject a 2.5 s ceiling that the code would accept.

The staging gate from the earlier reviews still applies before anyone flips the extension on.

policy: OffloadPolicy | None,
failed_attempts: Sequence[dict[str, Any]],
*,
engine_wait_seconds: float | None = None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No call site passes these, so route_offload always logs them as null, while the docstring says they carry the abandoned attempt's effective deadline. I'd either drop them or pass the values from the EngineWaitExpired in failed_attempts.

# prefill reads that proof, so the anchor is computed here whenever a
# watch can be armed -- not only for priority-scheduling endpoints.
if primary_plan.policy is not None and primary_plan.deadline is not None:
anchors.need()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only fires when the primary arms a watch. A fallback that arms one (fallback_watch_planned at ~3439) calls anchors.for_endpoint later, and if the endpoint isn't priority-scheduled it stores no anchor, so the next turn on that endpoint is charged cold. I'd call anchors.need() in the fallback branch too when its watch is planned.

"ROUTING_OFFLOAD_MAX_ENGINE_WAIT_SECONDS",
"routing",
"Ceiling on the extended first-token wait, in seconds.",
type="int",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

offload._positive_float_setting parses this as a float and the module default is 8.0, but type="int" makes the admin UI refuse fractional values like 2.5. I'd use float here, and for the rate entry above.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants