Skip to content

feat(llm): add HedgedLLM for p99 tail latency request hedging - #1082

Merged
AmitoVrito merged 2 commits into
SynapseKit:mainfrom
ramashishmaurya:feat/llm-request-hedging
Oct 16, 2026
Merged

AmitoVrito merged 2 commits into
SynapseKit:mainfrom
ramashishmaurya:feat/llm-request-hedging

Conversation

@ramashishmaurya

Copy link
Copy Markdown
Contributor

Summary

Adds HedgedLLM, HedgingConfig, and HedgingStats to synapsekit.llm for request hedging to mitigate p99 tail latency in production inference pipelines.

Type of change

  • Bug fix
  • New feature
  • Documentation update
  • Refactor / internal improvement
  • Dependency / tooling update

Changes

  • HedgedLLM(BaseLLM): Drop-in BaseLLM subclass 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 configurable hedge_delay SLA deadline.
  • Immediate Failure Fast-Path: If the primary fails outright before the deadline expires, the secondary is triggered immediately without waiting for the timeout.
  • Streaming TTFT Race: For stream() and stream_with_messages(), hedges on Time-To-First-Token (TTFT), shielding generator tasks and cleanly closing losers via aclose() to eliminate resource leaks.
  • Observability & FinOps: Tracks HedgingStats (total_requests, hedged_requests, primary_won, hedge_won, hedge_rate, and hedge_win_rate).
  • Zero Mock Tests: Full 19-test unit suite in tests/llm/test_hedging.py using hand-written async fakes per SynapseKit house standards.
  • Exports: Exported in synapsekit.llm and top-level synapsekit.
  • Changelog: Updated CHANGELOG.md under [Unreleased] -> Added.

Testing

  • All existing tests pass (uv run pytest tests/ -q)
  • New tests added for new behaviour (pytest tests/llm/test_hedging.py)
  • No API keys or secrets in the code

Documentation

  • Docstrings updated (if public API changed)
  • synapsekit-docs updated (if new feature)
  • CHANGELOG.md updated

Notes for reviewer

  • In _stream_hedged, the primary generator task is shielded with asyncio.shield during the deadline wait to prevent Python's asyncio.wait_for from inadvertently aborting the generator before the hedge race concludes.
  • Strictly adheres to the project constraint prohibiting unittest.mock.MagicMock / unittest.mock.AsyncMock.

ramashishmaurya and others added 2 commits October 15, 2026 17:05
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]>
@AmitoVrito

Copy link
Copy Markdown
Collaborator

Reviewed and fixed during merge triage.

Root cause of the CI test failures (3 streaming tests, all Python versions): _stream_hedged drove each candidate generator's __anext__() inside asyncio.create_task(), which copies the context. When synapsekit.observe is imported it monkeypatches BaseLLM.stream to open a span backed by a contextvar; the span's token was therefore set in the task's copied context but reset in the main context when the generator finalized, raising ValueError: Token var ... was created in a different Context. On the hedge-wins path that error propagated to the caller; on the primary-fast path the generic except Exception swallowed it, flipped primary_failed=True, and leaked the secondary's tokens into the output (hello world → hello worldbackup). It only reproduced in the full CI suite because the hedging tests in isolation never import synapsekit.observe.

Fix (pushed to this branch): each candidate stream is now driven entirely within its own task (_drain_stream) that funnels 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. No behavioural change to the generate/tool paths. Your existing 19 tests are the regression guard and now pass under the observe-active condition that was failing. Thanks for the clean, mock-free test suite — it pinpointed this immediately.

@AmitoVrito
AmitoVrito merged commit e9e3b94 into SynapseKit:main Oct 16, 2026
19 checks passed
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