From dee82b5a535e07dcc5901756f690b502d73a1ba6 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:14:43 +0800 Subject: [PATCH] Keep a conversation on the upstream that answered it, and hold a turn's route A conversation (client session header plus the content fingerprint, or the fingerprint alone) now stays on the upstream that last answered it: always within a turn (the last user message is a tool result), and across turns only while the previous answer read or wrote at least 1024 tokens of prompt cache less than five minutes ago. A pinned upstream that is cooling down is released, and a failover member that answered becomes the pin. Pins are scoped by route and group, kept in memory (4096 conversations, 24 hours). The routing decision made at the start of a turn is reused for the rest of the turn, so rules keyed on input size or images no longer move a turn halfway; it is re-evaluated only when the input no longer fits the smallest known context window among its candidates (from the price book). This replaces the load-balance fingerprint-modulo pinning: load-balance now rotates new conversations. `groups[].session_affinity` and `hurts_cache` are removed. RequestRouted and RoutingView gain `affinity` (held_route, stayed: turn | cache). Control API version 29. Co-Authored-By: Claude Opus 5.5 --- crates/tw-api/src/lib.rs | 54 +- crates/tw-config/tests/manual/schema.rs | 13 +- crates/tw-control/src/dryrun.rs | 8 - crates/tw-control/src/lib.rs | 3 - crates/tw-control/src/routes.rs | 3 - crates/tw-control/tests/dryrun.rs | 21 - crates/tw-control/tests/in_flight.rs | 1 + crates/tw-control/tests/live_state.rs | 1 + crates/tw-engine/src/engine.rs | 246 +------- crates/tw-gateway/src/affinity.rs | 584 +++++++++++++++++++ crates/tw-gateway/src/ending.rs | 14 + crates/tw-gateway/src/lib.rs | 1 + crates/tw-gateway/src/server.rs | 3 + crates/tw-gateway/src/server/pipeline.rs | 141 ++++- crates/tw-gateway/src/server/pipeline/hop.rs | 1 + crates/tw-gateway/src/server/upgrade.rs | 3 + crates/tw-gateway/src/state.rs | 3 + crates/tw-gateway/src/ws.rs | 1 + crates/tw-gateway/tests/affinity.rs | 182 ++++++ crates/tw-gateway/tests/passthrough.rs | 3 - crates/tw-gateway/tests/routing_facts.rs | 1 - crates/tw-gateway/tests/ws.rs | 1 - crates/tw-observe/src/bus.rs | 1 + crates/tw-store/src/db.rs | 1 + crates/tw-store/src/recorder.rs | 10 + docs/config.md | 20 +- docs/config.zh-CN.md | 7 +- 27 files changed, 1014 insertions(+), 313 deletions(-) create mode 100644 crates/tw-gateway/src/affinity.rs create mode 100644 crates/tw-gateway/tests/affinity.rs diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 24513766..c5acc248 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -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))] @@ -902,6 +912,10 @@ pub enum Event { /// 一跳就是被拒的那一家**(没有发出去) #[serde(default, skip_serializing_if = "Option::is_none")] denied_by: Option, + /// 这段对话之前的去向在这次路由里起了作用:沿用了这一轮的路由决定、留在了 + /// 上次回答的那一家。都没有时没有 + #[serde(default, skip_serializing_if = "Option::is_none")] + affinity: Option, /// 试过哪几家、各自什么结果。**一次就成的也有一条** —— /// 「只试了一家」和「试了三家」在用户眼里应该是不同的 attempts: Vec, @@ -1312,9 +1326,37 @@ pub struct RoutingView { /// 选定上游之后才判断的规则拒绝了它:是哪一条 #[serde(default, skip_serializing_if = "Option::is_none")] pub denied_by: Option, + /// 这段对话之前的去向起的作用(见 `RequestRouted::affinity`) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub affinity: Option, pub attempts: Vec, } +/// 一段对话之前的去向在这次路由里起的作用。 +/// +/// **缓存按上游隔离**:一段对话换一家,那一家要全价重算整段上下文。所以同一轮之内 +/// 路由决定不重新求值、也不换家;跨轮时上一次回答的缓存值得留、又没凉,才留下。 +#[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, +} + +slug_enum! { + /// 留在上次回答这段对话的那一家的理由。 + pub enum Stay { + /// 还在同一轮里:客户端在回传工具结果 + Turn = "turn", + /// 新的一轮,而上一次回答读写的缓存值得留、又没凉 + Cache = "cache", + } +} + /// 一个订阅额度窗口。**每个字段都直接来自上游**:响应头,或者账号的额度接口。 /// /// 我们自己推断的东西不放进这个结构 —— 界面上必须能区分「上游说的」和 @@ -1881,8 +1923,6 @@ pub struct GroupView { pub builtin: bool, /// 配置里写的 `type` pub kind: GroupKind, - /// 同一次会话固定走同一家。**这一项直接决定账单** - pub session_affinity: bool, /// `select` 组当前选中谁。 /// /// **界面要能切它** —— 这个策略本身就是「UI 上点选或托盘里切」, @@ -1890,9 +1930,6 @@ pub struct GroupView { #[serde(default, skip_serializing_if = "Option::is_none")] pub selected: Option, pub providers: Vec, - /// 这个组**按现在的配置**会不会让 prompt cache 不稳定(开着会话粘滞的 - /// 轮询组不会)。**要在界面上直说** —— 它决定了用户的账单。 - pub hurts_cache: bool, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -2789,9 +2826,6 @@ pub struct GroupInput { /// `select` 组优先使用的成员 #[serde(default, skip_serializing_if = "Option::is_none")] pub selected: Option, - /// 同一次会话固定走同一家。只对 `load-balance` 有意义 - #[serde(default = "default_true")] - pub session_affinity: bool, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -3837,8 +3871,6 @@ pub struct DryRunResult { /// 累积起来的参数改写 pub set: Vec, pub trace: Vec, - /// 这条路会不会伤到 prompt cache。**要直说 —— 它决定账单** - pub hurts_cache: bool, /// 候选链里此刻熔断着的那些。**试算是静态的,但熔断是当下的事实** pub circuit_open: Vec, /// 规则选中、但服务不了这个请求而被跳过的上游 diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index b65337e7..482c9de9 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -1183,8 +1183,8 @@ pub fn sections() -> Vec
{ 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( @@ -1193,15 +1193,6 @@ pub fn sections() -> Vec
{ 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, diff --git a/crates/tw-control/src/dryrun.rs b/crates/tw-control/src/dryrun.rs index 3c927084..ee0b6127 100644 --- a/crates/tw-control/src/dryrun.rs +++ b/crates/tw-control/src/dryrun.rs @@ -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), @@ -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(), @@ -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 diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index c76add74..36b133f7 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -357,11 +357,8 @@ async fn overview(State(s): State) -> Json { 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` 同一份视图:概览里少一个字段的话,两处会各自 diff --git a/crates/tw-control/src/routes.rs b/crates/tw-control/src/routes.rs index d5de4c8b..47a4bcfc 100644 --- a/crates/tw-control/src/routes.rs +++ b/crates/tw-control/src/routes.rs @@ -624,8 +624,6 @@ fn to_group(input: &tw_api::GroupInput, cfg: &tw_config::Config) -> Result bool { - matches!(self, GroupType::LoadBalance | GroupType::UrlTest) - } - /// 排顺序时要不要用到运行时的数字。 /// /// **`fallback` 和 `select` 不需要**,而它们是绝大多数人的配置 @@ -79,9 +69,7 @@ impl GroupType { /// 和真实转发不一样的结果」。 #[derive(Debug, Clone, Default)] pub struct Facts { - /// 会话指纹。`None` = 认不出来这是哪次会话 - pub session: Option, - /// 轮转的种子。认不出会话时用它 —— 通常是请求序号 + /// 轮转的种子 —— 通常是请求序号 pub seq: u64, /// 每家的典型 TTFB(毫秒)。**缺席 = 样本不够**,不是「很快」 pub ttfb_ms: std::collections::HashMap, @@ -96,15 +84,6 @@ pub struct Facts { /// 叫 `type`,所以「顺手写成 `kind:`」几乎是必然会发生的。没有这一行的 /// 时候它会被静默丢掉,用户得到一个 fallback 组,然后困惑于「我明明配了 /// 负载均衡」。这个项目已经栽过一次同样的(`listen: { addr: ... }`)。 -fn default_true() -> bool { - true -} - -/// 默认值不写进文件。 -fn is_true(b: &bool) -> bool { - *b -} - #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Group { @@ -112,51 +91,18 @@ pub struct Group { #[serde(default, rename = "type")] pub kind: GroupType, pub providers: Vec, - /// 同一个会话固定走同一家,缓存才能保住。 - /// - /// **默认开,而且这个默认值是这一节最重要的一行。**不开的话,一次 - /// 长会话每轮跳一家,prompt cache 全部失效 —— 而缓存命中与否成本 - /// 差 5 到 10 倍。「分散负载」换来的是账单翻几倍,而单用户 - /// 桌面场景根本没有需要分散的负载。 - /// - /// 真想要纯轮询的人写一句 `session_affinity: false`,那是个明确的 - /// 选择;而默认关掉,是让每一个不知道这件事的人默默付那笔钱。 - #[serde(default = "default_true", skip_serializing_if = "is_true")] - pub session_affinity: bool, /// `select` 用:当前选中的那个 #[serde(default, skip_serializing_if = "Option::is_none")] pub selected: Option, } -impl Group { - /// 这个组**按现在这份配置**会不会让 prompt cache 不稳定。 - /// - /// 三种情况分开看: - /// - /// - `load-balance` **开了粘滞就不伤缓存**:同一次对话始终落在同 - /// 一家,缓存该命中还是命中。把它一律标成危险是个假警报,而假 - /// 警报的代价是用户学会忽略这一栏的所有提示(没有风险的 - /// 时候要说「安全」)。 - /// - `url-test` **会伤**:排序随实测延迟变,一次对话中途完全可能 - /// 换家。 - /// - `cheapest` **不伤**:单价在一次对话里不会变,所以顺序是稳的 - /// —— 它换家的时机和 `fallback` 一样,只在上游不健康时。 - pub fn hurts_cache(&self) -> bool { - match self.kind { - GroupType::LoadBalance => !self.session_affinity, - GroupType::UrlTest => true, - GroupType::Fallback | GroupType::Select | GroupType::Cheapest => false, - } - } -} - /// 按策略排序。**纯函数** —— 同样的输入永远给同样的顺序,试算页因此 /// 能如实预告数据面会怎么走。 pub fn order_by(g: &Group, members: &[String], f: &Facts) -> Vec { match g.kind { // 这两种的顺序在 `expand_group` 里就定好了 GroupType::Fallback | GroupType::Select => members.to_vec(), - GroupType::LoadBalance => rotate(g, members, f), + GroupType::LoadBalance => rotate(members, f), GroupType::UrlTest => { // 有样本的按 TTFB 升序;没样本的保持原有相对次序排在后面。 // **`sort_by_key` 是稳定排序**,所以同速的两家不会每次换位 @@ -178,58 +124,22 @@ pub fn order_by(g: &Group, members: &[String], f: &Facts) -> Vec { } } -/// `load-balance` 的轮转。 +/// `load-balance` 的轮转:按 `seq` 轮到谁,谁排头。 /// -/// **认得出会话就固定一家**(不开粘滞的话,长会话每轮跳一家, -/// prompt cache 全废,而缓存命中与否成本差 5 到 10 倍 —— 「分散负载」 -/// 换来的可能是账单翻几倍)。 -/// -/// 认不出会话时按 `seq` 轮转。**选中的那一家排头,其余顺次跟上**, -/// 一个都不少 —— 故障转移还要用它们。 -fn rotate(g: &Group, members: &[String], f: &Facts) -> Vec { +/// **选中的那一家排头,其余顺次跟上**,一个都不少 —— 故障转移还要用它们。 +/// 同一段对话不在这里粘:留在上次回答它的那一家由网关按对话记着,这里只管 +/// 还没人回答过的。 +fn rotate(members: &[String], f: &Facts) -> Vec { if members.is_empty() { return Vec::new(); } - let start = if g.session_affinity { - match &f.session { - // **同一个会话永远落在同一家。**用会话指纹取模,不用计数器 - // —— 计数器会让「重启之后同一个会话换了一家」,而那正是 - // 粘滞要防的 - Some(s) => (hash64(s) % members.len() as u64) as usize, - // **认不出会话就钉住第一家,不要轮转。** - // - // 用户开粘滞是在说「别在一次对话里换家」。认不出这条属于 - // 哪次对话的时候去轮转,做的正好是他要求的反面 —— 而那 - // 时候的代价照样是缓存全废。钉住会让这部分流量集中在一家, - // 但**不均衡是可以看见的,缓存失效不是**。 - None => 0, - } - } else { - (f.seq % members.len() as u64) as usize - }; + let start = (f.seq % members.len() as u64) as usize; let mut out = Vec::with_capacity(members.len()); out.extend_from_slice(&members[start..]); out.extend_from_slice(&members[..start]); out } -/// 会话指纹 → 一个数。FNV-1a。 -/// -/// **不用 `DefaultHasher`。**它是 std 的 SipHash,文档明说不保证跨版本 -/// 稳定 —— 而这个数字决定一次对话钉在哪一家。它一变,所有正在进行的 -/// 会话会在同一时刻集体换家,**一次性把全部 prompt cache 作废**,而 -/// 现场表现只是「今天账单突然高了」,没有任何东西指向一次 Rust 升级。 -/// -/// 自己写五行,换来的是这个映射永远不变。不用于安全,只要稳定。 -fn hash64(s: &str) -> u64 { - let mut h: u64 = 0xcbf2_9ce4_8422_2325; - for b in s.as_bytes() { - h ^= *b as u64; - h = h.wrapping_mul(0x0000_0100_0000_01b3); - } - h -} - /// 改写请求参数。 /// /// **这是和流量代理最本质的分歧**:Clash 的规则只能决定走哪个 @@ -596,7 +506,6 @@ impl Engine { name: ALL_UPSTREAMS.to_string(), kind: GroupType::Fallback, providers: providers.clone(), - session_affinity: false, selected: None, }); } @@ -1251,7 +1160,6 @@ mod tests { name: "pool".into(), kind: GroupType::Fallback, providers: vec!["official".into(), "relay".into()], - session_affinity: false, selected: None, }; let e = Engine::with_default_rules( @@ -1272,7 +1180,6 @@ mod tests { name: "pool".into(), kind: GroupType::Select, providers: vec!["a".into(), "b".into(), "c".into()], - session_affinity: false, selected: Some("b".into()), }; let e = Engine::with_default_rules( @@ -1310,7 +1217,6 @@ mod tests { name: "empty".into(), kind: GroupType::Fallback, providers: vec![], - session_affinity: false, selected: None, }; let e = @@ -1639,12 +1545,7 @@ mod tests { } #[test] - fn only_load_balance_is_flagged_as_bad_for_cache() { - // 这张表要在 UI 上直接显示,因为它决定了用户的账单。 - assert!(!GroupType::Fallback.hurts_cache()); - assert!(!GroupType::Select.hurts_cache()); - assert!(GroupType::LoadBalance.hurts_cache()); - // 而默认必须是不伤缓存的那个 + fn the_default_group_type_is_fallback() { assert_eq!(GroupType::default(), GroupType::Fallback); } @@ -1681,12 +1582,11 @@ mod tests { assert!(e.to_string().contains("ton"), "{e}"); } - fn grp(kind: GroupType, sticky: bool) -> Group { + fn grp(kind: GroupType) -> Group { Group { name: "池子".into(), kind, providers: vec!["甲".into(), "乙".into(), "丙".into()], - session_affinity: sticky, selected: None, } } @@ -1696,7 +1596,7 @@ mod tests { // **这条是回归测试。**曾经 `load-balance` 和 `fallback` 行为完全 // 一样:引擎给出集合,而没有任何一层去转它,于是 6 个请求 6 次 // 落在第一家 —— 一个宣称做完了、实际什么都没做的功能。 - let g = grp(GroupType::LoadBalance, false); + let g = grp(GroupType::LoadBalance); let firsts: Vec = (0..6) .map(|seq| { let f = Facts { @@ -1712,7 +1612,7 @@ mod tests { #[test] fn rotating_keeps_every_candidate_because_failover_still_needs_them() { // 「轮到乙」不等于「甲和丙不要了」——那一家挂了还要能切 - let g = grp(GroupType::LoadBalance, false); + let g = grp(GroupType::LoadBalance); let f = Facts { seq: 1, ..Default::default() @@ -1720,43 +1620,10 @@ mod tests { assert_eq!(order_by(&g, &g.providers, &f), vec!["乙", "丙", "甲"]); } - #[test] - fn session_affinity_pins_one_conversation_to_one_upstream() { - // **不粘的话,长会话每轮跳一家,prompt cache 全废**,而缓存 - // 命中与否成本差 5 到 10 倍 - let g = grp(GroupType::LoadBalance, true); - let mut seen = std::collections::HashSet::new(); - for seq in 0..20 { - let f = Facts { - session: Some("会话-abc".into()), - seq, - ..Default::default() - }; - seen.insert(order_by(&g, &g.providers, &f)[0].clone()); - } - assert_eq!(seen.len(), 1, "同一个会话跳家了:{seen:?}"); - } - - #[test] - fn different_sessions_do_land_on_different_upstreams() { - // 粘滞不能粘成「所有会话都挤在一家」——那就不是均衡了 - let g = grp(GroupType::LoadBalance, true); - let seen: std::collections::HashSet = (0..60) - .map(|i| { - let f = Facts { - session: Some(format!("会话-{i}")), - ..Default::default() - }; - order_by(&g, &g.providers, &f)[0].clone() - }) - .collect(); - assert!(seen.len() > 1, "所有会话都挤在同一家:{seen:?}"); - } - #[test] fn url_test_puts_the_fastest_first_and_the_unmeasured_last() { // **「没测到」不等于「慢」,但排前面就等于放弃了「选最快的」** - let g = grp(GroupType::UrlTest, false); + let g = grp(GroupType::UrlTest); let mut ttfb = std::collections::HashMap::new(); ttfb.insert("丙".to_string(), 120u32); ttfb.insert("甲".to_string(), 400u32); @@ -1771,7 +1638,7 @@ mod tests { #[test] fn two_equally_fast_upstreams_do_not_swap_places_every_request() { // 同速时换来换去会让 prompt cache 白白多断一次 —— 稳定排序 - let g = grp(GroupType::UrlTest, false); + let g = grp(GroupType::UrlTest); let ttfb: std::collections::HashMap = [ ("甲".to_string(), 100u32), ("乙".to_string(), 100), @@ -1792,7 +1659,7 @@ mod tests { fn cheapest_sorts_by_input_price_and_puts_the_unpriced_last() { // **「最便宜」是一句关于钱的承诺** —— 挑一个不知道多少钱的, // 完全可能是最贵的那个 - let g = grp(GroupType::Cheapest, false); + let g = grp(GroupType::Cheapest); let price: std::collections::HashMap = [ ("甲".to_string(), (3_000_000i64, 15_000_000i64)), ("丙".to_string(), (1_800_000, 9_000_000)), @@ -1810,7 +1677,7 @@ mod tests { fn cheapest_uses_the_output_price_only_to_break_a_tie() { let g = Group { providers: vec!["甲".into(), "乙".into()], - ..grp(GroupType::Cheapest, false) + ..grp(GroupType::Cheapest) }; let price: std::collections::HashMap = [ ("甲".to_string(), (1_000i64, 9_000i64)), @@ -1828,7 +1695,7 @@ mod tests { #[test] fn fallback_and_select_never_get_reordered() { for kind in [GroupType::Fallback, GroupType::Select] { - let g = grp(kind, false); + let g = grp(kind); let f = Facts { seq: 7, ttfb_ms: [("丙".to_string(), 1u32)].into_iter().collect(), @@ -1842,66 +1709,16 @@ mod tests { assert!(!kind.needs_runtime()); } } - #[test] - fn the_session_to_slot_mapping_is_frozen_forever() { - // **这条测试就是那个「不许改」的锁。**这个数字决定一次对话钉在 - // 哪一家;改掉它等于让所有正在进行的会话同时换家,一次性作废 - // 全部 prompt cache —— 而现场表现只是「今天账单突然高了」。 - // - // 真要换算法的话,先想清楚怎么让已经在跑的会话平滑过去。 - assert_eq!(hash64(""), 0xcbf2_9ce4_8422_2325); - // 这三个值是用一份独立的 FNV-1a 实现(python)算出来的, - // 不是把这段代码的输出抄回来 —— 后者只能证明它没变,证明不了 - // 它是对的 - assert_eq!(hash64("会话-abc"), 16_378_437_173_232_644_658); - assert_eq!(hash64("a"), 0xaf63_dc4c_8601_ec8c); - } + /// 老配置里的 `session_affinity` 不再认:同一段对话留在哪一家由网关按对话记着, + /// 这一项没有要开关的东西了。**报错而不是静默丢掉**,和别的写错的字段一样 #[test] - fn load_balance_is_sticky_unless_you_explicitly_turn_it_off() { - // **默认值站在缓存这边。**不写 session_affinity 的人,是不知道 - // 这件事的人 —— 而默认关掉就是让他默默付那笔钱 - let y = "name: 池子\ntype: load-balance\nproviders: [甲, 乙]\n"; - let g: Group = serde_yaml_ng::from_str(y).unwrap(); - assert!(g.session_affinity, "默认没开粘滞"); - assert!(!g.hurts_cache(), "开着粘滞还报「会伤缓存」是个假警报"); - - let off: Group = serde_yaml_ng::from_str(&format!("{y}session_affinity: false\n")).unwrap(); - assert!(!off.session_affinity); - assert!(off.hurts_cache(), "关了粘滞就该直说会伤缓存"); - } - - #[test] - fn an_unrecognisable_session_pins_instead_of_rotating() { - // 用户开粘滞是在说「别在一次对话里换家」。认不出这条属于哪次 - // 对话时去轮转,做的正好是他要求的反面 - let g = grp(GroupType::LoadBalance, true); - for seq in 0..6 { - let f = Facts { - session: None, - seq, - ..Default::default() - }; - assert_eq!( - order_by(&g, &g.providers, &f)[0], - "甲", - "认不出会话时还在转" - ); - } - } - - #[test] - fn cheapest_does_not_get_flagged_as_cache_hostile() { - // 单价在一次对话里不会变,所以它的顺序是稳的 —— 换家的时机和 - // fallback 一样,只在上游不健康时。**没有风险的时候要说「安全」** - let mut g = grp(GroupType::Cheapest, false); - g.kind = GroupType::Cheapest; - assert!(!g.hurts_cache()); - let u = Group { - kind: GroupType::UrlTest, - ..g.clone() - }; - assert!(u.hurts_cache(), "url-test 的排序随实测延迟变,会伤"); + fn session_affinity_is_no_longer_a_group_field() { + let e = serde_yaml_ng::from_str::( + "name: g\ntype: load-balance\nproviders: [a]\nsession_affinity: false\n", + ) + .unwrap_err(); + assert!(e.to_string().contains("session_affinity"), "{e}"); } } @@ -2044,7 +1861,6 @@ mod builtin_tests { name: n.into(), kind: GroupType::Fallback, providers: vec!["a".into()], - session_affinity: true, selected: None, }; let e = Engine::with_default_rules( diff --git a/crates/tw-gateway/src/affinity.rs b/crates/tw-gateway/src/affinity.rs new file mode 100644 index 00000000..d1ec9d98 --- /dev/null +++ b/crates/tw-gateway/src/affinity.rs @@ -0,0 +1,584 @@ +//! 一段对话留在上次回答它的那一家;一轮开始时的路由决定沿用到这一轮结束。 +//! +//! **缓存按上游隔离。**客户端每个请求都带着整段对话,上游把读过的开头缓存起来,下 +//! 一个请求读缓存只付一成的价钱。换一家,那一家要全价重算整段上下文 —— 一段长对话 +//! 半路换一次家,就是几十万 token 的全价输入。所以: +//! +//! - **同一轮之内一律不换。**客户端在回传工具结果(agent 还在干这一轮的活)时,路由 +//! 决定不重新求值,上游也留在上次回答的那一家。按输入大小、有没有图片分流的规则, +//! 在一轮里随着上下文变长会翻过去 —— 以前每个请求都重新求值,一轮半路就换了家。 +//! 只有输入超出了所选模型的上下文时才重新求值:那时不换也发不出去。 +//! - **跨轮时看缓存值不值得留**:上一次回答读写了至少 [`CACHE_WORTH`] 个 token 的缓存、 +//! 离现在不到 [`CACHE_COLD_MS`](各家缓存最短的存活时间)才留下。缓存没有或已经 +//! 凉了,留下什么都省不到,策略组照常排序(`load-balance` 就是在这时轮到下一家)。 +//! - **留在「实际回答的那一家」**,不是路由排的头一个:故障转移之后接下回答的备选, +//! 就是之后留下的那一家 —— 缓存在它那儿。 +//! - **那一家不可用(熔断着、冷却中)就放开**,照常排序:留在一家发不出去的上游 +//! 上,省下的缓存一分钱都兑现不了。 +//! +//! 对话按「路由 + 对话标识」记(见 [`Conversation`]),回答的那一家还要对得上策略组: +//! 同一段对话这一轮被规则送去另一个组,上次那一家的缓存和这一组无关。 +//! +//! **只在内存里**,最多记 [`CAP`] 段、每段最多 [`KEEP_MS`]:core 重启之后第一轮 +//! 按策略重新排,最坏是一次缓存重建。**跨配置重载存活**,但沿用的路由决定只在同一 +//! 份配置里有效(配置改了,规则可能已经不是那条了)。 + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, Weak}; + +use axum::http::HeaderMap; +use tw_dialect::ir; +use tw_engine::{Decision, Engine}; + +/// 上一次回答读写了这么多 token 的缓存,跨轮才值得留下。 +/// +/// Anthropic 和 OpenAI 最短能缓存的前缀都是 1024 个 token:少于它,上游本来就不缓存。 +/// **读和写都算**:头一轮往往只有写(上游刚缓存下来),下一轮正是要读它的时候。 +pub const CACHE_WORTH: u64 = 1024; + +/// 上一次回答离现在超过这么久,缓存就当凉了。Anthropic 和 OpenAI 不被读取的缓存 +/// 最短都只存五分钟 +pub const CACHE_COLD_MS: u64 = 5 * 60 * 1000; + +/// 一段对话记多久。一天没动静的对话,缓存早就没了,沿用的路由决定也不再有意义 +pub const KEEP_MS: u64 = 24 * 60 * 60 * 1000; + +/// 最多记几段对话。满了先清掉超期的,还满就清最久没动静的那段 +pub const CAP: usize = 4096; + +/// 客户端自己说出对话身份的请求头:Claude Code、Codex、OpenCode 各有各的写法。 +const SESSION_HEADERS: &[&str] = &[ + "x-claude-code-session-id", + "session_id", + "session-id", + "conversation_id", + "x-session-affinity", + "x-opencode-session", +]; + +/// 这次请求属于哪段对话。 +/// +/// **客户端带着会话头时用它,再加上按内容认的指纹**([`crate::session::fingerprint`])。 +/// 只用会话头不够:Claude Code 的一个会话里还有子代理和起标题这类旁支请求,会话头 +/// 一样,系统提示和首条消息不一样,缓存也各是各的 —— 并成一段的话,旁支请求一来就 +/// 把正在干活的那一轮的记录冲掉。只用指纹也不够:同一个仓库里开头一字不差的两段 +/// 对话会被并成一段。 +/// +/// 两样都没有就是 `None`:认不出来的对话不记,每个请求照常排序。 +pub fn identity(headers: &HeaderMap, fp: Option<&str>) -> Option { + let named = SESSION_HEADERS.iter().find_map(|h| { + headers + .get(*h) + .and_then(|v| v.to_str().ok()) + .map(str::trim) + .filter(|v| !v.is_empty()) + }); + match (named, fp) { + // 会话头是客户端给的原文,不进记录:只留一个指纹 + (Some(named), fp) => { + let h = blake3::hash(format!("{named}\n{}", fp.unwrap_or_default()).as_bytes()); + Some(format!("s-{}", &h.to_hex()[..24])) + } + (None, Some(fp)) => Some(fp.to_string()), + (None, None) => None, + } +} + +/// 对话走到了第几轮。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Turn { + /// 用户说过几次话:带着文字、图片或文件,而不是工具结果的 user 消息 + pub number: u32, + /// 最后一条 user 消息是工具结果:agent 还在这一轮里干活 + pub within: bool, +} + +/// 从请求里的整段对话数出这是第几轮。 +/// +/// **看的是最后一条 user 消息**:agent 可以在工具结果后面附上自己的话(Claude Code +/// 会在同一条消息里跟一段 system-reminder 文字),那还是同一轮 —— 所以一条消息里 +/// 有工具结果,就不算用户又说了一次话。 +pub fn turn_of(r: &ir::Request) -> Turn { + let mut t = Turn::default(); + for m in r.messages.iter().filter(|m| m.role == ir::Role::User) { + let result = m.parts.iter().any(|p| matches!(p, ir::Part::ToolResult(_))); + let said = m.parts.iter().any(|p| { + matches!( + p, + ir::Part::Text(_) | ir::Part::Image(_) | ir::Part::File { .. } + ) + }); + if said && !result { + t.number += 1; + } + t.within = result; + } + t +} + +/// 一段对话在一条路由里的这一轮。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Conversation { + /// 路由名 + 对话标识:不同路由(不同的密钥)里的同一段对话各记各的 + key: String, + pub turn: Turn, +} + +impl Conversation { + pub fn new(route: &str, id: &str, turn: Turn) -> Self { + Self { + key: format!("{route}\n{id}"), + turn, + } + } +} + +/// 一段对话记着的。 +struct Entry { + /// 最后一次动它的时刻:超期和清理都按它 + touched_ms: u64, + /// 这一轮开头定下的路由决定 + held: Option, + /// 上次回答它的那一家 + answer: Option, +} + +struct Held { + turn: u32, + /// 是哪一份配置定的。**配置换了就不沿用**:规则可能已经改了、删了。存弱引用: + /// 旧引擎的那块内存在它还被引用时不会被复用,比较的不会是另一份配置 + engine: Weak, + decision: Decision, +} + +struct Answer { + /// 回答时规则把它交给的策略组。直接指上游的是 None + group: Option, + provider: String, + turn: u32, + at_ms: u64, + /// 那次回答读写的缓存 token + cache: u64, +} + +/// 每段对话的这一轮路由决定、上次回答它的那一家。 +#[derive(Default)] +pub struct Affinity { + entries: Mutex>, +} + +impl Affinity { + fn lock(&self) -> std::sync::MutexGuard<'_, HashMap> { + // 锁中毒了照样拿里面的表:少留一次缓存,好过一个不转发的网关 + self.entries.lock().unwrap_or_else(|p| p.into_inner()) + } + + /// 这一轮开头定下的路由决定。**只在同一轮里、同一份配置下**才有。 + pub fn held(&self, c: &Conversation, engine: &Arc, now_ms: u64) -> Option { + if !c.turn.within { + return None; + } + let map = self.lock(); + let e = map.get(&c.key).filter(|e| fresh(e, now_ms))?; + let h = e.held.as_ref()?; + (h.turn == c.turn.number && Weak::ptr_eq(&h.engine, &Arc::downgrade(engine))) + .then(|| h.decision.clone()) + } + + /// 记下这一轮的路由决定:规则刚求过值的那一个。 + pub fn decided(&self, c: &Conversation, engine: &Arc, d: &Decision, now_ms: u64) { + let held = Held { + turn: c.turn.number, + engine: Arc::downgrade(engine), + decision: d.clone(), + }; + self.upsert(&c.key, now_ms, |e| e.held = Some(held)); + } + + /// 该不该留在上次回答这段对话的那一家。该留就把它挪到 `candidates` 的头上, + /// 交回留下的理由。 + /// + /// `group` 是这次规则交给的策略组;`available` 说一家现在能不能进候选链(熔断、 + /// 冷却)。只剩一个候选时没有「留不留」可言。 + pub fn stay( + &self, + c: &Conversation, + group: Option<&str>, + candidates: &mut Vec, + available: impl Fn(&str) -> bool, + now_ms: u64, + ) -> Option { + if candidates.len() < 2 { + return None; + } + let map = self.lock(); + let a = map + .get(&c.key) + .filter(|e| fresh(e, now_ms))? + .answer + .as_ref()?; + if a.group.as_deref() != group { + return None; + } + let at = candidates.iter().position(|p| *p == a.provider)?; + if !available(&a.provider) { + return None; + } + let why = if c.turn.within && a.turn == c.turn.number { + tw_api::Stay::Turn + } else if a.cache >= CACHE_WORTH && now_ms.saturating_sub(a.at_ms) < CACHE_COLD_MS { + tw_api::Stay::Cache + } else { + return None; + }; + let p = candidates.remove(at); + candidates.insert(0, p); + Some(why) + } + + /// 这段对话这一次由谁回答,交给请求的结局:成功了才记(见 [`Ticket::answered`])。 + pub fn ticket( + self: &Arc, + c: &Conversation, + group: Option, + provider: &str, + ) -> Ticket { + Ticket { + store: Arc::clone(self), + key: c.key.clone(), + group, + provider: provider.to_string(), + turn: c.turn.number, + } + } + + fn answered(&self, t: &Ticket, cache: u64, now_ms: u64) { + let answer = Answer { + group: t.group.clone(), + provider: t.provider.clone(), + turn: t.turn, + at_ms: now_ms, + cache, + }; + self.upsert(&t.key, now_ms, |e| e.answer = Some(answer)); + } + + fn upsert(&self, key: &str, now_ms: u64, f: impl FnOnce(&mut Entry)) { + let mut map = self.lock(); + if !map.contains_key(key) && map.len() >= CAP { + map.retain(|_, e| fresh(e, now_ms)); + if map.len() >= CAP + && let Some(oldest) = map + .iter() + .min_by_key(|(_, e)| e.touched_ms) + .map(|(k, _)| k.clone()) + { + map.remove(&oldest); + } + } + let e = map.entry(key.to_string()).or_insert(Entry { + touched_ms: now_ms, + held: None, + answer: None, + }); + // 超期的整段作废:一天前那一轮的决定和回答,对现在的请求都没有意义 + if !fresh(e, now_ms) { + e.held = None; + e.answer = None; + } + e.touched_ms = e.touched_ms.max(now_ms); + f(e); + } + + #[cfg(test)] + fn tracked(&self) -> usize { + self.lock().len() + } +} + +fn fresh(e: &Entry, now_ms: u64) -> bool { + now_ms.saturating_sub(e.touched_ms) <= KEEP_MS +} + +/// 这一次由谁回答。**跟着请求的结局走**:上游回了成功、响应走完了才记下它和它读写 +/// 了多少缓存(见 [`crate::ending::Ending`])。 +pub struct Ticket { + store: Arc, + key: String, + group: Option, + provider: String, + turn: u32, +} + +impl Ticket { + /// 回答完了:那一家读写了 `cache` 个 token 的缓存。 + pub fn answered(self, cache: u64) { + self.store.answered(&self, cache, crate::server::now_ms()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tw_dialect::ir::{Message, Part, Role, ToolResult}; + + const MIN: u64 = 60_000; + + fn conv(number: u32, within: bool) -> Conversation { + Conversation::new("default", "对话", Turn { number, within }) + } + + fn engine() -> Arc { + Arc::new(Engine::with_default_rules( + vec!["甲".into(), "乙".into()], + vec![], + vec![], + )) + } + + fn decision(rule: &str) -> Decision { + Decision { + candidates: vec!["甲".into(), "乙".into()], + matched_rule: rule.into(), + via_group: Some("池子".into()), + set: Default::default(), + rewritten_by: vec![], + } + } + + fn pool() -> Vec { + vec!["甲".into(), "乙".into(), "丙".into()] + } + + fn answer(a: &Arc, c: &Conversation, provider: &str, cache: u64, at: u64) { + let t = a.ticket(c, Some("池子".into()), provider); + a.answered(&t, cache, at); + } + + fn up(_: &str) -> bool { + true + } + + #[test] + fn a_session_header_names_the_conversation_and_the_content_tells_its_branches_apart() { + let mut h = HeaderMap::new(); + h.insert("x-claude-code-session-id", "sess-1".parse().unwrap()); + let main = identity(&h, Some("主对话")).unwrap(); + // 同一个会话头、同一段内容:同一段对话 + assert_eq!(identity(&h, Some("主对话")), Some(main.clone())); + // 同一个会话头下的旁支请求(子代理、起标题):内容不一样,各是各的 + assert_ne!(identity(&h, Some("子代理")), Some(main.clone())); + // 内容一字不差的两段对话,靠会话头分开 + let mut other = HeaderMap::new(); + other.insert("x-claude-code-session-id", "sess-2".parse().unwrap()); + assert_ne!(identity(&other, Some("主对话")), Some(main.clone())); + // Codex 的写法也认 + let mut codex = HeaderMap::new(); + codex.insert("session_id", "sess-1".parse().unwrap()); + assert!(identity(&codex, Some("主对话")).is_some()); + // 会话头原文不进标识 + assert!(!main.contains("sess-1"), "{main}"); + } + + #[test] + fn without_a_header_the_content_fingerprint_is_the_conversation() { + let h = HeaderMap::new(); + assert_eq!(identity(&h, Some("fp-1")), Some("fp-1".into())); + // 空的会话头不算数 + let mut blank = HeaderMap::new(); + blank.insert("session_id", " ".parse().unwrap()); + assert_eq!(identity(&blank, Some("fp-1")), Some("fp-1".into())); + // 什么都认不出来就不记 + assert_eq!(identity(&h, None), None); + } + + fn user(parts: Vec) -> Message { + Message { + role: Role::User, + parts, + } + } + + fn result() -> Part { + Part::ToolResult(ToolResult { + id: "t".into(), + content: vec![], + is_error: false, + }) + } + + #[test] + fn tool_results_continue_the_turn_and_a_new_user_message_starts_one() { + let text = |s: &str| Part::Text(s.into()); + let mut r = ir::Request { + messages: vec![user(vec![text("改一下")])], + ..Default::default() + }; + assert_eq!( + turn_of(&r), + Turn { + number: 1, + within: false + } + ); + // 工具结果回来了,后面跟着 agent 自己的一段话:还是第一轮 + r.messages.push(Message { + role: Role::Assistant, + parts: vec![], + }); + r.messages + .push(user(vec![result(), text("")])); + assert_eq!( + turn_of(&r), + Turn { + number: 1, + within: true + } + ); + // 用户又说话了:第二轮 + r.messages.push(user(vec![text("再改一下")])); + assert_eq!( + turn_of(&r), + Turn { + number: 2, + within: false + } + ); + } + + #[test] + fn within_a_turn_the_route_decided_at_its_start_is_kept() { + let a = Arc::new(Affinity::default()); + let e = engine(); + // 这一轮开头:规则求值,记下 + a.decided(&conv(3, false), &e, &decision("小输入"), 0); + // 同一轮里的下一个请求:沿用,即使规则现在会给出别的 + assert_eq!( + a.held(&conv(3, true), &e, MIN).map(|d| d.matched_rule), + Some("小输入".into()) + ); + // 新的一轮重新求值 + assert_eq!(a.held(&conv(4, false), &e, MIN), None); + // 轮数对不上(记着的是别的轮)也不沿用 + assert_eq!(a.held(&conv(4, true), &e, MIN), None); + // 配置换了:规则可能已经不是那条了 + assert_eq!(a.held(&conv(3, true), &engine(), MIN), None); + // 另一条路由里的同一段对话各记各的 + let elsewhere = Conversation::new("另一条", "对话", conv(3, true).turn); + assert_eq!(a.held(&elsewhere, &e, MIN), None); + } + + #[test] + fn within_a_turn_the_one_that_answered_stays_first_whatever_its_cache() { + let a = Arc::new(Affinity::default()); + answer(&a, &conv(2, false), "乙", 0, 0); + let mut c = pool(); + assert_eq!( + a.stay(&conv(2, true), Some("池子"), &mut c, up, 30 * MIN), + Some(tw_api::Stay::Turn), + "同一轮里不看缓存、也不看隔了多久" + ); + assert_eq!(c, ["乙", "甲", "丙"], "其余的顺次留着做故障转移"); + } + + #[test] + fn across_turns_it_stays_only_while_the_cache_is_worth_it_and_warm() { + let a = Arc::new(Affinity::default()); + let next = conv(3, false); + // 缓存够、没凉:留 + answer(&a, &conv(2, true), "丙", CACHE_WORTH, 0); + let mut c = pool(); + assert_eq!( + a.stay(&next, Some("池子"), &mut c, up, CACHE_COLD_MS - 1), + Some(tw_api::Stay::Cache) + ); + assert_eq!(c[0], "丙"); + // 凉了:放开,顺序照策略 + let mut c = pool(); + assert_eq!(a.stay(&next, Some("池子"), &mut c, up, CACHE_COLD_MS), None); + assert_eq!(c, pool()); + // 缓存太少:没什么可留的 + answer(&a, &conv(2, true), "丙", CACHE_WORTH - 1, 0); + let mut c = pool(); + assert_eq!(a.stay(&next, Some("池子"), &mut c, up, MIN), None); + assert_eq!(c, pool()); + } + + #[test] + fn a_pinned_upstream_that_is_cooling_down_is_released() { + let a = Arc::new(Affinity::default()); + answer(&a, &conv(1, false), "乙", 50_000, 0); + let mut c = pool(); + let open = |p: &str| p != "乙"; + assert_eq!( + a.stay(&conv(1, true), Some("池子"), &mut c, open, MIN), + None + ); + assert_eq!(c, pool(), "熔断着的那家不该被挪到头上"); + } + + #[test] + fn the_failover_member_that_answered_becomes_the_one_it_stays_on() { + let a = Arc::new(Affinity::default()); + // 路由排的头一个是甲,甲失败、乙接下了回答:记的是乙 + answer(&a, &conv(1, false), "乙", 8_000, 0); + let mut c = pool(); + assert_eq!( + a.stay(&conv(1, true), Some("池子"), &mut c, up, MIN), + Some(tw_api::Stay::Turn) + ); + assert_eq!(c[0], "乙"); + // 下一次又转移到了丙:之后留在丙 + answer(&a, &conv(1, true), "丙", 8_000, 2 * MIN); + let mut c = pool(); + a.stay(&conv(1, true), Some("池子"), &mut c, up, 3 * MIN); + assert_eq!(c[0], "丙"); + } + + #[test] + fn another_group_or_a_member_no_longer_offered_does_not_pin() { + let a = Arc::new(Affinity::default()); + answer(&a, &conv(1, false), "乙", 8_000, 0); + // 这一轮规则把它交给了另一个组 + let mut c = pool(); + assert_eq!( + a.stay(&conv(1, true), Some("别的组"), &mut c, up, MIN), + None + ); + // 那一家不在这次的候选里(停用了、没有这个模型) + let mut c: Vec = vec!["甲".into(), "丙".into()]; + assert_eq!(a.stay(&conv(1, true), Some("池子"), &mut c, up, MIN), None); + // 只有一个候选:没有留不留可言 + let mut c: Vec = vec!["乙".into()]; + assert_eq!(a.stay(&conv(1, true), Some("池子"), &mut c, up, MIN), None); + } + + #[test] + fn a_day_old_conversation_is_forgotten_and_the_table_stays_bounded() { + let a = Arc::new(Affinity::default()); + answer(&a, &conv(1, false), "乙", 8_000, 0); + let mut c = pool(); + assert_eq!( + a.stay(&conv(1, true), Some("池子"), &mut c, up, KEEP_MS + 1), + None + ); + for i in 0..CAP as u64 { + let c = Conversation::new("default", &format!("旧-{i}"), Turn::default()); + answer(&a, &c, "甲", 0, i); + } + assert_eq!(a.tracked(), CAP); + // 满了:清掉最久没动静的那段,新的照样记得住 + answer(&a, &conv(9, false), "丙", 0, CAP as u64); + assert_eq!(a.tracked(), CAP); + let mut c = pool(); + assert_eq!( + a.stay(&conv(9, true), Some("池子"), &mut c, up, CAP as u64 + 1), + Some(tw_api::Stay::Turn) + ); + // 超期的一次清光 + answer(&a, &conv(10, false), "丙", 0, KEEP_MS + CAP as u64 + 10); + let fresh_key = Conversation::new("default", "新的", Turn::default()); + answer(&a, &fresh_key, "丙", 0, 2 * KEEP_MS + CAP as u64 + 10); + assert!(a.tracked() <= 2, "{}", a.tracked()); + } +} diff --git a/crates/tw-gateway/src/ending.rs b/crates/tw-gateway/src/ending.rs index e59e3b42..144c5ceb 100644 --- a/crates/tw-gateway/src/ending.rs +++ b/crates/tw-gateway/src/ending.rs @@ -67,6 +67,9 @@ pub struct Ending { /// 上游在流里报的错:哪一家、原话。**有它就不是成功** —— 响应头是 200,回答却断在了 /// 半路 upstream_error: Option<(String, String)>, + /// 这段对话这一次由谁回答(见 [`crate::affinity`])。**成功走完了才记**:失败的、 + /// 半路断了的不算回答过,下一次照常排序 + answer: Option, /// 报过了。**只能报一次** told: bool, } @@ -131,6 +134,7 @@ impl Ending { opened: None, watch: None, upstream_error: None, + answer: None, told: false, } } @@ -156,6 +160,11 @@ impl Ending { }); } + /// 这一次由谁回答:成功走完时记下它和它读写了多少缓存。 + pub fn answered_by(&mut self, ticket: crate::affinity::Ticket) { + self.answer = Some(ticket); + } + /// 上游的响应头到了。从这里起,客户端再走掉,报出去的取消带着状态码。 pub fn responded(&mut self, status: u16) { self.status = Some(status); @@ -245,6 +254,11 @@ impl Ending { return; } let usage = self.settle(); + if let Some(t) = self.answer.take() + && (200..300).contains(&status) + { + t.answered(usage.as_ref().map_or(0, |u| u.cache_read + u.cache_write)); + } let duration_ms = self.duration_ms(); let tokens_per_sec = rate(self.opened, usage.as_ref(), duration_ms); self.bus.emit(tw_api::Event::RequestFinished { diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 4d9a127d..818346b4 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -6,6 +6,7 @@ //! 时只需要换掉挑选逻辑。 pub mod access; +pub mod affinity; pub mod auth; pub mod bedrock; pub mod bodies; diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index a4bf0a59..0f5cc226 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -280,6 +280,8 @@ pub(crate) struct Choice { pub(crate) group: Option, /// 附加了参数改写的规则 pub(crate) rewritten_by: Vec, + /// 这段对话之前的去向起的作用(见 [`crate::affinity`]) + pub(crate) affinity: Option, } /// 规则做了决定、这个请求却一家上游都不会去时的路由事件:尝试链是空的。 @@ -295,6 +297,7 @@ pub(crate) fn routed_nowhere(id: u64, choice: Choice) -> tw_api::Event { group: choice.group, rewritten_by: choice.rewritten_by, denied_by: None, + affinity: choice.affinity, attempts: Vec::new(), // 一家都没接下:没有哪一家的计费方式可以跟着走 billing: tw_api::Billing::PerToken, diff --git a/crates/tw-gateway/src/server/pipeline.rs b/crates/tw-gateway/src/server/pipeline.rs index be04ca97..242cbe2e 100644 --- a/crates/tw-gateway/src/server/pipeline.rs +++ b/crates/tw-gateway/src/server/pipeline.rs @@ -77,7 +77,8 @@ pub(super) async fn pipeline( } let (reading, fp) = read(&req, intent); - let (choice, decision) = match route(&state, &rt, &req, &reading, fp.as_deref())? { + let conv = conversation(&rt, &req, &reading, fp.as_deref()); + let (choice, decision) = match route(&state, &rt, &req, &reading, conv.as_ref())? { Routed::Go(choice, decision) => (choice, decision), // 规则做了决定,请求却一家上游都不会去。**照样开始、照样报路由**,失败由 // `passthrough` 按这个错误报 —— 不排队:它一个字节都不会发出去 @@ -111,9 +112,17 @@ pub(super) async fn pipeline( ); screen(&state, &rt, &reading, &started)?; let served = hop::try_upstreams(&state, &rt, &req, &reading, &decision, &started).await?; - let ending = ending + let mut ending = ending .take() .expect("written when the start event was emitted"); + // 记下实际回答的那一家:故障转移之后接下的备选,就是这段对话之后留下的那一家 + if let Some(c) = &conv { + ending.answered_by(state.affinity.ticket( + c, + decision.via_group.clone(), + &served.provider.name, + )); + } Ok(relay::respond( &state, &rt, @@ -179,8 +188,8 @@ fn probe(state: &AppState, rt: &Runtime, req: &Inbound) -> Probe { /// 管线第 2 步的前半:读出路由事实,和这段对话的指纹。 /// -/// **只解析一次,指纹也只算一次。**路由要它,会话粘滞的策略组要指纹,开始事件 -/// 归会话也要指纹,而 body 可能有几百 KB —— 解两遍、哈希两遍是白付一份钱。 +/// **只解析一次,指纹也只算一次。**路由要它,认对话(见 `crate::affinity`)要指纹, +/// 开始事件归会话也要指纹,而 body 可能有几百 KB —— 解两遍、哈希两遍是白付一份钱。 /// /// 生成回答的请求解码成中间表示,**四种格式的客户端读出同一份路由事实**。 /// body 解不开时用空的性质走兜底规则。**不要因此拒绝请求** —— 我们的解析器 @@ -203,6 +212,47 @@ fn read(req: &Inbound, intent: String) -> (crate::client_api::Reading, Option, +) -> Option { + let Some(Ok(d)) = &reading.decoded else { + return None; + }; + let id = crate::affinity::identity(&req.headers, fp)?; + Some(crate::affinity::Conversation::new( + rt.engine.route_of(&req.client_name), + &id, + crate::affinity::turn_of(&d.request), + )) +} + +/// 输入超出了这个决定所选模型的上下文窗口:这一轮沿用的决定要重新求值。 +/// +/// 按候选里最小的那个窗口算,留 5% 的余量(输入是估的)。**知道窗口的才算**:价目表 +/// 里没写的模型,说不出它装不装得下,照常沿用。 +fn outgrown( + state: &AppState, + rt: &Runtime, + req: &Inbound, + facts: &tw_engine::RequestFacts, + d: &tw_engine::Decision, +) -> bool { + let book = state.pricing.load(); + rt.engine + .models_asked(rt.engine.rules_for_client(&req.client_name), facts, d) + .iter() + .filter_map(|(p, m)| book.resolve_for(p, m)?.price.max_input_tokens) + .min() + .is_some_and(|limit| facts.input_tokens.saturating_mul(100) >= limit.saturating_mul(95)) +} + /// 管线第 2 步的中段:模型准入。**和 `GET /v1/models` 共用同一个函数** /// —— 列出来的一定能用。 /// @@ -318,37 +368,57 @@ fn route( rt: &Runtime, req: &Inbound, reading: &crate::client_api::Reading, - fp: Option<&str>, + conv: Option<&crate::affinity::Conversation>, ) -> Result { let facts = &reading.facts; let route = rt.engine.route_of(&req.client_name).to_string(); - let mut decision = match rt.engine.route(facts).map_err(|e| { - GatewayError::config(msg!("gw.route.failed", detail = e => "Routing failed: {detail}")) - })? { - tw_engine::Outcome::Route(d) => d, - tw_engine::Outcome::Deny { rule, reason } => { - // **带理由的拒绝。**一个没有理由的拒绝,和一个 bug,在用户 - // 眼里没有区别。 - tracing::info!(%rule, "a rule denied the request"); - let why = GatewayError::denied(msg!( - "gw.route.denied", rule = rule.clone(), reason = reason => - "Rule `{rule}` denied this request: {reason}" - )); - // 拒绝了就什么都没改:累积的改写跟着这个决定一起作废 - let choice = Choice { - route, - rule, - group: None, - rewritten_by: Vec::new(), - }; - return Ok(Routed::Refused(choice, why)); - } + let now = now_ms(); + // 同一轮里沿用这一轮开头的决定:按输入大小、有没有图片分流的规则,不能让一轮 + // 半路换家(见 `crate::affinity`)。输入超出了所选模型的上下文的,重新求值 + let held = conv + .and_then(|c| state.affinity.held(c, &rt.engine, now)) + .filter(|d| !outgrown(state, rt, req, facts, d)); + let held_route = held.is_some(); + let mut decision = match held { + Some(d) => d, + None => match rt.engine.route(facts).map_err(|e| { + GatewayError::config(msg!("gw.route.failed", detail = e => "Routing failed: {detail}")) + })? { + tw_engine::Outcome::Route(d) => { + if let Some(c) = conv { + state.affinity.decided(c, &rt.engine, &d, now); + } + d + } + tw_engine::Outcome::Deny { rule, reason } => { + // **带理由的拒绝。**一个没有理由的拒绝,和一个 bug,在用户 + // 眼里没有区别。 + tracing::info!(%rule, "a rule denied the request"); + let why = GatewayError::denied(msg!( + "gw.route.denied", rule = rule.clone(), reason = reason => + "Rule `{rule}` denied this request: {reason}" + )); + // 拒绝了就什么都没改:累积的改写跟着这个决定一起作废 + let choice = Choice { + route, + rule, + group: None, + rewritten_by: Vec::new(), + affinity: None, + }; + return Ok(Routed::Refused(choice, why)); + } + }, }; - let choice = Choice { + let mut choice = Choice { route, rule: decision.matched_rule.clone(), group: decision.via_group.clone(), rewritten_by: decision.rewritten_by.clone(), + affinity: held_route.then_some(tw_api::AffinityView { + held_route, + stayed: None, + }), }; // 每个候选实际要的模型:规则改写过的按改写后的算。准入、跳过、比价都看它 let asked = rt.engine.models_asked( @@ -398,12 +468,27 @@ fn route( } _ => Default::default(), }, - session: fp.map(str::to_string), }; decision.candidates = rt .engine .order(Some(&gname), &decision.candidates, &facts_rt); } + // 留在上次回答这段对话的那一家:同一轮里一律留,跨轮看缓存值不值得留。**排在 + // 策略组排序之后** —— 该留的时候盖过策略,放开的时候策略照常说了算 + if let Some(c) = conv + && let Some(why) = state.affinity.stay( + c, + decision.via_group.as_deref(), + &mut decision.candidates, + |p| state.health.is_available(p), + now, + ) + { + choice.affinity = Some(tw_api::AffinityView { + held_route, + stayed: Some(why), + }); + } Ok(Routed::Go(choice, decision)) } diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index 83ce16cd..033277a1 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -353,6 +353,7 @@ pub(super) async fn try_upstreams<'a>( group: choice.group.clone(), rewritten_by, denied_by, + affinity: choice.affinity.clone(), attempts: chain, billing: billing.into(), }); diff --git a/crates/tw-gateway/src/server/upgrade.rs b/crates/tw-gateway/src/server/upgrade.rs index 28d8cd92..2cd9d5ea 100644 --- a/crates/tw-gateway/src/server/upgrade.rs +++ b/crates/tw-gateway/src/server/upgrade.rs @@ -89,6 +89,7 @@ pub(super) async fn ws_upgrade( rule, group: None, rewritten_by: Vec::new(), + affinity: None, }; let (id, ending) = open(&choice, "", tw_api::Billing::PerToken); state.bus.emit(super::routed_nowhere(id, choice)); @@ -102,6 +103,8 @@ pub(super) async fn ws_upgrade( rule: decision.matched_rule.clone(), group: decision.via_group.clone(), rewritten_by: Vec::new(), + // WebSocket 那条路一条连接跑好几轮,不按对话记 + affinity: None, }; let (alive, _) = state.health.filter(&decision.candidates); let Some(name) = alive.first().map(|s| s.to_string()) else { diff --git a/crates/tw-gateway/src/state.rs b/crates/tw-gateway/src/state.rs index 6a7a5bb4..eef33be7 100644 --- a/crates/tw-gateway/src/state.rs +++ b/crates/tw-gateway/src/state.rs @@ -207,6 +207,8 @@ pub struct AppState { pub live: crate::live::Live, /// 每段对话此刻归到哪一次会话(见 [`crate::session::Sessions`])。**跨重载存活** pub sessions: Arc, + /// 每段对话这一轮的路由决定、上次回答它的那一家(见 [`crate::affinity`])。**跨重载存活** + pub affinity: Arc, /// Anthropic 流里上游静默多久就补一个 `ping`(见 `relay`)。**测试会把它调短**, /// 否则一条心跳的测试要干等十五秒 pub ping_every: std::time::Duration, @@ -261,6 +263,7 @@ impl AppState { proxies: Arc::new(std::sync::Mutex::new(Default::default())), live: crate::live::Live::default(), sessions: Default::default(), + affinity: Default::default(), ping_every: crate::PING_EVERY, ping_for: crate::PING_FOR, }; diff --git a/crates/tw-gateway/src/ws.rs b/crates/tw-gateway/src/ws.rs index a7f3432e..e73c0152 100644 --- a/crates/tw-gateway/src/ws.rs +++ b/crates/tw-gateway/src/ws.rs @@ -181,6 +181,7 @@ pub async fn proxy( // 升级请求没有正文,没有什么可改写的;第二阶段也不在这条路上跑 rewritten_by: Vec::new(), denied_by: None, + affinity: None, attempts: vec![attempt], billing: billing.into(), }); diff --git a/crates/tw-gateway/tests/affinity.rs b/crates/tw-gateway/tests/affinity.rs new file mode 100644 index 00000000..9ae6669b --- /dev/null +++ b/crates/tw-gateway/tests/affinity.rs @@ -0,0 +1,182 @@ +//! 一段对话留在上次回答它的那一家,一轮开始时的路由决定沿用到这一轮结束 —— +//! 走真实的管线,看路由事件里说的和实际去的那一家。 + +use std::net::SocketAddr; +use std::time::Duration; + +use axum::Router; +use axum::routing::any; +use tokio::sync::broadcast::Receiver; +use tw_api::{AffinityView, Event, Stay}; +use tw_config::{Client, Config, Provider}; +use tw_engine::{RouteSet, Rule}; + +/// 回一个读了 5000 token 缓存的回答:跨轮值得留 +async fn upstream() -> SocketAddr { + let app = Router::new().fallback(any(|| async { + axum::response::Response::builder() + .header("content-type", "application/json") + .body(axum::body::Body::from( + r#"{"type":"message","content":[],"usage":{"input_tokens":3,"cache_read_input_tokens":5000,"output_tokens":1}}"#, + )) + .unwrap() + })); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let a = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + a +} + +fn provider(name: &str, up: SocketAddr) -> Provider { + Provider { + name: name.into(), + base_url: format!("http://{up}"), + key: Some("sk-x".into()), + protocol: Some(tw_config::Protocol::Anthropic), + ..Default::default() + } +} + +fn rule(name: &str, when: &str, to: &str) -> Rule { + Rule { + name: name.into(), + when: serde_yaml_ng::from_str(when).unwrap(), + to: Some(to.into()), + set: None, + deny: None, + } +} + +/// 输入大的直接去乙,其余在甲乙之间轮流 +fn cfg(up: SocketAddr) -> Config { + Config { + clients: vec![Client { + name: "我".into(), + key: "tw-k".into(), + ..Default::default() + }], + providers: vec![provider("甲", up), provider("乙", up)], + groups: vec![tw_engine::Group { + name: "池".into(), + kind: tw_engine::GroupType::LoadBalance, + providers: vec!["甲".into(), "乙".into()], + selected: None, + }], + routes: vec![RouteSet::default_with(vec![ + rule("大输入", "{ input_tokens: \">2000\" }", "乙"), + rule("轮流", "{}", "池"), + ])], + ..Default::default() + } +} + +async fn serve(cfg: Config) -> (SocketAddr, Receiver) { + let state = tw_gateway::AppState::new(cfg).unwrap(); + let events = state.bus.subscribe(); + let addr = tw_gateway::serve(state, ([127, 0, 0, 1], 0).into()) + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + (addr, events) +} + +/// 发一个请求,交回它的路由事件:规则、实际回答的那一家、`affinity` +async fn ask( + gw: SocketAddr, + rx: &mut Receiver, + messages: &str, +) -> (String, String, Option) { + let body = format!( + r#"{{"model":"claude-sonnet-4-5","max_tokens":16,"system":"你是一个助手","messages":{messages}}}"# + ); + let st = reqwest::Client::builder() + .no_proxy() + .build() + .unwrap() + .post(format!("http://{gw}/v1/messages")) + .header("x-api-key", "tw-k") + .header("x-claude-code-session-id", "会话-1") + .body(body) + .send() + .await + .unwrap() + .status(); + assert_eq!(st, 200); + let mut routed = None; + loop { + let ev = tokio::time::timeout(Duration::from_secs(5), rx.recv()) + .await + .expect("5 秒内没等到结局") + .expect("事件流断了"); + match ev { + Event::RequestRouted { + rule, + attempts, + affinity, + .. + } => routed = Some((rule, attempts.last().unwrap().provider.clone(), affinity)), + Event::RequestFinished { .. } => return routed.expect("没有路由事件"), + Event::RequestFailed { message, .. } => panic!("失败了:{message:?}"), + _ => {} + } + } +} + +fn user(text: &str) -> String { + format!(r#"{{"role":"user","content":"{text}"}}"#) +} + +fn tool_round(i: usize, output: &str) -> String { + format!( + r#"{{"role":"assistant","content":[{{"type":"tool_use","id":"t{i}","name":"Read","input":{{}}}}]}},{{"role":"user","content":[{{"type":"tool_result","tool_use_id":"t{i}","content":"{output}"}}]}}"# + ) +} + +#[tokio::test] +async fn a_turn_keeps_its_route_and_upstream_and_a_warm_cache_keeps_the_next_turn() { + let up = upstream().await; + let (gw, mut rx) = serve(cfg(up)).await; + // 大到让「大输入」那条规则命中 + let big = "读到的文件内容 ".repeat(1500); + + // 第一轮开头:输入小,轮到池子里的某一家 + let first = user("帮我重构"); + let (rule, answered, affinity) = ask(gw, &mut rx, &format!("[{first}]")).await; + assert_eq!(rule, "轮流"); + assert_eq!(affinity, None, "头一次没什么可沿用的"); + + // 同一轮里工具结果回来了,输入变大:**规则不重新求值,也不换家** + let (rule, again, affinity) = + ask(gw, &mut rx, &format!("[{first},{}]", tool_round(1, &big))).await; + assert_eq!(rule, "轮流", "一轮半路按输入大小换了规则"); + assert_eq!(again, answered, "一轮半路换了家"); + assert_eq!( + affinity, + Some(AffinityView { + held_route: true, + stayed: Some(Stay::Turn), + }) + ); + + // 新的一轮、输入小:规则重新求值,上一次读了 5000 token 缓存、刚刚才答 —— 留下 + let history = format!( + "{first},{},{{\"role\":\"assistant\",\"content\":\"好了\"}}", + tool_round(1, "短") + ); + let (rule, stayed, affinity) = + ask(gw, &mut rx, &format!("[{history},{}]", user("再加个测试"))).await; + assert_eq!(rule, "轮流"); + assert_eq!(stayed, answered, "缓存热着,新的一轮却轮到了别家"); + assert_eq!( + affinity, + Some(AffinityView { + held_route: false, + stayed: Some(Stay::Cache), + }) + ); + + // 新的一轮、输入大:重新求值,命中「大输入」 + let (rule, to, _) = ask(gw, &mut rx, &format!("[{history},{}]", user(&big))).await; + assert_eq!(rule, "大输入"); + assert_eq!(to, "乙"); +} diff --git a/crates/tw-gateway/tests/passthrough.rs b/crates/tw-gateway/tests/passthrough.rs index c18b9405..6aaa0c99 100644 --- a/crates/tw-gateway/tests/passthrough.rs +++ b/crates/tw-gateway/tests/passthrough.rs @@ -1029,7 +1029,6 @@ async fn a_phase_two_rule_is_recomputed_after_failover() { name: "全部".into(), kind: tw_engine::GroupType::Fallback, providers: vec!["official".into(), "relay".into()], - session_affinity: false, selected: None, }]; cfg.routes[0].rules.last_mut().unwrap().to = Some("全部".into()); @@ -1167,7 +1166,6 @@ async fn a_phase_one_set_applies_on_every_attempt_including_after_failover() { name: "全部".into(), kind: tw_engine::GroupType::Fallback, providers: vec!["dead".into(), "good".into()], - session_affinity: false, selected: None, }]; let gw = serve_cfg(cfg).await; @@ -1978,7 +1976,6 @@ async fn the_attempt_chain_records_every_hop_and_why_each_one_failed() { name: "全部".into(), kind: tw_engine::GroupType::Fallback, providers: vec!["挂了的".into(), "限流的".into(), "好的".into()], - session_affinity: false, selected: None, }]; cfg.routes = vec![tw_engine::RouteSet::default_with(vec![tw_engine::Rule { diff --git a/crates/tw-gateway/tests/routing_facts.rs b/crates/tw-gateway/tests/routing_facts.rs index 3be83eca..08c62e7e 100644 --- a/crates/tw-gateway/tests/routing_facts.rs +++ b/crates/tw-gateway/tests/routing_facts.rs @@ -78,7 +78,6 @@ fn cfg(providers: Vec, rules: Vec) -> Config { name: "池".into(), kind: tw_engine::GroupType::Fallback, providers: vec!["up".into()], - session_affinity: false, selected: None, }], routes: vec![ diff --git a/crates/tw-gateway/tests/ws.rs b/crates/tw-gateway/tests/ws.rs index e017d4a1..36f6e417 100644 --- a/crates/tw-gateway/tests/ws.rs +++ b/crates/tw-gateway/tests/ws.rs @@ -305,7 +305,6 @@ fn routed_to_an_account(up: SocketAddr) -> Config { name: "账号池".into(), kind: tw_engine::GroupType::Fallback, providers: vec!["订阅账号".into()], - session_affinity: false, selected: None, }], routes: vec![tw_engine::RouteSet::default_with(vec![tw_engine::Rule { diff --git a/crates/tw-observe/src/bus.rs b/crates/tw-observe/src/bus.rs index 78214959..c683d5cd 100644 --- a/crates/tw-observe/src/bus.rs +++ b/crates/tw-observe/src/bus.rs @@ -420,6 +420,7 @@ mod tests { group: Some("__all__".into()), rewritten_by: vec![], denied_by: None, + affinity: None, attempts: vec![ tw_api::AttemptView { provider: "p".into(), diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index aee39a15..5d5f6ff2 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -2627,6 +2627,7 @@ mod route_stats_tests { group: None, rewritten_by: rewritten_by.iter().map(|s| s.to_string()).collect(), denied_by: denied_by.map(str::to_string), + affinity: None, attempts: vec![], }) .unwrap(), diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 8e1b4ff9..c281bbc0 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -230,6 +230,7 @@ impl Recorder { group: group.clone(), rewritten_by: rewritten_by.clone(), denied_by: None, + affinity: None, attempts: Vec::new(), }, billing: *billing, @@ -245,6 +246,7 @@ impl Recorder { group, rewritten_by, denied_by, + affinity, attempts, billing, } => { @@ -270,6 +272,7 @@ impl Recorder { group: group.clone(), rewritten_by: rewritten_by.clone(), denied_by: denied_by.clone(), + affinity: affinity.clone(), attempts: attempts.clone(), }; p.billing = *billing; @@ -823,6 +826,7 @@ mod tests { group: Some("__all__".into()), rewritten_by: vec![], denied_by: None, + affinity: None, attempts: vec![ tw_api::AttemptView { provider: "官方".into(), @@ -879,6 +883,7 @@ mod tests { group: None, rewritten_by: vec![], denied_by: None, + affinity: None, attempts: vec![tw_api::AttemptView { provider: "官方".into(), model: None, @@ -906,6 +911,7 @@ mod tests { group: None, rewritten_by: vec!["换成 Haiku".into()], denied_by: None, + affinity: None, attempts: vec![ tw_api::AttemptView { provider: "官方".into(), @@ -985,6 +991,7 @@ mod tests { group: Some("pool".into()), rewritten_by: vec!["关掉思考".into(), "走中转时限长".into()], denied_by: Some("中转不收密钥".into()), + affinity: None, attempts: vec![tw_api::AttemptView { provider: "中转".into(), model: None, @@ -1329,6 +1336,7 @@ mod billing_tests { group: None, rewritten_by: vec![], denied_by: None, + affinity: None, attempts: vec![tw_api::AttemptView { provider: "订阅账号".into(), model: None, @@ -1414,6 +1422,7 @@ mod billing_tests { group: Some("__all__".into()), rewritten_by: vec![], denied_by: None, + affinity: None, attempts: vec![tw_api::AttemptView { provider: "订阅账号".into(), model: None, @@ -1790,6 +1799,7 @@ mod translation_tests { group: None, rewritten_by: vec![], denied_by: None, + affinity: None, attempts: chain .iter() .map(|p| tw_api::AttemptView { diff --git a/docs/config.md b/docs/config.md index 19df823f..4e1bfa8b 100644 --- a/docs/config.md +++ b/docs/config.md @@ -827,15 +827,25 @@ group with `to`. | Field | Type | Default | Description | |---|---|---|---| | `name` | string | **required** | Name of the group; unique, and not the name of an upstream. | -| `type` | `fallback` \| `select` \| `load-balance` \| `url-test` \| `cheapest` | `fallback` | `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. | +| `type` | `fallback` \| `select` \| `load-balance` \| `url-test` \| `cheapest` | `fallback` | `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. | | `providers` | list of strings | **required** | Member upstreams, by name. | -| `session_affinity` | bool | `true` | 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. | | `selected` | string | — | For `select`: the chosen member. | -`fallback` is the default because spreading a session across upstreams -loses the prompt cache, which is worth far more than any spread of load on -a single user's machine. +`fallback` is the default because a single user's machine has no load to +spread. + +Whatever the type, a conversation stays on the upstream that last answered +it, so that what the upstream holds of it in its prompt cache is read again +rather than paid for in full elsewhere. Within a turn (while the client sends +tool results back) it always stays; across turns it stays while the previous +answer read or wrote at least 1024 tokens of prompt cache and came less than +five minutes ago. An upstream that is cooling down after failures releases +the conversation, and whichever upstream answered after a failover is the one +it stays on. The rule a turn matched at its start also holds for the rest of +that turn: rules keyed on input size or images do not move a turn halfway, +unless its input no longer fits the context window of a model the rule sends +it to. `load-balance` therefore takes turns between new conversations. ### `routes` diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index 8ec901c4..1116041c 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -696,13 +696,14 @@ security: | 字段 | 类型 | 默认值 | 说明 | |---|---|---|---| | `name` | 字符串 | **必填** | 策略组的名字,不能重复,也不能和上游同名。 | -| `type` | `fallback` \| `select` \| `load-balance` \| `url-test` \| `cheapest` | `fallback` | `fallback`:按顺序取第一个健康的。`select`:取 `selected` 指定的那个。`load-balance`:轮流。`url-test`:按实测首字节时间取最快的。`cheapest`:取输入单价最低的。 | +| `type` | `fallback` \| `select` \| `load-balance` \| `url-test` \| `cheapest` | `fallback` | `fallback`:按顺序取第一个健康的。`select`:取 `selected` 指定的那个。`load-balance`:新对话轮流。`url-test`:按实测首字节时间取最快的。`cheapest`:取输入单价最低的。 | | `providers` | 字符串列表 | **必填** | 成员上游的名字。 | -| `session_affinity` | 布尔 | `true` | 同一会话固定走同一家,使 prompt cache 持续命中。在 `load-balance` 下关闭会让每一轮都换一家,缓存随之失效。 | | `selected` | 字符串 | — | `select` 类型选中的成员。 | -默认类型为 `fallback`:把一个会话分散到多家上游会丢掉 prompt cache,而在单个使用者的机器上,分散负载换来的远不及缓存省下的。 +默认类型为 `fallback`:单个使用者的机器上没有需要分散的负载。 + +无论哪种类型,一段对话都留在上次回答它的那一家上游,让上游缓存着的那部分被再次读取,而不是换一家全价重算。同一轮之内(客户端正在回传工具结果)一律不换;跨轮时,上一次回答读或写了至少 1024 个 token 的 prompt cache、且距今不到五分钟,才继续留下。上游因失败进入冷却时,对话随之放开;故障转移之后接下回答的那一家,就是之后留下的那一家。一轮开始时命中的规则也沿用到这一轮结束:按输入大小或图片分流的规则不会让一轮半路换家,除非输入已经超出规则所指模型的上下文窗口。因此 `load-balance` 轮流的是新对话。 ### `routes`