From 2d8023c9286d152f01766b8fe0ace4058bc81af9 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 17 Sep 2026 15:31:34 +0800 Subject: [PATCH] fix(engine): anchor the text after the last `*` at the end of a model name `glob_match` looked for each literal segment from left to right and stopped at its first occurrence. The segment after the last `*` therefore only matched when its first occurrence happened to end the name: `*-mini` did not match `gpt-4o-mini-2024-mini`, and `a*b` did not match `abab`. The same matcher decides a routing rule's `when.model`, which models a key's `allow` list shows, and an upstream's `models_only`. A pattern written this way silently left out models it names, and the desktop app mirrors the matcher to show the enabled scope, so both sides were wrong the same way. The first and last segments are now anchored to the start and the end and may not overlap; the segments in between are found left to right in what remains, which is enough when `*` is the only wildcard. A test compares the matcher with a backtracking one on every pattern of up to five characters over `a`, `b` and `*` against every string of up to six characters. Bumps the workspace to 0.2.2 so the desktop app can pin the fix. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 40 +++++++-------- Cargo.toml | 2 +- crates/tw-engine/src/rule.rs | 95 ++++++++++++++++++++++++++++++------ 3 files changed, 101 insertions(+), 36 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b3ded576..472ea070 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2775,7 +2775,7 @@ dependencies = [ [[package]] name = "tw-adopt" -version = "0.2.1" +version = "0.2.2" dependencies = [ "serde", "serde_json", @@ -2789,7 +2789,7 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.2.1" +version = "0.2.2" dependencies = [ "serde", "serde_json", @@ -2797,7 +2797,7 @@ dependencies = [ [[package]] name = "tw-config" -version = "0.2.1" +version = "0.2.2" dependencies = [ "blake3", "notify", @@ -2817,7 +2817,7 @@ dependencies = [ [[package]] name = "tw-control" -version = "0.2.1" +version = "0.2.2" dependencies = [ "axum", "bytes", @@ -2852,7 +2852,7 @@ dependencies = [ [[package]] name = "tw-crypto" -version = "0.2.1" +version = "0.2.2" dependencies = [ "aes-gcm", "anyhow", @@ -2864,7 +2864,7 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.2.1" +version = "0.2.2" dependencies = [ "serde", "serde_json", @@ -2872,7 +2872,7 @@ dependencies = [ [[package]] name = "tw-engine" -version = "0.2.1" +version = "0.2.2" dependencies = [ "serde", "serde_json", @@ -2884,7 +2884,7 @@ dependencies = [ [[package]] name = "tw-gateway" -version = "0.2.1" +version = "0.2.2" dependencies = [ "arc-swap", "async-stream", @@ -2924,7 +2924,7 @@ dependencies = [ [[package]] name = "tw-observe" -version = "0.2.1" +version = "0.2.2" dependencies = [ "tokio", "tracing", @@ -2933,7 +2933,7 @@ dependencies = [ [[package]] name = "tw-pricing" -version = "0.2.1" +version = "0.2.2" dependencies = [ "arc-swap", "flate2", @@ -2945,7 +2945,7 @@ dependencies = [ [[package]] name = "tw-protocol" -version = "0.2.1" +version = "0.2.2" dependencies = [ "bytes", "futures", @@ -2957,7 +2957,7 @@ dependencies = [ [[package]] name = "tw-provider" -version = "0.2.1" +version = "0.2.2" dependencies = [ "async-stream", "aws-credential-types", @@ -2982,7 +2982,7 @@ dependencies = [ [[package]] name = "tw-redact" -version = "0.2.1" +version = "0.2.2" dependencies = [ "base64", "serde", @@ -2992,7 +2992,7 @@ dependencies = [ [[package]] name = "tw-resil" -version = "0.2.1" +version = "0.2.2" dependencies = [ "futures", "metrics", @@ -3005,7 +3005,7 @@ dependencies = [ [[package]] name = "tw-scan" -version = "0.2.1" +version = "0.2.2" dependencies = [ "notify", "regex", @@ -3022,14 +3022,14 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.2.1" +version = "0.2.2" dependencies = [ "thiserror", ] [[package]] name = "tw-store" -version = "0.2.1" +version = "0.2.2" dependencies = [ "bytes", "libc", @@ -3047,7 +3047,7 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.2.1" +version = "0.2.2" dependencies = [ "serde", "serde_json", @@ -3056,7 +3056,7 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.2.1" +version = "0.2.2" dependencies = [ "saphyr-parser", "serde_yaml_ng", @@ -3065,7 +3065,7 @@ dependencies = [ [[package]] name = "twcore" -version = "0.2.1" +version = "0.2.2" dependencies = [ "anyhow", "chrono", diff --git a/Cargo.toml b/Cargo.toml index c9c43127..b6eed9da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ repository = "https://github.com/ThinkWatchProject/ThinkWatch-Core" # 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。 # 这里是 crate 的版本。 -version = "0.2.1" +version = "0.2.2" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── diff --git a/crates/tw-engine/src/rule.rs b/crates/tw-engine/src/rule.rs index 0d26901e..3eb4c1b4 100644 --- a/crates/tw-engine/src/rule.rs +++ b/crates/tw-engine/src/rule.rs @@ -210,27 +210,30 @@ pub enum MatchError { pub fn glob_match(pattern: &str, s: &str) -> bool { // 大小写不敏感:上游对模型名的大小写并不一致,而用户不该关心这个。 let (pattern, s) = (pattern.to_ascii_lowercase(), s.to_ascii_lowercase()); - let mut parts = pattern.split('*'); - let Some(first) = parts.next() else { - return true; + let parts: Vec<&str> = pattern.split('*').collect(); + let [first, middle @ .., last] = parts.as_slice() else { + // 没有 `*`:精确匹配 + return pattern == s; }; - if !s.starts_with(first) { + // **头尾各自锚定,再在中间找其余几段。**只从左往右找的话,最后一段会 + // 停在它第一次出现的地方:`*-mini` 对 `gpt-4o-mini-2024-mini` 就判成不 + // 匹配,而它明明以 `-mini` 结尾。 + // + // 头尾不能重叠:`ab*ba` 不匹配 `aba`。 + if s.len() < first.len() + last.len() || !s.starts_with(first) || !s.ends_with(last) { return false; } - let mut pos = first.len(); - let mut last_was_star = pattern.len() > first.len(); - for part in parts { - if part.is_empty() { - last_was_star = true; - continue; - } - match s[pos..].find(part) { - Some(i) => pos += i + part.len(), + // 小写化不改变字节长度,而头尾都是完整的 str,切出来的边界一定合法 + let mut rest = &s[first.len()..s.len() - last.len()]; + // 中间几段取最左边的出现位置:只有 `*` 一种通配符时,这样找不会错过 + // 任何一种匹配 + for part in middle { + match rest.find(part) { + Some(i) => rest = &rest[i + part.len()..], None => return false, } - last_was_star = false; } - last_was_star || pos == s.len() + true } #[cfg(test)] @@ -267,6 +270,68 @@ mod tests { assert!(glob_match("*", "anything")); } + #[test] + fn the_part_after_the_last_star_anchors_at_the_end() { + // 结尾那一段在前面也出现过:只从左往右找会停在第一次出现的地方 + assert!(glob_match("*-mini", "gpt-4o-mini-2024-mini")); + assert!(glob_match("gpt-*-mini", "gpt-4o-mini-realtime-mini")); + assert!(glob_match("a*b", "abxb")); + assert!(!glob_match("*-mini", "gpt-4o-mini-2024")); + // 头尾不能共用同一段字符 + assert!(!glob_match("ab*ba", "aba")); + assert!(glob_match("ab*ba", "abba")); + } + + /// 参考实现:逐字符回溯。慢,但一眼能看出是对的。 + fn reference(p: &[u8], s: &[u8]) -> bool { + match (p.first(), s.first()) { + (None, None) => true, + (None, Some(_)) => false, + (Some(b'*'), _) => reference(&p[1..], s) || (!s.is_empty() && reference(p, &s[1..])), + (Some(c), Some(d)) => c == d && reference(&p[1..], &s[1..]), + (Some(_), None) => false, + } + } + + #[test] + fn agrees_with_a_backtracking_matcher_on_every_short_input() { + // 字母表只要 `a` `b` 两个字母加 `*`:能出现「一段在前面重复出现」的 + // 全部形状,而穷举的规模还很小(模式 ≤ 5 个字符,字符串 ≤ 6 个) + fn all(alphabet: &[u8], max: usize) -> Vec> { + let mut out = vec![Vec::new()]; + let mut layer = vec![Vec::new()]; + for _ in 0..max { + layer = layer + .iter() + .flat_map(|w| { + alphabet.iter().map(move |c| { + let mut w = w.clone(); + w.push(*c); + w + }) + }) + .collect(); + out.extend(layer.iter().cloned()); + } + out + } + let patterns = all(b"ab*", 5); + let strings = all(b"ab", 6); + for p in &patterns { + for s in &strings { + let (ps, ss) = ( + std::str::from_utf8(p).unwrap(), + std::str::from_utf8(s).unwrap(), + ); + assert_eq!( + glob_match(ps, ss), + reference(p, s), + "pattern `{ps}` against `{ss}`" + ); + } + } + } + #[test] fn model_matching_ignores_case() { // 上游对模型名的大小写并不一致,而用户不该为此写两条规则。