Repository navigation
feat(llm): add HedgedLLM for p99 tail latency request hedging - #1082
Conversation
HedgedLLM._stream_hedged drove each candidate generator's __anext__()
inside asyncio.create_task(), which copies the context. The observe
instrumentation opens a span whose contextvar token was then reset in a
different context when the generator finalized, raising "Token created
in a different Context". On the hedge-wins path that ValueError
propagated to the caller; on the primary-fast path it was swallowed by
the generic except clause, flipping primary_failed=True and leaking the
secondary's tokens into the output ("hello world" -> "hello worldbackup").
Each candidate stream is now driven entirely within its own task via
_drain_stream(), funnelling tokens through a queue, so the span token is
set and reset in the same context. The hedge races on the first queued
token and cancels the loser's task, which closes its generator in-context.
Only surfaces when synapsekit.observe is imported (it monkeypatches
BaseLLM.stream), so it reproduced in the full CI suite but not when the
hedging tests ran in isolation.
Co-authored-by: Ashish Maurya <[email protected]>
|
Reviewed and fixed during merge triage. Root cause of the CI test failures (3 streaming tests, all Python versions): Fix (pushed to this branch): each candidate stream is now driven entirely within its own task ( |
Summary
Adds
HedgedLLM,HedgingConfig, andHedgingStatstosynapsekit.llmfor request hedging to mitigate p99 tail latency in production inference pipelines.Type of change
Changes
HedgedLLM(BaseLLM): Drop-inBaseLLMsubclass implementing Request Hedging (based on Google's The Tail at Scale). Dispatches requests to a primary model and concurrently spins up a secondary backup if the primary lags past a configurablehedge_delaySLA deadline.stream()andstream_with_messages(), hedges on Time-To-First-Token (TTFT), shielding generator tasks and cleanly closing losers viaaclose()to eliminate resource leaks.HedgingStats(total_requests,hedged_requests,primary_won,hedge_won,hedge_rate, andhedge_win_rate).tests/llm/test_hedging.pyusing hand-written async fakes per SynapseKit house standards.synapsekit.llmand top-levelsynapsekit.CHANGELOG.mdunder[Unreleased] -> Added.Testing
uv run pytest tests/ -q)pytest tests/llm/test_hedging.py)Documentation
Notes for reviewer
_stream_hedged, the primary generator task is shielded withasyncio.shieldduring the deadline wait to prevent Python'sasyncio.wait_forfrom inadvertently aborting the generator before the hedge race concludes.unittest.mock.MagicMock/unittest.mock.AsyncMock.