Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -288,9 +288,8 @@ def add_arguments(self, parser) -> None:
env_var="DYN_ROUTER_REPLICA_SYNC",
default=False,
help=(
"KV Router: Enable replica synchronization across multiple router instances. "
"When true, routers will publish and subscribe to events to maintain "
"consistent state."
"KV Router: Enable best-effort active-sequence synchronization through "
"the Runtime event plane."
),
)
add_negatable_bool_argument(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"active_prefill_tokens_threshold",
"active_prefill_tokens_threshold_frac",
"session_affinity_ttl_secs",
"session_affinity_replica_sync",
)

_ENFORCE_DISAGG_DEPRECATION = (
Expand Down Expand Up @@ -69,6 +70,7 @@ class RouterConfigBase(ConfigBase):
min_initial_workers: int
enforce_disagg: bool
session_affinity_ttl_secs: Optional[int]
session_affinity_replica_sync: bool
active_decode_blocks_threshold: Optional[float]
active_prefill_tokens_threshold: Optional[int]
active_prefill_tokens_threshold_frac: Optional[float]
Expand Down Expand Up @@ -195,13 +197,27 @@ def add_arguments(self, parser) -> None:
env_var="DYN_ROUTER_SESSION_AFFINITY_TTL_SECS",
default=None,
help=(
"Enable router-local session affinity with this idle TTL in seconds. "
"Enable session affinity with this router-local idle TTL in seconds. "
"Add --router-session-affinity-replica-sync for best-effort binding "
"synchronization. "
"Affinity is disabled when this option is omitted. "
"This is independent of KV prediction TTL settings."
),
arg_type=int,
dest="session_affinity_ttl_secs",
)
add_negatable_bool_argument(
g,
flag_name="--router-session-affinity-replica-sync",
env_var="DYN_ROUTER_SESSION_AFFINITY_REPLICA_SYNC",
default=False,
dest="session_affinity_replica_sync",
help=(
"Enable best-effort session-affinity binding synchronization through "
"the Runtime event plane. Requires "
"--router-session-affinity-ttl-secs."
),
)
add_negatable_bool_argument(
g,
flag_name="--enforce-disagg",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@ def test_frontend_rejection_thresholds_default_to_none(
"active_prefill_tokens_threshold": None,
"active_prefill_tokens_threshold_frac": None,
"session_affinity_ttl_secs": None,
"session_affinity_replica_sync": False,
}
assert "busy-worker rejection disabled" in caplog.text

Expand Down Expand Up @@ -507,6 +508,7 @@ def test_all_rejection_thresholds_and_queue_override_are_forwarded(
"active_prefill_tokens_threshold": 1000,
"active_prefill_tokens_threshold_frac": 2.0,
"session_affinity_ttl_secs": None,
"session_affinity_replica_sync": False,
}
assert config.kv_router_kwargs()["router_queue_threshold"] == 32.0

Expand Down Expand Up @@ -641,12 +643,14 @@ def test_rejection_threshold_validation_rejects_invalid_values(

def test_session_affinity_ttl_cli_and_environment(monkeypatch) -> None:
monkeypatch.delenv("DYN_ROUTER_SESSION_AFFINITY_TTL_SECS", raising=False)
monkeypatch.delenv("DYN_ROUTER_SESSION_AFFINITY_REPLICA_SYNC", raising=False)
parser = argparse.ArgumentParser()
FrontendArgGroup().add_arguments(parser)
config = FrontendConfig.from_cli_args(parser.parse_args([]))
config.validate()
assert config.session_affinity_ttl_secs is None
assert config.router_kwargs()["session_affinity_ttl_secs"] is None
assert config.router_kwargs()["session_affinity_replica_sync"] is False

monkeypatch.setenv("DYN_ROUTER_SESSION_AFFINITY_TTL_SECS", "600")
parser = argparse.ArgumentParser()
Expand All @@ -665,6 +669,68 @@ def test_session_affinity_ttl_cli_and_environment(monkeypatch) -> None:
assert config.session_affinity_ttl_secs == 900


@pytest.mark.parametrize(
("environment", "args"),
[
(False, ["--router-session-affinity-replica-sync"]),
(True, []),
],
ids=["cli", "environment"],
)
def test_session_affinity_replica_sync_flows_outside_kv_config(
monkeypatch: pytest.MonkeyPatch,
environment: bool,
args: list[str],
) -> None:
monkeypatch.delenv("DYN_ROUTER_SESSION_AFFINITY_REPLICA_SYNC", raising=False)
if environment:
monkeypatch.setenv("DYN_ROUTER_SESSION_AFFINITY_REPLICA_SYNC", "true")

parser = argparse.ArgumentParser()
FrontendArgGroup().add_arguments(parser)
config = FrontendConfig.from_cli_args(
parser.parse_args(
[
"--router-mode",
"random",
"--router-session-affinity-ttl-secs",
"300",
*args,
]
)
)
config.validate()

assert config.router_kwargs()["session_affinity_replica_sync"] is True
assert config.kv_router_kwargs()["router_replica_sync"] is False


def test_session_affinity_replica_sync_requires_ttl() -> None:
parser = argparse.ArgumentParser()
FrontendArgGroup().add_arguments(parser)
config = FrontendConfig.from_cli_args(
parser.parse_args(["--router-session-affinity-replica-sync"])
)

with pytest.raises(
ValueError,
match="router-session-affinity-replica-sync.*router-session-affinity-ttl-secs",
):
config.validate()


def test_active_sequence_replica_sync_stays_in_kv_config() -> None:
parser = argparse.ArgumentParser()
FrontendArgGroup().add_arguments(parser)
config = FrontendConfig.from_cli_args(
parser.parse_args(["--router-mode", "random", "--router-replica-sync"])
)
config.validate()

assert config.kv_router_kwargs()["router_replica_sync"] is True
assert config.router_kwargs()["session_affinity_replica_sync"] is False


@pytest.mark.parametrize("ttl", [0, 31_536_001])
def test_session_affinity_ttl_rejects_out_of_range(ttl: int) -> None:
parser = argparse.ArgumentParser()
Expand Down
8 changes: 8 additions & 0 deletions components/src/dynamo/frontend/frontend_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,14 @@ def validate(self) -> None:
"--router-session-affinity-ttl-secs must be between 1 and "
f"{_MAX_SESSION_AFFINITY_TTL_SECS}"
)
if (
self.session_affinity_replica_sync
and self.session_affinity_ttl_secs is None
):
raise ValueError(
"--router-session-affinity-replica-sync requires "
"--router-session-affinity-ttl-secs"
)
if self.tokenizer_backend not in self._VALID_TOKENIZER_BACKENDS:
raise ValueError(
f"--tokenizer: invalid value '{self.tokenizer_backend}' "
Expand Down
4 changes: 3 additions & 1 deletion docs/components/frontend/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ The Rust HTTP server also reads these environment variables (not exposed as CLI
| `--router-temperature` | `DYN_ROUTER_TEMPERATURE` | `0.0` | Softmax temperature for normalized worker sampling. 0 = deterministic |
| `--router-kv-events` / `--no-router-kv-events` | `DYN_ROUTER_USE_KV_EVENTS` | `true` | Enable KV cache state events from workers. Disable for prediction-based routing |
| `--router-ttl-secs` | `DYN_ROUTER_TTL_SECS` | `120.0` | Block TTL when KV events are disabled |
| `--router-replica-sync` / `--no-router-replica-sync` | `DYN_ROUTER_REPLICA_SYNC` | `false` | Sync state across multiple router instances |
| `--router-replica-sync` / `--no-router-replica-sync` | `DYN_ROUTER_REPLICA_SYNC` | `false` | Best-effort sync of KV active-sequence state |
| `--router-session-affinity-ttl-secs` | `DYN_ROUTER_SESSION_AFFINITY_TTL_SECS` | unset | Enables session affinity with this router-local idle TTL |
| `--router-session-affinity-replica-sync` / `--no-router-session-affinity-replica-sync` | `DYN_ROUTER_SESSION_AFFINITY_REPLICA_SYNC` | `false` | Best-effort sync of session-affinity bindings; requires `--router-session-affinity-ttl-secs` |
| `--router-snapshot-threshold` | `DYN_ROUTER_SNAPSHOT_THRESHOLD` | `1000000` | Messages before triggering a snapshot |
| `--router-reset-states` / `--no-router-reset-states` | `DYN_ROUTER_RESET_STATES` | `false` | Reset router state on startup. **Warning:** affects existing replicas |
| `--router-track-active-blocks` / `--no-router-track-active-blocks` | `DYN_ROUTER_TRACK_ACTIVE_BLOCKS` | `true` | Track blocks used by in-progress requests for load balancing |
Expand Down
35 changes: 28 additions & 7 deletions docs/components/router/router-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,35 @@ The configured value is the idle timeout. It is independent of
`--router-ttl-secs` and `--router-predicted-ttl-secs`. Omit the session-affinity
option to keep affinity disabled.

Add `--router-session-affinity-replica-sync` to synchronize affinity bindings
between router replicas through the Runtime event plane. This option requires
`--router-session-affinity-ttl-secs`; it does not enable session affinity by itself.
The origin publishes a binding after successful dispatch so concurrent requests can
observe it, then publishes it again when the request lease ends so peer idle timers
restart when the request becomes idle. The extra event fanout is an intentional
tradeoff.

Synchronization is advisory. Each replica owns its local idle TTL and uses the
first live binding it observes. A matching update refreshes that local deadline,
an expired binding can be replaced, and a conflicting live binding is ignored.
Events use the same component scope as active-sequence synchronization, and the
session-affinity subscriber additionally rejects targets outside its local worker
set. Stronger cross-model or worker-role isolation is future work.

Dropped, delayed, or reordered events do not affect request correctness, but can
temporarily reduce affinity. In particular, a long request can outlive a peer's
local TTL, and a dropped lease-completion update can leave peer deadlines out of
sync until a later request republishes the binding.

If the bound worker disappears, Dynamo invalidates the binding so a subsequent
selection can bind an available worker. Router restart clears all bindings. Bindings
are not shared between frontend replicas. In a multi-frontend deployment, configure
the ingress or load balancer to consistently route a session to one frontend. Hash
the raw session header received at ingress, not Dynamo's normalized internal
`session_id`: canonical clients send `X-Dynamo-Session-ID`, while agent-native
clients use the corresponding header listed in [Session IDs](../../agents/session-ids.md).
Agent-native identity is normalized only after the request reaches the frontend.
received from replicas are not authoritative storage. For strict affinity, configure
the ingress or load balancer to consistently route a session to one frontend, or use
an authoritative external binding store. When hashing at ingress, hash the raw
session header rather than Dynamo's normalized internal `session_id`: canonical
clients send `X-Dynamo-Session-ID`, while agent-native clients use the corresponding
header listed in [Session IDs](../../agents/session-ids.md). Agent-native identity is
normalized only after the request reaches the frontend.

Direct mode still requires the phase-appropriate explicit worker ID on every
affinity request. The stored binding validates that target but does not supply a
Expand Down Expand Up @@ -199,7 +220,7 @@ For Kubernetes deployment examples, see [Kubernetes Topology-Aware KV Transfer](
- `--router-track-output-blocks`: **Experimental.** Enables tracking of output blocks during generation. When enabled, the router adds placeholder blocks as tokens are generated and applies fractional decay based on progress toward the expected output sequence length (`agent_hints.osl` in `nvext`). For the cost-model behavior, see [Decode Load Modeling](router-concepts.md#decode-load-modeling).
- `--no-router-assume-kv-reuse`: When tracking active blocks, disables the assumption of KV cache reuse. This is useful in disaggregated setups where transferred blocks are not actually deduplicated on the decode side.
- `--no-router-track-prefill-tokens`: Disables prompt-side prefill token accounting in the router's active load model. Use this for decode-only routing paths where prompt processing already happened elsewhere.
- `--router-replica-sync`: Disabled by default. Enables NATS-based synchronization of local routing decisions between router replicas.
- `--router-replica-sync`: Disabled by default. Enables best-effort Runtime event-plane synchronization of KV active-sequence state. Session-affinity synchronization uses the separate `--router-session-affinity-replica-sync` option.

## KV Indexer / Approx KV Indexer

Expand Down
11 changes: 10 additions & 1 deletion docs/components/router/router-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ The operational concern is replica synchronization. Active blocks are tracked lo
There are two operating modes for active blocks:

- **Local-only tracking**: Leave replicas unsynchronized. Each router balances using the subset of active requests it routed itself. This is simpler and may be acceptable when traffic is already well distributed across replicas or when active-load precision is less important.
- **Replica sync**: Enable `--router-replica-sync` so replicas publish and subscribe to active-sequence lifecycle events through NATS core messaging. This gives each replica a more complete active-load view across the router fleet.
- **Replica sync**: Enable `--router-replica-sync` so replicas publish and subscribe to component-scoped active-sequence lifecycle events through the Runtime event plane. This gives each replica a more complete active-load view across the router fleet.

```bash
# Router replica 1
Expand All @@ -85,6 +85,15 @@ python -m dynamo.frontend --router-mode kv --http-port 8001 --router-replica-syn

With replica sync enabled, a new router still starts with zero active-block knowledge, but it converges through live request handling and active-sequence events from other replicas. Without it, each replica keeps an isolated active-block view, which can lead to suboptimal load balancing.

Session-affinity synchronization uses the separate
`--router-session-affinity-replica-sync` option and requires
`--router-session-affinity-ttl-secs`. That path is best effort: each replica owns its
local idle TTL, rejects targets outside its local worker membership, and keeps the
first live binding it observes. The origin publishes after dispatch for concurrent
visibility and again when the lease ends to restart peer idle timers. Long requests
and dropped completion updates can temporarily desynchronize those timers. Use
ingress stickiness or authoritative storage when affinity must be strict.

## Dynamo-Native Remote Indexer

For Dynamo-native deployments, the remote indexer is served by `dynamo.frontend` or `dynamo.router`, not by `dynamo.indexer`.
Expand Down
3 changes: 2 additions & 1 deletion docs/kubernetes/gateway-api/reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,8 @@ Set these values on the EPP component unless the deployment manifest says otherw
| `DYN_ROUTER_KV_OVERLAP_SCORE_CREDIT_DECAY` | `0.0` | Reduces prefix-overlap credit as active prefill load rises above the least-loaded eligible worker. |
| `DYN_ROUTER_PREFILL_LOAD_SCALE` | `1.0` | Scales prompt-side prefill load after cache-hit credits are applied. |
| `DYN_ROUTER_TEMPERATURE` | `0.0` | `0.0` selects deterministically. Higher values allow more worker exploration through softmax sampling. |
| `DYN_ROUTER_REPLICA_SYNC` | `false` | Publishes and subscribes router state across router replicas. |
| `DYN_ROUTER_REPLICA_SYNC` | `false` | Publishes and subscribes KV active-sequence state across router replicas. |
| `DYN_ROUTER_SESSION_AFFINITY_REPLICA_SYNC` | `false` | Publishes and subscribes session-affinity bindings across router replicas. Requires `DYN_ROUTER_SESSION_AFFINITY_TTL_SECS`. |
| `DYN_ROUTER_TRACK_ACTIVE_BLOCKS` | `true` | Tracks active decode blocks for load balancing. |
| `DYN_ROUTER_TRACK_OUTPUT_BLOCKS` | `false` | Predicts output blocks during generation and decays them by progress toward expected output length. |
| `DYN_ROUTER_TRACK_PREFILL_TOKENS` | `true` | Includes active prompt-side prefill tokens in load accounting. |
Expand Down
12 changes: 11 additions & 1 deletion lib/bindings/python/rust/llm/entrypoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -432,12 +432,14 @@ pub struct RouterConfig {
/// Threshold for active prefill tokens as fraction of max_num_batched_tokens
active_prefill_tokens_threshold_frac: Option<f64>,
session_affinity_ttl_secs: Option<u64>,
session_affinity_replica_sync: bool,
}

#[pymethods]
impl RouterConfig {
#[new]
#[pyo3(signature = (mode, config=None, active_decode_blocks_threshold=None, active_prefill_tokens_threshold=None, active_prefill_tokens_threshold_frac=None, enforce_disagg=false, session_affinity_ttl_secs=None))]
#[pyo3(signature = (mode, config=None, active_decode_blocks_threshold=None, active_prefill_tokens_threshold=None, active_prefill_tokens_threshold_frac=None, enforce_disagg=false, session_affinity_ttl_secs=None, session_affinity_replica_sync=false))]
#[allow(clippy::too_many_arguments)]
pub fn new(
mode: RouterMode,
config: Option<KvRouterConfig>,
Expand All @@ -446,6 +448,7 @@ impl RouterConfig {
active_prefill_tokens_threshold_frac: Option<f64>,
enforce_disagg: bool,
session_affinity_ttl_secs: Option<u64>,
session_affinity_replica_sync: bool,
) -> PyResult<Self> {
if enforce_disagg {
static WARN_ONCE: std::sync::Once = std::sync::Once::new();
Expand All @@ -460,6 +463,11 @@ impl RouterConfig {
"session_affinity_ttl_secs must be between 1 and 31536000",
));
}
if session_affinity_replica_sync && session_affinity_ttl_secs.is_none() {
return Err(PyValueError::new_err(
"session_affinity_replica_sync requires session_affinity_ttl_secs",
));
}
RsLoadThresholdConfig {
active_decode_blocks_threshold,
active_prefill_tokens_threshold,
Expand All @@ -474,6 +482,7 @@ impl RouterConfig {
active_prefill_tokens_threshold,
active_prefill_tokens_threshold_frac,
session_affinity_ttl_secs,
session_affinity_replica_sync,
})
}
}
Expand All @@ -490,6 +499,7 @@ impl From<RouterConfig> for RsRouterConfig {
},
enforce_disagg: false,
session_affinity_ttl_secs: rc.session_affinity_ttl_secs,
session_affinity_replica_sync: rc.session_affinity_replica_sync,
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions lib/bindings/python/src/dynamo/_core.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -1646,6 +1646,8 @@ class RouterConfig:
active_prefill_tokens_threshold: Optional[int] = None,
active_prefill_tokens_threshold_frac: Optional[float] = None,
enforce_disagg: bool = False,
session_affinity_ttl_secs: Optional[int] = None,
session_affinity_replica_sync: bool = False,
) -> None:
"""
Create a RouterConfig.
Expand All @@ -1657,6 +1659,8 @@ class RouterConfig:
active_prefill_tokens_threshold: Literal token count threshold for prefill busy detection
active_prefill_tokens_threshold_frac: Fraction of max_num_batched_tokens for busy detection
enforce_disagg: Deprecated and ignored. Routing topology and readiness come from registered worker types.
session_affinity_ttl_secs: Router-local session-affinity idle TTL in seconds.
session_affinity_replica_sync: Whether to synchronize session-affinity bindings across router replicas.
"""
...

Expand Down
2 changes: 2 additions & 0 deletions lib/llm/src/discovery/watcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1625,6 +1625,7 @@ impl ModelWatcher {
Some(prefill_config),
self.prefill_load_estimator.clone(),
router_config.session_affinity_ttl_secs,
router_config.session_affinity_replica_sync,
model_name.clone(),
namespace.clone(),
prefill_enable_eagle,
Expand Down Expand Up @@ -1668,6 +1669,7 @@ impl ModelWatcher {
encoder_chooser.clone(),
uses_multimodal_cache_routing(card),
router_config.session_affinity_ttl_secs,
router_config.session_affinity_replica_sync,
)
.await
.context("build_preprocessed_routing")?,
Expand Down
Loading
Loading