Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
54 changes: 43 additions & 11 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,17 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt");
/// [`ProviderView::region`] 和 [`ProviderPreview::region`]。Bedrock API Key 走
/// 原来的 `key`,放进 `Authorization: Bearer`。照 27 写的界面解析不了带 `bedrock` 的
/// 上游列表。
pub const CONTROL_API_VERSION: u32 = 28;
///
/// **29 起一段对话留在上次回答它的那一家**,不再只是 `load-balance` 组按会话取模:
/// 同一轮之内一律不换,跨轮时上一次回答读写的缓存值得留、又没凉才留;一轮开始时的
/// 路由决定沿用到这一轮结束。于是策略组的 `session_affinity`([`GroupView`]、
/// [`GroupInput`],配置里的 `groups[].session_affinity` 一并删了,写着它的配置加载
/// 不了)和 `hurts_cache`([`GroupView`]、[`DryRunResult`])都删了:没有哪种策略还会在
/// 对话半路丢掉缓存。[`Event::RequestRouted`] 和 [`RoutingView`] 多了 `affinity`
/// ([`AffinityView`]):这次沿用了这一轮的路由决定、留在了上次回答的那一家的,
/// 说得出来。照 28 写的界面保存策略组时交的 `session_affinity` 被忽略,读
/// `hurts_cache` 读到的是 undefined。
pub const CONTROL_API_VERSION: u32 = 29;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
Expand Down Expand Up @@ -902,6 +912,10 @@ pub enum Event {
/// 一跳就是被拒的那一家**(没有发出去)
#[serde(default, skip_serializing_if = "Option::is_none")]
denied_by: Option<String>,
/// 这段对话之前的去向在这次路由里起了作用:沿用了这一轮的路由决定、留在了
/// 上次回答的那一家。都没有时没有
#[serde(default, skip_serializing_if = "Option::is_none")]
affinity: Option<AffinityView>,
/// 试过哪几家、各自什么结果。**一次就成的也有一条** ——
/// 「只试了一家」和「试了三家」在用户眼里应该是不同的
attempts: Vec<AttemptView>,
Expand Down Expand Up @@ -1312,9 +1326,37 @@ pub struct RoutingView {
/// 选定上游之后才判断的规则拒绝了它:是哪一条
#[serde(default, skip_serializing_if = "Option::is_none")]
pub denied_by: Option<String>,
/// 这段对话之前的去向起的作用(见 `RequestRouted::affinity`)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub affinity: Option<AffinityView>,
pub attempts: Vec<AttemptView>,
}

/// 一段对话之前的去向在这次路由里起的作用。
///
/// **缓存按上游隔离**:一段对话换一家,那一家要全价重算整段上下文。所以同一轮之内
/// 路由决定不重新求值、也不换家;跨轮时上一次回答的缓存值得留、又没凉,才留下。
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct AffinityView {
/// 沿用了这一轮开头定下的路由决定(规则、策略组、改写):同一轮里规则没有重新
/// 求值。输入超出了所选模型的上下文、重新求了值的,是 `false`
pub held_route: bool,
/// 排在最前面的是上次回答这段对话的那一家:留下的理由。没留的没有
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stayed: Option<Stay>,
}

slug_enum! {
/// 留在上次回答这段对话的那一家的理由。
pub enum Stay {
/// 还在同一轮里:客户端在回传工具结果
Turn = "turn",
/// 新的一轮,而上一次回答读写的缓存值得留、又没凉
Cache = "cache",
}
}

/// 一个订阅额度窗口。**每个字段都直接来自上游**:响应头,或者账号的额度接口。
///
/// 我们自己推断的东西不放进这个结构 —— 界面上必须能区分「上游说的」和
Expand Down Expand Up @@ -1881,18 +1923,13 @@ pub struct GroupView {
pub builtin: bool,
/// 配置里写的 `type`
pub kind: GroupKind,
/// 同一次会话固定走同一家。**这一项直接决定账单**
pub session_affinity: bool,
/// `select` 组当前选中谁。
///
/// **界面要能切它** —— 这个策略本身就是「UI 上点选或托盘里切」,
/// 而切不了的话它等于一个只能改 YAML 才能用的功能。
#[serde(default, skip_serializing_if = "Option::is_none")]
pub selected: Option<String>,
pub providers: Vec<String>,
/// 这个组**按现在的配置**会不会让 prompt cache 不稳定(开着会话粘滞的
/// 轮询组不会)。**要在界面上直说** —— 它决定了用户的账单。
pub hurts_cache: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -2789,9 +2826,6 @@ pub struct GroupInput {
/// `select` 组优先使用的成员
#[serde(default, skip_serializing_if = "Option::is_none")]
pub selected: Option<String>,
/// 同一次会话固定走同一家。只对 `load-balance` 有意义
#[serde(default = "default_true")]
pub session_affinity: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -3837,8 +3871,6 @@ pub struct DryRunResult {
/// 累积起来的参数改写
pub set: Vec<SetView>,
pub trace: Vec<RuleTrace>,
/// 这条路会不会伤到 prompt cache。**要直说 —— 它决定账单**
pub hurts_cache: bool,
/// 候选链里此刻熔断着的那些。**试算是静态的,但熔断是当下的事实**
pub circuit_open: Vec<String>,
/// 规则选中、但服务不了这个请求而被跳过的上游
Expand Down
13 changes: 2 additions & 11 deletions crates/tw-config/tests/manual/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1183,8 +1183,8 @@ pub fn sections() -> Vec<Section> {
Kind::Enum(group_types),
Def::Is("fallback"),
t(
"`fallback`: the first healthy member, in order. `select`: the member named in `selected`. `load-balance`: take turns. `url-test`: the fastest by measured time to first byte. `cheapest`: the lowest input price.",
"`fallback`:按顺序取第一个健康的。`select`:取 `selected` 指定的那个。`load-balance`:轮流。`url-test`:按实测首字节时间取最快的。`cheapest`:取输入单价最低的。",
"`fallback`: the first healthy member, in order. `select`: the member named in `selected`. `load-balance`: take turns between new conversations. `url-test`: the fastest by measured time to first byte. `cheapest`: the lowest input price.",
"`fallback`:按顺序取第一个健康的。`select`:取 `selected` 指定的那个。`load-balance`:新对话轮流。`url-test`:按实测首字节时间取最快的。`cheapest`:取输入单价最低的。",
),
),
row(
Expand All @@ -1193,15 +1193,6 @@ pub fn sections() -> Vec<Section> {
Def::Required,
t("Member upstreams, by name.", "成员上游的名字。"),
),
row(
"session_affinity",
Kind::Bool,
Def::Is("true"),
t(
"Keep a session on the same upstream so its prompt cache keeps hitting. Turning it off under `load-balance` spreads every turn and loses the cache.",
"同一会话固定走同一家,使 prompt cache 持续命中。在 `load-balance` 下关闭会让每一轮都换一家,缓存随之失效。",
),
),
row(
"selected",
Kind::Str,
Expand Down
8 changes: 0 additions & 8 deletions crates/tw-control/src/dryrun.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ fn order_like_the_data_plane(
}
let cfg = s.config();
let facts = tw_engine::Facts {
session: None,
seq: s.gateway.bus.peek_id(),
ttfb_ms: s.gateway.latency.snapshot(&d.candidates),
price: s.gateway.unit_prices(&cfg.providers, asked, &d.candidates),
Expand Down Expand Up @@ -205,7 +204,6 @@ pub async fn dry_run(
via_group: None,
set: Vec::new(),
trace,
hurts_cache: false,
circuit_open: Vec::new(),
skipped: Vec::new(),
converted: Vec::new(),
Expand All @@ -220,12 +218,6 @@ pub async fn dry_run(
out.outcome = DryRunOutcome::Route;
out.rule = Some(d.matched_rule.clone());
out.via_group = d.via_group.clone();
// 按这个组的配置判断:开着会话粘滞的轮询组不伤缓存
out.hurts_cache = d
.via_group
.as_deref()
.and_then(|g| engine.groups().iter().find(|x| x.name == g))
.is_some_and(|g| g.hurts_cache());
out.set = describe(&d.set);
out.strategy = d
.via_group
Expand Down
3 changes: 0 additions & 3 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,11 +357,8 @@ async fn overview(State(s): State<ControlState>) -> Json<tw_api::Overview> {
name: g.name.clone(),
builtin: tw_engine::is_builtin_group(&g.name),
kind: routes::group_kind(g.kind),
session_affinity: g.session_affinity,
selected: g.selected.clone(),
providers: g.providers.clone(),
// 按这个组的配置判断:开着会话粘滞的轮询组不伤缓存
hurts_cache: g.hurts_cache(),
})
.collect(),
// 和 `GET /keys` 同一份视图:概览里少一个字段的话,两处会各自
Expand Down
3 changes: 0 additions & 3 deletions crates/tw-control/src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -624,8 +624,6 @@ fn to_group(input: &tw_api::GroupInput, cfg: &tw_config::Config) -> Result<Group
name,
kind,
providers,
// 只对轮询有意义;其余策略保持默认,不往文件里写
session_affinity: kind != GroupType::LoadBalance || input.session_affinity,
selected,
})
}
Expand Down Expand Up @@ -788,7 +786,6 @@ mod msg_codes {
kind: tw_api::GroupKind::from_slug(kind).unwrap(),
providers: providers.iter().map(|p| p.to_string()).collect(),
selected: None,
session_affinity: true,
};
let code = |i: tw_api::GroupInput| to_group(&i, &c).unwrap_err().code;
assert_eq!(
Expand Down
21 changes: 0 additions & 21 deletions crates/tw-control/tests/dryrun.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,6 @@ groups:
- name: 都试试
type: load-balance
providers: [官方, 中转]
- name: 真轮询
type: load-balance
session_affinity: false
providers: [官方, 中转]
routes:
- name: default
rules:
Expand Down Expand Up @@ -111,22 +107,6 @@ async fn a_plain_request_falls_through_to_the_catch_all() {
assert_eq!(r.via_group.as_deref(), Some("都试试"));
assert_eq!(r.candidates.len(), 2);
assert_eq!(r.route, "default");
// 开着会话粘滞(默认)的轮询不伤缓存:同一次对话始终落在同一家。
// 一律标成危险是假警报,而假警报会让人学会忽略这一栏
assert!(!r.hurts_cache, "粘滞的轮询不该报");
}

#[tokio::test]
async fn round_robin_without_affinity_is_said_to_hurt_the_cache() {
// **要直说 —— 它决定账单。**
let (_d, app) = app();
let r = run(
&app,
r#"{"model":"claude-sonnet-4-5","draft":{"name":"草稿","rules":[{"name":"兜底","to":"真轮询"}]}}"#,
)
.await;
assert!(r.hurts_cache);
assert_eq!(r.route, "草稿");
}

#[tokio::test]
Expand Down Expand Up @@ -228,7 +208,6 @@ async fn a_cached_request_is_pinned_to_the_official_upstream() {
let r = run(&app, r#"{"model":"claude-sonnet-4-5","cache":true}"#).await;
assert_eq!(r.rule.as_deref(), Some("带缓存的必须走官方"));
assert_eq!(r.candidates, vec!["官方".to_string()]);
assert!(!r.hurts_cache);
}

#[tokio::test]
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/in_flight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ async fn it_gives_every_running_request_with_what_has_happened_to_it_so_far() {
group: None,
rewritten_by: vec![],
denied_by: None,
affinity: None,
attempts: vec![tw_api::AttemptView {
provider: "官方".into(),
model: None,
Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/live_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ async fn a_request_still_running_can_be_opened_and_becomes_whole_when_it_ends()
group: Some("__all__".into()),
rewritten_by: vec![],
denied_by: None,
affinity: None,
attempts: vec![tw_api::AttemptView {
provider: "官方".into(),
model: None,
Expand Down
Loading
Loading