From d05c1a6b81ce6f020b93b7c83b99c9775b483f26 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 24 Sep 2026 10:36:28 +0800 Subject: [PATCH] feat: one circuit-breaker state machine, and hidden characters in requests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The AI gateway's route health and the MCP gateway's server breaker each carried their own state machine, and the desktop gateway a third. They now all run thinkwatch-core's tw-breaker; what differs between them — where the state lives, what trips it — stays with each. Route health (Redis, shared by replicas, tripped by an error rate): - One Lua call inserts the sample, trims and tallies the window and reads the breaker; the transition is computed from that tally with the shared machine and written back only when it changes, by compare-and-set, so two replicas that read the same state cannot both write. - **A tripped route came back only when its Redis key expired.** It moved from open to half-open only when a request on it completed, and an open route is never picked. A cooled breaker now reads as half-open, the next request probes it, and a success closes it. The new integration test fails on dev with "All routes failed" after the cooldown. - The router and the route-health page read one `CircuitBreakerConfig`. With the breaker disabled, a route reads as closed instead of keeping whatever state it last had. MCP breaker: the same machine in process, keyed by server id, transitions mirrored to the dashboard registry as before. Its API is synchronous now. Dashboard: **every AI provider read `Closed`** — the registry it looked in is process-local and only the MCP breaker wrote to it. AI rows now read their routes' real state from Redis, a provider showing its worst route. Hidden characters: Unicode tag characters carry an instruction invisibly into the model's context, and bidi overrides make text read differently on screen than it is. `security.hidden_text` (off / log / warn / block, default warn) checks the caller's messages and the tool results inside them — where a fetched page smuggles one in — using tw-guard's scanner. Only those two kinds are flagged: zero-width joiners make emoji, Persian needs the non-joiner, Cyrillic is Russian. Warn writes `gateway.hidden_text_flagged` to the audit log; block refuses with 403 and writes `gateway.hidden_text_blocked`. The security page gets a card. Pins core v0.40.0. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 40 +- Cargo.toml | 14 +- crates/common/Cargo.toml | 1 + crates/common/src/cb_registry.rs | 77 ++- crates/gateway/Cargo.toml | 1 + crates/gateway/src/health.rs | 481 +++++++++--------- crates/gateway/src/hidden_text.rs | 195 +++++++ crates/gateway/src/lib.rs | 1 + crates/gateway/src/proxy/generate.rs | 41 ++ crates/gateway/src/proxy/routing.rs | 16 +- crates/mcp-gateway/Cargo.toml | 1 + crates/mcp-gateway/src/circuit_breaker.rs | 323 ++++-------- crates/mcp-gateway/src/lifecycle/mod.rs | 3 +- .../src/lifecycle/stages/check_breaker.rs | 2 +- crates/mcp-gateway/src/proxy.rs | 8 +- crates/server/Cargo.toml | 1 + crates/server/src/app.rs | 5 +- crates/server/src/handlers/admin/settings.rs | 9 + crates/server/src/handlers/dashboard/live.rs | 61 ++- crates/server/src/handlers/mcp_servers.rs | 8 +- .../src/handlers/route_observability.rs | 4 +- crates/test-support/tests/gateway_failover.rs | 145 ++++++ crates/test-support/tests/hidden_text.rs | 145 ++++++ db/seeds.sql | 1 + web/src/i18n/en.json | 7 + web/src/i18n/zh.json | 7 + web/src/routes/admin/settings/types.ts | 7 + web/src/routes/gateway/hidden-text-card.tsx | 62 +++ web/src/routes/gateway/security.tsx | 12 + 29 files changed, 1117 insertions(+), 561 deletions(-) create mode 100644 crates/gateway/src/hidden_text.rs create mode 100644 crates/test-support/tests/hidden_text.rs create mode 100644 web/src/routes/gateway/hidden-text-card.tsx diff --git a/Cargo.lock b/Cargo.lock index d777c943..bad5dfe3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4094,6 +4094,7 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tracing", + "tw-breaker", "tw-crypto", "tw-guard", "url", @@ -4134,6 +4135,7 @@ dependencies = [ "tokio", "tokio-stream", "tracing", + "tw-breaker", "tw-dialect", "tw-guard", "tw-types", @@ -4168,6 +4170,7 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tracing", + "tw-breaker", "tw-crypto", "uuid", "xxhash-rust", @@ -4213,6 +4216,7 @@ dependencies = [ "tower-http", "tracing", "tracing-subscriber", + "tw-breaker", "tw-crypto", "tw-dialect", "tw-guard", @@ -4673,10 +4677,18 @@ dependencies = [ "utf-8", ] +[[package]] +name = "tw-breaker" +version = "0.40.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.40.0#579217ac4addeceb0858c7b744dd9fc38a2a070c" +dependencies = [ + "serde", +] + [[package]] name = "tw-crypto" -version = "0.38.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.38.0#f4d406753e8a5d9f8c02b5ce49ca61658d12a37c" +version = "0.40.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.40.0#579217ac4addeceb0858c7b744dd9fc38a2a070c" dependencies = [ "aes-gcm", "anyhow", @@ -4688,8 +4700,8 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.38.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.38.0#f4d406753e8a5d9f8c02b5ce49ca61658d12a37c" +version = "0.40.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.40.0#579217ac4addeceb0858c7b744dd9fc38a2a070c" dependencies = [ "serde", "serde_json", @@ -4697,8 +4709,8 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.38.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.38.0#f4d406753e8a5d9f8c02b5ce49ca61658d12a37c" +version = "0.40.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.40.0#579217ac4addeceb0858c7b744dd9fc38a2a070c" dependencies = [ "base64 0.22.1", "regex", @@ -4712,16 +4724,16 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.38.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.38.0#f4d406753e8a5d9f8c02b5ce49ca61658d12a37c" +version = "0.40.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.40.0#579217ac4addeceb0858c7b744dd9fc38a2a070c" dependencies = [ "thiserror 2.0.18", ] [[package]] name = "tw-types" -version = "0.38.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.38.0#f4d406753e8a5d9f8c02b5ce49ca61658d12a37c" +version = "0.40.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.40.0#579217ac4addeceb0858c7b744dd9fc38a2a070c" dependencies = [ "serde", "serde_json", @@ -4730,8 +4742,8 @@ dependencies = [ [[package]] name = "tw-upstream" -version = "0.38.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.38.0#f4d406753e8a5d9f8c02b5ce49ca61658d12a37c" +version = "0.40.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.40.0#579217ac4addeceb0858c7b744dd9fc38a2a070c" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -4744,8 +4756,8 @@ dependencies = [ [[package]] name = "tw-wire" -version = "0.38.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.38.0#f4d406753e8a5d9f8c02b5ce49ca61658d12a37c" +version = "0.40.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.40.0#579217ac4addeceb0858c7b744dd9fc38a2a070c" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 0f7baebe..72d702cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -54,12 +54,13 @@ debug = "line-tables-only" # One copy, not two. Code that lives in core is used from core directly, # never re-exported through a local shim — the envelope layout in # tw-crypto already drifted by 61 lines once, while two copies existed. -tw-crypto = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.38.0" } -tw-dialect = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.38.0" } -tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.38.0" } -tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.38.0" } -tw-upstream = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.38.0" } -tw-wire = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.38.0" } +tw-breaker = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.40.0" } +tw-crypto = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.40.0" } +tw-dialect = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.40.0" } +tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.40.0" } +tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.40.0" } +tw-upstream = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.40.0" } +tw-wire = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.40.0" } # Web framework axum = { version = "0.8", features = ["macros", "ws"] } @@ -150,3 +151,4 @@ think-watch-auth = { path = "crates/auth" } think-watch-gateway = { path = "crates/gateway" } think-watch-mcp-gateway = { path = "crates/mcp-gateway" } + diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index d0fe4b2e..d3095c8e 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -4,6 +4,7 @@ version.workspace = true edition.workspace = true [dependencies] +tw-breaker = { workspace = true } tw-guard = { workspace = true } tw-crypto = { workspace = true } axum = { workspace = true } diff --git a/crates/common/src/cb_registry.rs b/crates/common/src/cb_registry.rs index 2d2e7101..31e3a7e3 100644 --- a/crates/common/src/cb_registry.rs +++ b/crates/common/src/cb_registry.rs @@ -1,36 +1,33 @@ //! Process-wide circuit-breaker state registry. //! -//! Both the AI gateway (`think-watch-gateway`) and the MCP gateway -//! (`think-watch-mcp-gateway`) write into this shared map every time a -//! circuit transitions. The dashboard handler in `think-watch-server` reads -//! a snapshot to render real-time CB state in the upstream-health panel. +//! The MCP gateway (`think-watch-mcp-gateway`) writes into this map every +//! time one of its in-process breakers transitions, and the Open listener +//! turns an opening into an audit event. The dashboard handler reads a +//! snapshot to render MCP rows. //! -//! Living in `think-watch-common` keeps the two gateways decoupled while -//! still letting them share a single global view. +//! AI routes are not here: their breakers live in Redis, shared by every +//! replica, and the dashboard reads them from there +//! (`HealthTracker::state`). A process-local map would show each replica +//! only its own view. use std::collections::HashMap; use std::sync::OnceLock; use std::sync::RwLock; -/// Public, stable representation of a circuit-breaker state. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CbState { - Closed, - HalfOpen, - Open, -} +/// A breaker's state: thinkwatch-core's, the state machine every breaker +/// here runs. +use tw_breaker::State; -impl CbState { - pub fn as_str(&self) -> &'static str { - match self { - CbState::Closed => "Closed", - CbState::HalfOpen => "HalfOpen", - CbState::Open => "Open", - } +/// How the dashboard spells a state (`Closed` / `HalfOpen` / `Open`). +pub fn label(state: State) -> &'static str { + match state { + State::Closed => "Closed", + State::HalfOpen => "HalfOpen", + State::Open => "Open", } } -static CB_REGISTRY: OnceLock>> = OnceLock::new(); +static CB_REGISTRY: OnceLock>> = OnceLock::new(); /// Signature of the Open-transition listener. Named so the static's /// type declaration stays short and clippy::type_complexity happy. @@ -43,7 +40,7 @@ pub type OpenListener = Box; /// breakers so downstream subscribers can distinguish them. static OPEN_LISTENER: OnceLock = OnceLock::new(); -fn cb_registry() -> &'static RwLock> { +fn cb_registry() -> &'static RwLock> { CB_REGISTRY.get_or_init(|| RwLock::new(HashMap::new())) } @@ -63,14 +60,14 @@ where /// either "ai" or "mcp" — used by the Open listener to tag emitted /// audit events. When the transition is Closed→Open or HalfOpen→Open /// the listener (if installed) fires once. -pub fn record_cb_with_kind(key: &str, state: CbState, kind: &str) { +pub fn record_cb_with_kind(key: &str, state: State, kind: &str) { let prev = if let Ok(mut m) = cb_registry().write() { m.insert(key.to_string(), state) } else { None }; - if state == CbState::Open - && prev != Some(CbState::Open) + if state == State::Open + && prev != Some(State::Open) && let Some(listener) = OPEN_LISTENER.get() { listener(key, kind); @@ -78,7 +75,7 @@ pub fn record_cb_with_kind(key: &str, state: CbState, kind: &str) { } /// Snapshot the current state of every key the registry has seen. -pub fn snapshot_cb_states() -> HashMap { +pub fn snapshot_cb_states() -> HashMap { cb_registry().read().map(|m| m.clone()).unwrap_or_default() } @@ -127,10 +124,10 @@ mod tests { let _g = serial_lock().lock().unwrap(); let _ = drain_captured(); // discard residue from earlier tests - record_cb_with_kind("test-fires-once", CbState::Closed, "ai"); - record_cb_with_kind("test-fires-once", CbState::Open, "ai"); - record_cb_with_kind("test-fires-once", CbState::Open, "ai"); - record_cb_with_kind("test-fires-once", CbState::Open, "ai"); + record_cb_with_kind("test-fires-once", State::Closed, "ai"); + record_cb_with_kind("test-fires-once", State::Open, "ai"); + record_cb_with_kind("test-fires-once", State::Open, "ai"); + record_cb_with_kind("test-fires-once", State::Open, "ai"); let calls = drain_captured(); let calls_for_key: Vec<_> = calls @@ -150,9 +147,9 @@ mod tests { let _g = serial_lock().lock().unwrap(); let _ = drain_captured(); - record_cb_with_kind("test-re-fires", CbState::Open, "mcp"); - record_cb_with_kind("test-re-fires", CbState::Closed, "mcp"); - record_cb_with_kind("test-re-fires", CbState::Open, "mcp"); + record_cb_with_kind("test-re-fires", State::Open, "mcp"); + record_cb_with_kind("test-re-fires", State::Closed, "mcp"); + record_cb_with_kind("test-re-fires", State::Open, "mcp"); let calls = drain_captured(); let calls_for_key: Vec<_> = calls.iter().filter(|(k, _)| k == "test-re-fires").collect(); @@ -169,8 +166,8 @@ mod tests { let _g = serial_lock().lock().unwrap(); let _ = drain_captured(); - record_cb_with_kind("test-no-half-open", CbState::Closed, "ai"); - record_cb_with_kind("test-no-half-open", CbState::HalfOpen, "ai"); + record_cb_with_kind("test-no-half-open", State::Closed, "ai"); + record_cb_with_kind("test-no-half-open", State::HalfOpen, "ai"); let calls = drain_captured(); assert!( @@ -183,12 +180,12 @@ mod tests { fn snapshot_reflects_latest_state_for_each_key() { let _g = serial_lock().lock().unwrap(); - record_cb_with_kind("snapshot-test-1", CbState::Closed, "ai"); - record_cb_with_kind("snapshot-test-2", CbState::Open, "mcp"); - record_cb_with_kind("snapshot-test-1", CbState::HalfOpen, "ai"); + record_cb_with_kind("snapshot-test-1", State::Closed, "ai"); + record_cb_with_kind("snapshot-test-2", State::Open, "mcp"); + record_cb_with_kind("snapshot-test-1", State::HalfOpen, "ai"); let snap = snapshot_cb_states(); - assert_eq!(snap.get("snapshot-test-1"), Some(&CbState::HalfOpen)); - assert_eq!(snap.get("snapshot-test-2"), Some(&CbState::Open)); + assert_eq!(snap.get("snapshot-test-1"), Some(&State::HalfOpen)); + assert_eq!(snap.get("snapshot-test-2"), Some(&State::Open)); } } diff --git a/crates/gateway/Cargo.toml b/crates/gateway/Cargo.toml index 6e5fad2a..488da431 100644 --- a/crates/gateway/Cargo.toml +++ b/crates/gateway/Cargo.toml @@ -4,6 +4,7 @@ version.workspace = true edition.workspace = true [dependencies] +tw-breaker = { workspace = true } tw-guard = { workspace = true } tw-types = { workspace = true } tw-dialect = { workspace = true } diff --git a/crates/gateway/src/health.rs b/crates/gateway/src/health.rs index baea6a77..c26797c8 100644 --- a/crates/gateway/src/health.rs +++ b/crates/gateway/src/health.rs @@ -1,19 +1,16 @@ //! Per-route health: rolling-window error rate + EWMA latency + -//! circuit-breaker state machine. Backed by Redis so all gateway -//! replicas share the same view (the project-existing `failover.rs` -//! breaker is per-process-mutex; this module is the multi-instance -//! companion that drives selection-time filtering). +//! circuit breaker. Backed by Redis so all gateway replicas share the +//! same view; drives selection-time filtering. //! -//! ### Not shared with the desktop gateway +//! ### The state machine is shared, the premises are not //! -//! thinkwatch-core has a breaker of its own (`tw-gateway::health`), and -//! the two are kept apart on purpose. That one is in-process, trips on -//! consecutive failures, bypasses itself when a route has one candidate -//! and fails open when every candidate is down — right for one user -//! with nowhere else to go. This one is shared across replicas through -//! Redis, trips on an error rate over a window, is tuned by an admin, -//! and filters open routes out. The premises are opposite; one -//! abstraction over both would serve neither. +//! The breaker's state machine is thinkwatch-core's `tw-breaker`, the one +//! the desktop gateway and this crate's MCP breaker also run. What is +//! ours is where it lives and what trips it: state shared across +//! replicas through Redis, tripped by an error rate over a window, tuned +//! by an admin, and an open route filtered out of selection. (The desktop +//! keeps it in-process, trips on consecutive failures and fails open when +//! every candidate is down — right for one user with nowhere else to go.) //! //! ### Storage //! @@ -22,26 +19,27 @@ //! timestamp_ms, member = `"::"`. //! The seq number disambiguates simultaneous writes within the //! same millisecond; the rest is parsed back at tally time. -//! * `route_health:{route_id}:state` — small string `":"`. -//! Empty / missing means "closed" (optimistic default). State -//! transitions are written atomically inside the Lua script -//! alongside the sample insert. +//! * `route_health:{route_id}:state` — the breaker, as `tw-breaker`'s +//! JSON. Missing or unreadable means closed. //! * `route_health:{route_id}:counters` — Hash. Currently a single //! `lifetime_requests` field, `HINCRBY`-ed by 1 on every call. //! Counts cumulative traffic the rolling-window `total` can't //! express — operators tuning weights need to know whether a //! route has actually carried any requests at all. //! -//! ### Circuit-breaker semantics +//! ### One round trip, two when the state changes //! -//! - **Closed**: pass-through. After every record, if rolling-window -//! sample count ≥ `min_samples` AND error_pct ≥ `error_pct`, trip -//! to Open and stamp `opened_at_ms = now`. -//! - **Open**: filtered out at selection time. After -//! `now - opened_at_ms ≥ open_secs`, transition to HalfOpen. -//! - **HalfOpen**: selectable again. The next completion decides: -//! success ⇒ Closed (and reset window so old errors don't drag -//! us back); error ⇒ Open again (re-stamp opened_at_ms). +//! Recording a completion is one Lua call: insert the sample, drop what +//! fell out of the window, tally it, read the breaker. The transition is +//! computed here, from that tally. Only when it changes the breaker is it +//! written back, by a compare-and-set: two replicas that computed from the +//! same state cannot both write, and the one that loses was looking at a +//! state that is no longer there. +//! +//! **A cooled breaker is half-open when read**, with no write needed. It +//! used to become half-open only when a request on that route completed — +//! and an open route is never picked, so it stayed open until its state +//! key expired, about four cooldowns later. //! //! ### Why ZSET + Lua and not per-second Hash buckets? //! @@ -55,6 +53,9 @@ use fred::clients::Client; use fred::interfaces::{HashesInterface, KeysInterface, LuaInterface, SortedSetsInterface}; use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; +use think_watch_common::dynamic_config::DynamicConfig; +use tw_breaker::{Breaker, Policy, State, Tally, Trip}; use uuid::Uuid; const SAMPLE_CAP: u32 = 1000; @@ -63,10 +64,8 @@ const SAMPLE_CAP: u32 = 1000; /// uniqueness under simultaneous writes within the same millisecond. static SAMPLE_SEQ: AtomicU64 = AtomicU64::new(0); -/// Atomic record + breaker transition. Returns the post-update -/// `(state, total, errs, ewma_ms_x100, lifetime_requests)` so the -/// caller can include these in the decision log without a second -/// round-trip. +/// Insert a sample, trim the window, tally it and read the breaker. +/// Returns `(breaker_json_or_empty, total, errs, ewma_ms_x100, lifetime)`. const LUA_RECORD: &str = r#" local samples_key = KEYS[1] local state_key = KEYS[2] @@ -74,30 +73,20 @@ local counters_key = KEYS[3] local now_ms = tonumber(ARGV[1]) local window_start = tonumber(ARGV[2]) local member = ARGV[3] -local latency_ms = tonumber(ARGV[4]) -local is_error = tonumber(ARGV[5]) -local cb_enabled = tonumber(ARGV[6]) -local error_pct = tonumber(ARGV[7]) -local min_samples = tonumber(ARGV[8]) -local open_secs = tonumber(ARGV[9]) -local sample_cap = tonumber(ARGV[10]) - --- Drop expired samples + over-cap entries. +local ttl = tonumber(ARGV[4]) +local sample_cap = tonumber(ARGV[5]) + redis.call('ZREMRANGEBYSCORE', samples_key, '-inf', window_start) local oversize = redis.call('ZCARD', samples_key) - sample_cap if oversize > 0 then redis.call('ZREMRANGEBYRANK', samples_key, 0, oversize - 1) end - --- Insert new sample. redis.call('ZADD', samples_key, now_ms, member) -redis.call('EXPIRE', samples_key, math.max(60, open_secs * 4)) +redis.call('EXPIRE', samples_key, ttl) --- Bump the cumulative lifetime counter. Persistent (no EXPIRE) — --- this is the all-time view the rolling window can't express. +-- Cumulative, no EXPIRE: the all-time view the window can't express. local lifetime = redis.call('HINCRBY', counters_key, 'lifetime_requests', 1) --- Tally rolling window from member names: format "::". local members = redis.call('ZRANGEBYSCORE', samples_key, window_start, '+inf') local total = 0 local errs = 0 @@ -114,59 +103,32 @@ for _, m in ipairs(members) do end end --- Read current breaker state. -local raw = redis.call('GET', state_key) -local state = 'closed' -local opened_at = 0 -if raw then - local s, t = raw:match('^([a-z_]+):(%d+)$') - if s then state = s; opened_at = tonumber(t) or 0 end -end - -local new_state = state - -if cb_enabled == 1 then - if state == 'open' then - if now_ms - opened_at >= open_secs * 1000 then - new_state = 'half_open' - redis.call('SET', state_key, 'half_open:' .. now_ms, - 'EX', math.max(60, open_secs * 4)) - end - elseif state == 'half_open' then - if is_error == 1 then - new_state = 'open' - redis.call('SET', state_key, 'open:' .. now_ms, - 'EX', math.max(60, open_secs * 4)) - else - new_state = 'closed' - redis.call('DEL', state_key) - -- Wipe samples so old errors don't drag us back open. - redis.call('DEL', samples_key) - total = 0; errs = 0; ewma_num = 0 - end - else -- closed - if total >= min_samples and (errs * 100) >= (error_pct * total) then - new_state = 'open' - redis.call('SET', state_key, 'open:' .. now_ms, - 'EX', math.max(60, open_secs * 4)) - end - end -end +local state = redis.call('GET', state_key) or '' +return { state, total, errs, math.floor(ewma_num * 100), lifetime } +"#; --- Re-insert this sample if it got wiped on half_open success. -if new_state == 'closed' and state == 'half_open' and is_error == 0 then - redis.call('ZADD', samples_key, now_ms, member) - redis.call('EXPIRE', samples_key, math.max(60, open_secs * 4)) - total = 1 - ewma_num = latency_ms +/// Write the breaker back only if nobody else has since. `ARGV[1]` is the +/// value read (empty = there was none), `ARGV[2]` the new one (empty = +/// delete: a closed breaker is the default). `ARGV[4] == '1'` also wipes +/// the window — a route that just recovered starts clean, so the errors +/// that opened it cannot drag it straight back. +const LUA_CAS: &str = r#" +local state_key = KEYS[1] +local samples_key = KEYS[2] +local current = redis.call('GET', state_key) or '' +if current ~= ARGV[1] then return 0 end +if ARGV[2] == '' then + redis.call('DEL', state_key) +else + redis.call('SET', state_key, ARGV[2], 'EX', tonumber(ARGV[3])) end - -return { new_state, total, errs, math.floor(ewma_num * 100), lifetime } +if ARGV[4] == '1' then redis.call('DEL', samples_key) end +return 1 "#; #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] pub struct RouteHealth { - pub state: BreakerState, + pub state: State, pub total: u32, pub errors: u32, pub error_pct: f64, @@ -176,43 +138,9 @@ pub struct RouteHealth { /// tuning weights use this to tell apart "no traffic yet" from /// "quiet right now". `HINCRBY`-backed in Redis; persists across /// gateway restarts since the counter hash carries no TTL. - #[serde(default)] pub lifetime_requests: u64, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum BreakerState { - #[default] - Closed, - Open, - HalfOpen, -} - -impl BreakerState { - pub fn as_str(self) -> &'static str { - match self { - Self::Closed => "closed", - Self::Open => "open", - Self::HalfOpen => "half_open", - } - } - pub fn from_redis(s: &str) -> Self { - match s { - "open" => Self::Open, - "half_open" => Self::HalfOpen, - _ => Self::Closed, - } - } - /// Open routes are excluded; half_open lets a probe through. We - /// don't gate concurrency on the probe — any race resolves by - /// the first completion picking the next state, good enough as - /// an autotune signal. - pub fn allows_selection(self) -> bool { - !matches!(self, Self::Open) - } -} - /// Tunables loaded from system_settings on each request — cheap to /// re-read because DynamicConfig is in-memory. #[derive(Debug, Clone, Copy)] @@ -224,6 +152,65 @@ pub struct CircuitBreakerConfig { pub open_secs: u32, } +impl CircuitBreakerConfig { + /// The breaker settings in force. The router and the route-health + /// page both read them here, so the page shows what selection sees. + pub async fn load(dc: &DynamicConfig) -> Self { + Self { + enabled: dc.cb_enabled().await, + error_pct: dc.cb_error_pct().await, + min_samples: dc.cb_min_samples().await, + window_secs: dc.cb_window_secs().await, + open_secs: dc.cb_open_secs().await, + } + } + + /// As a `tw-breaker` policy: an error rate over the window, one probe. + pub fn policy(&self) -> Policy { + Policy { + trip: Trip::ErrorRate { + percent: self.error_pct, + min_samples: self.min_samples, + }, + cooldown: Duration::from_secs(u64::from(self.open_secs)), + probes: 1, + } + } + + /// How long the samples and the breaker are kept after the last write. + fn ttl_secs(&self) -> u32 { + (self.open_secs * 4).max(60) + } +} + +fn keys(route_id: Uuid) -> (String, String, String) { + ( + format!("route_health:{route_id}:samples"), + format!("route_health:{route_id}:state"), + format!("route_health:{route_id}:counters"), + ) +} + +fn parse(raw: &str) -> Breaker { + serde_json::from_str(raw).unwrap_or_default() +} + +fn health(state: State, total: u32, errors: u32, ewma: f64, lifetime: u64) -> RouteHealth { + let error_pct = if total > 0 { + f64::from(errors) * 100.0 / f64::from(total) + } else { + 0.0 + }; + RouteHealth { + state, + total, + errors, + error_pct, + ewma_latency_ms: (total > 0 && ewma > 0.0).then_some(ewma), + lifetime_requests: lifetime, + } +} + #[derive(Clone)] pub struct HealthTracker { redis: Client, @@ -234,11 +221,9 @@ impl HealthTracker { Self { redis } } - /// Record a request completion. Atomic via Lua: writes the - /// sample, recomputes the rolling tally, transitions the breaker, - /// returns the post-update health snapshot. Failures are logged - /// and degrade gracefully — health tracking isn't on the request - /// critical path. + /// Record a request completion and return the route's health after it. + /// Failures are logged and degrade gracefully — health tracking isn't + /// on the request critical path. pub async fn record( &self, route_id: Uuid, @@ -247,17 +232,11 @@ impl HealthTracker { cfg: CircuitBreakerConfig, ) -> RouteHealth { let now_ms = chrono::Utc::now().timestamp_millis(); - let window_start = now_ms - (cfg.window_secs as i64) * 1000; + let window_start = now_ms - i64::from(cfg.window_secs) * 1000; let seq = SAMPLE_SEQ.fetch_add(1, Ordering::Relaxed); - let member = format!("{seq}:{latency_ms}:{}", if is_error { 1 } else { 0 }); - let samples_key = format!("route_health:{route_id}:samples"); - let state_key = format!("route_health:{route_id}:state"); - let counters_key = format!("route_health:{route_id}:counters"); + let member = format!("{seq}:{latency_ms}:{}", u8::from(is_error)); + let (samples_key, state_key, counters_key) = keys(route_id); - // Lua returns [state_string, total, errors, ewma_ms_x100, - // lifetime_requests]. Decoded as a tuple of fred-supported - // scalar types — Vec of mixed-type Lua replies isn't - // directly FromValue-compatible. let result: Result<(String, i64, i64, i64, i64), _> = self .redis .eval( @@ -271,57 +250,90 @@ impl HealthTracker { now_ms.to_string(), window_start.to_string(), member, - latency_ms.to_string(), - (if is_error { 1 } else { 0 }).to_string(), - (if cfg.enabled { 1 } else { 0 }).to_string(), - cfg.error_pct.to_string(), - cfg.min_samples.to_string(), - cfg.open_secs.to_string(), + cfg.ttl_secs().to_string(), SAMPLE_CAP.to_string(), ], ) .await; - - match result { - Ok((state, total, errs, ewma_x100, lifetime)) => { - let total_u = total.max(0) as u32; - let errs_u = errs.max(0) as u32; - let error_pct = if total_u > 0 { - errs_u as f64 * 100.0 / total_u as f64 - } else { - 0.0 - }; - let ewma = (ewma_x100 as f64) / 100.0; - RouteHealth { - state: BreakerState::from_redis(&state), - total: total_u, - errors: errs_u, - error_pct, - ewma_latency_ms: if ewma > 0.0 { Some(ewma) } else { None }, - lifetime_requests: lifetime.max(0) as u64, - } - } + let (raw, total, errs, ewma_x100, lifetime) = match result { + Ok(r) => r, Err(e) => { tracing::warn!("route_health record failed: {e}"); - RouteHealth::default() + return RouteHealth::default(); } + }; + let total = u32::try_from(total.max(0)).unwrap_or(u32::MAX); + let errors = u32::try_from(errs.max(0)).unwrap_or(u32::MAX); + let ewma = ewma_x100 as f64 / 100.0; + let lifetime = u64::try_from(lifetime.max(0)).unwrap_or(0); + + if !cfg.enabled { + return health(State::Closed, total, errors, ewma, lifetime); } + let policy = cfg.policy(); + let mut breaker = parse(&raw); + let before = breaker; + let change = breaker.record(!is_error, Tally { total, errors }, &policy, now_ms); + if breaker != before { + let recovered = change == Some(State::Closed); + let next = if breaker == Breaker::default() { + String::new() + } else { + serde_json::to_string(&breaker).unwrap_or_default() + }; + let written: Result = self + .redis + .eval( + LUA_CAS, + vec![state_key.as_str(), samples_key.as_str()], + vec![ + raw.clone(), + next, + cfg.ttl_secs().to_string(), + if recovered { "1" } else { "0" }.to_string(), + ], + ) + .await; + match written { + Ok(1) => { + if let Some(s) = change { + tracing::info!(%route_id, state = ?s, "route circuit breaker changed state"); + } + } + // Another replica wrote first; its view stands. + Ok(_) => breaker = parse(&raw), + Err(e) => { + tracing::warn!("route_health state write failed: {e}"); + breaker = parse(&raw); + } + } + } + health( + breaker.state_at(&policy, now_ms), + total, + errors, + ewma, + lifetime, + ) + } + + /// The breaker's state right now — one read. A cooled open breaker is + /// half-open. Best-effort: an error reads as closed. + pub async fn state(&self, route_id: Uuid, cfg: CircuitBreakerConfig) -> State { + if !cfg.enabled { + return State::Closed; + } + let (_, state_key, _) = keys(route_id); + let raw: Option = self.redis.get(&state_key).await.ok().flatten(); + parse(raw.as_deref().unwrap_or("")) + .state_at(&cfg.policy(), chrono::Utc::now().timestamp_millis()) } /// Read-only snapshot — for selection-time filter and UI display. - /// No state mutation, so done in Rust rather than Lua. /// Best-effort: errors return a default (closed, no data). - pub async fn snapshot(&self, route_id: Uuid, window_secs: u32) -> RouteHealth { - let samples_key = format!("route_health:{route_id}:samples"); - let state_key = format!("route_health:{route_id}:state"); - let counters_key = format!("route_health:{route_id}:counters"); - - let state_raw: Option = self.redis.get(&state_key).await.ok().flatten(); - let state = state_raw - .as_deref() - .and_then(|s| s.split(':').next()) - .map(BreakerState::from_redis) - .unwrap_or_default(); + pub async fn snapshot(&self, route_id: Uuid, cfg: CircuitBreakerConfig) -> RouteHealth { + let (samples_key, _, counters_key) = keys(route_id); + let state = self.state(route_id, cfg).await; // HGET → Option; missing field == route hasn't seen // any traffic yet, which we render as 0. @@ -331,17 +343,16 @@ impl HealthTracker { .await .ok() .flatten(); - let lifetime_requests = lifetime_raw + let lifetime = lifetime_raw .as_deref() .and_then(|s| s.parse::().ok()) .unwrap_or(0); let now_ms = chrono::Utc::now().timestamp_millis(); - let window_start = (now_ms - (window_secs as i64) * 1000) as f64; - let plus_inf = f64::INFINITY; + let window_start = (now_ms - i64::from(cfg.window_secs) * 1000) as f64; let members: Vec = self .redis - .zrangebyscore(&samples_key, window_start, plus_inf, false, None) + .zrangebyscore(&samples_key, window_start, f64::INFINITY, false, None) .await .unwrap_or_default(); @@ -366,20 +377,7 @@ impl HealthTracker { }; } } - - let error_pct = if total > 0 { - errs as f64 * 100.0 / total as f64 - } else { - 0.0 - }; - RouteHealth { - state, - total, - errors: errs, - error_pct, - ewma_latency_ms: if total > 0 { Some(ewma) } else { None }, - lifetime_requests, - } + health(state, total, errs, ewma, lifetime) } /// Bulk variant for the UI — sequential per-route reads. fred's @@ -388,11 +386,11 @@ impl HealthTracker { pub async fn snapshot_many( &self, route_ids: &[Uuid], - window_secs: u32, + cfg: CircuitBreakerConfig, ) -> Vec<(Uuid, RouteHealth)> { let mut out = Vec::with_capacity(route_ids.len()); for id in route_ids { - out.push((*id, self.snapshot(*id, window_secs).await)); + out.push((*id, self.snapshot(*id, cfg).await)); } out } @@ -420,52 +418,75 @@ impl HealthTracker { mod tests { use super::*; + fn cfg() -> CircuitBreakerConfig { + CircuitBreakerConfig { + enabled: true, + error_pct: 50, + min_samples: 4, + window_secs: 60, + open_secs: 30, + } + } + /// Default health is the value the wire emits when a route has /// never seen a request — must include a zero lifetime counter /// so the UI never has to handle `undefined` for that field. #[test] - fn default_route_health_has_zero_lifetime() { + fn default_route_health_is_closed_with_nothing_counted() { let h = RouteHealth::default(); + assert_eq!(h.state, State::Closed); assert_eq!(h.lifetime_requests, 0); - assert_eq!(h.total, 0); - assert_eq!(h.errors, 0); + assert_eq!((h.total, h.errors), (0, 0)); } - /// Serialized wire shape: `lifetime_requests` must round-trip - /// through JSON so the frontend can read it directly off the - /// route-health endpoint without an aliased field. + /// The UI reads `state` as `closed` / `open` / `half_open` and + /// `lifetime_requests` directly off the route-health endpoint. #[test] - fn route_health_serializes_lifetime_requests() { - let h = RouteHealth { - state: BreakerState::Closed, - total: 3, - errors: 1, - error_pct: 33.3, - ewma_latency_ms: Some(120.5), - lifetime_requests: 42, - }; + fn route_health_serializes_the_way_the_ui_reads_it() { + let h = health(State::HalfOpen, 3, 1, 120.5, 42); let json = serde_json::to_value(&h).unwrap(); + assert_eq!(json["state"], "half_open"); assert_eq!(json["lifetime_requests"], 42); assert_eq!(json["total"], 3); + assert!((json["error_pct"].as_f64().unwrap() - 33.33).abs() < 0.01); + } - // Round-trip preserves the value. - let back: RouteHealth = serde_json::from_value(json).unwrap(); - assert_eq!(back.lifetime_requests, 42); + #[test] + fn the_policy_is_an_error_rate_with_one_probe() { + let p = cfg().policy(); + assert_eq!( + p.trip, + Trip::ErrorRate { + percent: 50, + min_samples: 4 + } + ); + assert_eq!(p.cooldown, Duration::from_secs(30)); + assert_eq!(p.probes, 1); } - /// Deserialization tolerates missing `lifetime_requests` via the - /// serde default — keeps the snapshot decode path robust if Redis - /// hands back an older blob we don't expect to see in practice. #[test] - fn route_health_deserializes_without_lifetime_field() { - let raw = serde_json::json!({ - "state": "closed", - "total": 0, - "errors": 0, - "error_pct": 0.0, - "ewma_latency_ms": null, - }); - let h: RouteHealth = serde_json::from_value(raw).unwrap(); - assert_eq!(h.lifetime_requests, 0); + fn an_unreadable_stored_breaker_is_closed() { + // Keys written by the previous format (`open:`) read as closed + assert_eq!(parse("open:1700000000000"), Breaker::default()); + assert_eq!(parse(""), Breaker::default()); + } + + #[test] + fn a_stored_open_breaker_is_half_open_once_cooled() { + let p = cfg().policy(); + let mut b = Breaker::default(); + b.record( + false, + Tally { + total: 4, + errors: 4, + }, + &p, + 0, + ); + let raw = serde_json::to_string(&b).unwrap(); + assert_eq!(parse(&raw).state_at(&p, 29_000), State::Open); + assert_eq!(parse(&raw).state_at(&p, 30_000), State::HalfOpen); } } diff --git a/crates/gateway/src/hidden_text.rs b/crates/gateway/src/hidden_text.rs new file mode 100644 index 00000000..0ef5e3b8 --- /dev/null +++ b/crates/gateway/src/hidden_text.rs @@ -0,0 +1,195 @@ +//! Invisible characters in what the caller sends. +//! +//! Unicode tag characters (`U+E0000`–`U+E007F`) render as nothing in +//! almost every editor and still reach the model's token stream — a whole +//! instruction can ride along invisibly ("ASCII smuggling"). Bidirectional +//! overrides make text on screen read in a different order than the +//! characters really are. Neither has a legitimate use in a prompt, and +//! both show up where the caller did not write them: in a web page or a +//! file a tool fetched, handed back as a tool result. +//! +//! Detection is thinkwatch-core's (`tw_guard::hidden`), the scanner the +//! desktop gateway runs over client config files. Only the two kinds that +//! `tw_guard::hidden::Kind::smuggles` names are flagged here: zero-width joiners build +//! emoji, a zero-width non-joiner is ordinary Persian, and Cyrillic is +//! ordinary Russian. +//! +//! Scanned: the caller's messages and the tool results inside them. +//! Not scanned: the system prompt (the operator's) and the model's own +//! turns. + +use serde::{Deserialize, Serialize}; +use think_watch_common::dynamic_config::DynamicConfig; +use tw_dialect::ir::{Part, Request, Role}; +use tw_guard::hidden; + +/// What a hit does. Same words as the content filter's actions. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Action { + Off, + /// Record it in the application log only. + Log, + /// Let the request through and write an audit event. The default: + /// nothing breaks, and an operator sees it happening. + #[default] + Warn, + /// Refuse the request with 403. + Block, +} + +/// `security.hidden_text`. Missing or unreadable means the default. +pub async fn action(dc: &DynamicConfig) -> Action { + dc.get("security.hidden_text") + .await + .and_then(|v| serde_json::from_value(v).ok()) + .unwrap_or_default() +} + +/// One kind of hidden character, where it was found and how often. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Found { + /// `tag` or `bidi` + pub kind: &'static str, + /// Inside a tool result rather than text the caller typed. + pub in_tool_result: bool, + pub count: usize, + /// The first code point seen, as `U+E0049`. + pub example: String, +} + +/// Scan the caller's messages, tool results included. +pub fn scan(request: &Request) -> Vec { + let mut out: Vec = Vec::new(); + for m in request.messages.iter().filter(|m| m.role == Role::User) { + scan_parts(&m.parts, false, &mut out); + } + out +} + +fn scan_parts(parts: &[Part], in_tool_result: bool, out: &mut Vec) { + for p in parts { + match p { + Part::Text(s) => { + for h in hidden::scan(s).into_iter().filter(|h| h.kind.smuggles()) { + let kind = h.kind.slug(); + match out + .iter_mut() + .find(|f| f.kind == kind && f.in_tool_result == in_tool_result) + { + Some(f) => f.count += 1, + None => out.push(Found { + kind, + in_tool_result, + count: 1, + example: h.codepoint, + }), + } + } + } + Part::ToolResult(r) => scan_parts(&r.content, true, out), + Part::Image(_) | Part::File { .. } | Part::Thinking(_) | Part::ToolCall(_) => {} + } + } +} + +/// What the caller is told when the request is refused. +pub fn refusal(found: &[Found]) -> tw_types::GatewayError { + let place = if found.iter().any(|f| f.in_tool_result) { + "a tool result" + } else { + "the message" + }; + tw_types::GatewayError::PolicyBlocked(format!( + "{place} contains invisible characters that can hide instructions from a reader ({})", + found.iter().map(|f| f.kind).collect::>().join(", ") + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use tw_dialect::ir::{Message, ToolResult}; + + fn user(parts: Vec) -> Request { + Request { + model: "m".into(), + messages: vec![Message { + role: Role::User, + parts, + }], + ..Default::default() + } + } + + /// "ignore" written in tag characters + fn smuggled() -> String { + "summarise this" + .chars() + .chain( + "ignore" + .chars() + .map(|c| char::from_u32(0xE0000 + c as u32).unwrap()), + ) + .collect() + } + + #[test] + fn tag_characters_in_a_tool_result_are_found() { + let r = user(vec![Part::ToolResult(ToolResult { + id: "t".into(), + content: vec![Part::Text(smuggled())], + is_error: false, + })]); + let found = scan(&r); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0].kind, "tag"); + assert!(found[0].in_tool_result); + assert_eq!(found[0].count, 6); + assert!(refusal(&found).to_string().contains("tool result")); + } + + #[test] + fn a_bidi_override_in_typed_text_is_found() { + let found = scan(&user(vec![Part::Text("abc\u{202E}fed".into())])); + assert_eq!(found[0].kind, "bidi"); + assert!(!found[0].in_tool_result); + } + + #[test] + fn ordinary_text_in_any_script_is_left_alone() { + for s in [ + "👨\u{200D}👩\u{200D}👧 family", + "Привет, как дела?", + "می\u{200C}خواهم", + "مرحبا بالعالم", + "π ≈ 3.14", + ] { + assert!(scan(&user(vec![Part::Text(s.into())])).is_empty(), "{s}"); + } + } + + #[test] + fn the_system_prompt_and_the_models_turns_are_not_scanned() { + let mut r = user(vec![Part::Text("hi".into())]); + r.system = vec![smuggled()]; + r.messages.push(Message { + role: Role::Assistant, + parts: vec![Part::Text(smuggled())], + }); + assert!(scan(&r).is_empty()); + } + + #[test] + fn the_setting_reads_the_content_filters_words() { + for (s, a) in [ + ("off", Action::Off), + ("log", Action::Log), + ("warn", Action::Warn), + ("block", Action::Block), + ] { + assert_eq!(serde_json::from_value::(s.into()).unwrap(), a); + } + assert_eq!(Action::default(), Action::Warn); + } +} diff --git a/crates/gateway/src/lib.rs b/crates/gateway/src/lib.rs index e0eee405..f006249e 100644 --- a/crates/gateway/src/lib.rs +++ b/crates/gateway/src/lib.rs @@ -2,6 +2,7 @@ pub mod cache; pub mod content_filter; pub mod cost_tracker; pub mod health; +pub mod hidden_text; pub mod lifecycle; pub mod metadata; pub mod metrics_labels; diff --git a/crates/gateway/src/proxy/generate.rs b/crates/gateway/src/proxy/generate.rs index 99acca64..72a8dd5e 100644 --- a/crates/gateway/src/proxy/generate.rs +++ b/crates/gateway/src/proxy/generate.rs @@ -393,6 +393,47 @@ async fn generate( } } + // 4b. Invisible characters that can carry an instruction past a + // reader — in what the caller typed, or in a tool result. + let hidden_action = crate::hidden_text::action(&state.dynamic_config).await; + if hidden_action != crate::hidden_text::Action::Off { + let found = crate::hidden_text::scan(&decoded.request); + if !found.is_empty() { + use crate::hidden_text::Action as H; + use think_watch_common::audit::{AuditActor, GatewayActor, LogType}; + metrics::counter!("gateway_hidden_text_total", "action" => format!("{hidden_action:?}")) + .increment(1); + tracing::warn!(trace_id = %trace_id, ?found, "request carries hidden characters"); + if matches!(hidden_action, H::Warn | H::Block) { + let blocked = hidden_action == H::Block; + state.audit.log( + GatewayActor { + user_id: identity.user_id.as_deref(), + user_email: identity.user_email.as_deref(), + api_key_id: identity.api_key_id.as_deref(), + api_key_lineage_id: identity.api_key_lineage_id.as_deref(), + ip: identity.ip_address.as_deref(), + session_id: None, + } + .audit(if blocked { + "gateway.hidden_text_blocked" + } else { + "gateway.hidden_text_flagged" + }) + .log_type(LogType::Audit) + .detail(serde_json::json!({ + "trace_id": trace_id, + "model": mapped_model, + "found": found, + })), + ); + } + if hidden_action == H::Block { + return Err(ctx.emit(crate::hidden_text::refusal(&found)).into()); + } + } + } + let call_ctx = CallCtx::new( Some(trace_id.clone()), identity.user_id.clone(), diff --git a/crates/gateway/src/proxy/routing.rs b/crates/gateway/src/proxy/routing.rs index c8a6f5fc..c636fc70 100644 --- a/crates/gateway/src/proxy/routing.rs +++ b/crates/gateway/src/proxy/routing.rs @@ -107,13 +107,7 @@ async fn resolve_routing_config( } async fn resolve_breaker_config(state: &GatewayState) -> CircuitBreakerConfig { - CircuitBreakerConfig { - enabled: state.dynamic_config.cb_enabled().await, - error_pct: state.dynamic_config.cb_error_pct().await, - min_samples: state.dynamic_config.cb_min_samples().await, - window_secs: state.dynamic_config.cb_window_secs().await, - open_secs: state.dynamic_config.cb_open_secs().await, - } + CircuitBreakerConfig::load(&state.dynamic_config).await } /// Strategy/affinity/breaker context resolved once per request and @@ -163,11 +157,7 @@ async fn pick_with_strategy<'a>( } let mut healths: Vec = Vec::with_capacity(group.len()); for entry in group { - let h = ctx - .state - .health - .snapshot(entry.route_id, ctx.breaker.window_secs) - .await; + let h = ctx.state.health.snapshot(entry.route_id, ctx.breaker).await; healths.push(h); } @@ -187,7 +177,7 @@ async fn pick_with_strategy<'a>( let mut excluded: Vec = Vec::with_capacity(group.len()); for (i, entry) in group.iter().enumerate() { let h = &healths[i]; - let excl = !h.state.allows_selection() || tried.contains(&entry.provider_id); + let excl = h.state == tw_breaker::State::Open || tried.contains(&entry.provider_id); excluded.push(excl); let success_rate = if h.total > 0 { Some((1.0 - h.error_pct / 100.0).clamp(0.0, 1.0)) diff --git a/crates/mcp-gateway/Cargo.toml b/crates/mcp-gateway/Cargo.toml index 2b8049e0..ba915d45 100644 --- a/crates/mcp-gateway/Cargo.toml +++ b/crates/mcp-gateway/Cargo.toml @@ -4,6 +4,7 @@ version.workspace = true edition.workspace = true [dependencies] +tw-breaker = { workspace = true } tw-crypto = { workspace = true } think-watch-common = { workspace = true } think-watch-auth = { workspace = true } diff --git a/crates/mcp-gateway/src/circuit_breaker.rs b/crates/mcp-gateway/src/circuit_breaker.rs index a5506daf..05baaa50 100644 --- a/crates/mcp-gateway/src/circuit_breaker.rs +++ b/crates/mcp-gateway/src/circuit_breaker.rs @@ -5,26 +5,22 @@ //! when its CB trips we just fail fast on subsequent calls until the //! recovery window elapses. //! -//! All breaker state lives behind a single `Mutex`. The -//! previous design split state across an `RwLock`, two -//! `AtomicU32`s, and an `RwLock>`, which made the -//! check / record_failure / record_success transitions racy: two -//! concurrent failures could both observe `Closed`, both bump the -//! counter, and both trip Open separately (writing `last_failure` -//! twice). Holding one mutex for the entire transition makes every -//! state change atomic. +//! The state machine is thinkwatch-core's `tw-breaker` — the one the AI +//! gateway's route health and the desktop gateway also run. Each +//! transition happens under one lock, so two concurrent failures cannot +//! both trip the breaker. //! //! Every state transition is mirrored into the global `cb_registry` in //! `think-watch-common`, which the dashboard handler in the server crate //! reads to render real upstream-health on the UI. -use std::collections::HashMap; -use std::sync::Arc; -use std::time::{Duration, Instant}; -use tokio::sync::{Mutex, RwLock}; +use std::collections::HashSet; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tw_breaker::{Breakers, Policy, State, Trip}; use uuid::Uuid; -use think_watch_common::cb_registry::{CbState, record_cb_with_kind}; +use think_watch_common::cb_registry::record_cb_with_kind; /// Tunables for a single circuit breaker. #[derive(Debug, Clone, Copy)] @@ -47,144 +43,16 @@ impl Default for CircuitConfig { } } -/// Mutable inner state of a single breaker. Always accessed under the -/// outer `Mutex`, never split across multiple locks. -#[derive(Debug)] -struct BreakerInner { - state: CbState, - consecutive_failures: u32, - half_open_successes: u32, - last_failure: Option, -} - -/// One circuit breaker, scoped to a single MCP server. -/// -/// Keyed by `server_id` (UUID) at the registry level so a rename or -/// a second server that happens to share a name doesn't inherit the -/// other's open/closed state. The display name is passed in on every -/// call rather than stored on the breaker, so a rename takes effect -/// in dashboard / log output immediately — caching the name at -/// breaker construction would freeze the old label until process -/// restart. -struct Breaker { - #[allow(dead_code)] - server_id: Uuid, - config: CircuitConfig, - inner: Mutex, -} - -impl Breaker { - fn new(server_id: Uuid, display_name: &str, config: CircuitConfig) -> Self { - record_cb_with_kind(display_name, CbState::Closed, "mcp"); - Self { - server_id, - config, - inner: Mutex::new(BreakerInner { - state: CbState::Closed, - consecutive_failures: 0, - half_open_successes: 0, - last_failure: None, - }), - } - } - - /// Decide whether a new request is allowed through. Side effect: if - /// the breaker is `Open` and the recovery window has elapsed, this - /// transitions it to `HalfOpen` so the caller's request acts as a - /// probe. The whole check-then-transition runs under one mutex so - /// concurrent callers can't both "win" the half-open promotion. - async fn check(&self, display_name: &str) -> Result<(), CircuitOpen> { - let mut inner = self.inner.lock().await; - match inner.state { - CbState::Closed | CbState::HalfOpen => Ok(()), - CbState::Open => { - let elapsed_ok = inner - .last_failure - .map(|t| t.elapsed() >= Duration::from_secs(self.config.recovery_secs)) - .unwrap_or(false); - if elapsed_ok { - inner.state = CbState::HalfOpen; - inner.half_open_successes = 0; - inner.consecutive_failures = 0; - record_cb_with_kind(display_name, CbState::HalfOpen, "mcp"); - tracing::info!( - server = %display_name, - "MCP circuit breaker HALF-OPEN (probing recovery)" - ); - Ok(()) - } else { - Err(CircuitOpen) - } - } - } - } - - async fn record_success(&self, display_name: &str) { - let mut inner = self.inner.lock().await; - inner.consecutive_failures = 0; - match inner.state { - CbState::HalfOpen => { - inner.half_open_successes += 1; - if inner.half_open_successes >= self.config.half_open_max { - inner.state = CbState::Closed; - inner.half_open_successes = 0; - record_cb_with_kind(display_name, CbState::Closed, "mcp"); - tracing::info!( - server = %display_name, - "MCP circuit breaker CLOSED (recovered)" - ); - } - } - CbState::Open => { - // Shouldn't happen — `check` would have rejected — but if - // a stale request lands, recover gracefully. - inner.state = CbState::Closed; - record_cb_with_kind(display_name, CbState::Closed, "mcp"); - } - CbState::Closed => {} - } - } - - /// Record a failure. Transitions the breaker to Open on either - /// Closed-past-threshold or HalfOpen-probe-failed. The - /// `record_cb_with_kind` side-effect fires the global OPEN_LISTENER, - /// which is where the `provider.circuit_open` audit event gets - /// emitted — no return-value threading required. - async fn record_failure(&self, display_name: &str) { - let mut inner = self.inner.lock().await; - inner.consecutive_failures += 1; - match inner.state { - CbState::Closed => { - if inner.consecutive_failures >= self.config.failure_threshold { - inner.state = CbState::Open; - inner.last_failure = Some(Instant::now()); - let failures = inner.consecutive_failures; - record_cb_with_kind(display_name, CbState::Open, "mcp"); - tracing::warn!( - server = %display_name, - failures, - "MCP circuit breaker OPEN" - ); - } - } - CbState::HalfOpen => { - // Probe failed → go back to Open and restart the timer. - inner.state = CbState::Open; - inner.last_failure = Some(Instant::now()); - inner.half_open_successes = 0; - record_cb_with_kind(display_name, CbState::Open, "mcp"); - tracing::warn!( - server = %display_name, - "MCP circuit breaker back to OPEN (probe failed)" - ); - } - CbState::Open => {} +impl CircuitConfig { + fn policy(&self) -> Policy { + Policy { + trip: Trip::Consecutive(self.failure_threshold), + cooldown: Duration::from_secs(self.recovery_secs), + probes: self.half_open_max, } } } -/// Sentinel returned when a request is rejected because its server's -/// circuit is currently `Open`. #[derive(Debug)] pub struct CircuitOpen; @@ -196,19 +64,21 @@ impl std::fmt::Display for CircuitOpen { impl std::error::Error for CircuitOpen {} -/// Per-process registry of one circuit breaker per MCP server, keyed -/// by the server's stable UUID (NOT name). -/// -/// Renaming a server, or accidentally registering two servers with the -/// same name, used to share or inherit breaker state because the map -/// was string-keyed. Concretely: server `srv` flaps, breaker trips -/// OPEN; admin deletes `srv` and creates a fresh, healthy `srv` → -/// new server immediately rejects every call until the recovery -/// window elapses. UUID keys eliminate both failure modes. -#[derive(Clone, Default)] +/// Keyed by `server_id` so a rename, or a second server that happens to +/// share a name, does not inherit the other's state. The display name is +/// passed in on every call rather than stored, so a rename shows up in +/// the dashboard on the next state change. +#[derive(Clone)] pub struct McpCircuitBreakers { - inner: Arc>>>, - config: CircuitConfig, + breakers: Arc>, + /// Servers already announced to the dashboard as closed. + known: Arc>>, +} + +impl Default for McpCircuitBreakers { + fn default() -> Self { + Self::new() + } } impl McpCircuitBreakers { @@ -218,59 +88,58 @@ impl McpCircuitBreakers { pub fn with_config(config: CircuitConfig) -> Self { Self { - inner: Arc::new(RwLock::new(HashMap::new())), - config, + breakers: Arc::new(Breakers::new(config.policy())), + known: Arc::new(Mutex::new(HashSet::new())), } } - /// Get the breaker for `server_id`, creating it on first touch. - /// `display_name` is used only at creation time for the initial - /// `record_cb_with_kind` event; subsequent state-change events - /// pick up whatever name the current caller is using, so a server - /// rename takes effect on the very next breaker event. - async fn breaker_for(&self, server_id: Uuid, display_name: &str) -> Arc { - if let Some(b) = self.inner.read().await.get(&server_id) { - return Arc::clone(b); + /// The first time a server is seen, the dashboard learns it as closed. + fn announce(&self, server_id: Uuid, display_name: &str) { + let mut known = self.known.lock().unwrap_or_else(|e| e.into_inner()); + if known.insert(server_id) { + record_cb_with_kind(display_name, State::Closed, "mcp"); } - let mut w = self.inner.write().await; - if let Some(b) = w.get(&server_id) { - return Arc::clone(b); + } + + fn report(&self, display_name: &str, change: Option) { + let Some(s) = change else { return }; + record_cb_with_kind(display_name, s, "mcp"); + match s { + State::Open => tracing::warn!(server = %display_name, "MCP circuit breaker OPEN"), + State::HalfOpen => tracing::info!( + server = %display_name, + "MCP circuit breaker HALF-OPEN (probing recovery)" + ), + State::Closed => { + tracing::info!(server = %display_name, "MCP circuit breaker CLOSED (recovered)") + } } - let b = Arc::new(Breaker::new(server_id, display_name, self.config)); - w.insert(server_id, Arc::clone(&b)); - b } - /// Returns `Ok(())` if the server can be called. Returns `Err(CircuitOpen)` - /// if the breaker is currently rejecting requests. `display_name` - /// is used for log lines and the dashboard cb_registry on every - /// state-change event — pass the current name so a rename is - /// reflected immediately. - pub async fn check(&self, server_id: Uuid, display_name: &str) -> Result<(), CircuitOpen> { - self.breaker_for(server_id, display_name) - .await - .check(display_name) - .await + /// May a call go through? Once the recovery window has elapsed, the + /// breaker turns half-open here and the call is a probe. + pub fn check(&self, server_id: Uuid, display_name: &str) -> Result<(), CircuitOpen> { + self.announce(server_id, display_name); + let (admitted, change) = self.breakers.admit(&server_id); + self.report(display_name, change); + if admitted { Ok(()) } else { Err(CircuitOpen) } } - pub async fn record_success(&self, server_id: Uuid, display_name: &str) { - self.breaker_for(server_id, display_name) - .await - .record_success(display_name) - .await; + pub fn record_success(&self, server_id: Uuid, display_name: &str) { + self.announce(server_id, display_name); + let change = self.breakers.record(&server_id, true); + self.report(display_name, change); } - pub async fn record_failure(&self, server_id: Uuid, display_name: &str) { - self.breaker_for(server_id, display_name) - .await - .record_failure(display_name) - .await; + pub fn record_failure(&self, server_id: Uuid, display_name: &str) { + self.announce(server_id, display_name); + let change = self.breakers.record(&server_id, false); + self.report(display_name, change); } - /// Pre-register a server so it shows up in the dashboard CB snapshot - /// even before its first call. - pub async fn register(&self, server_id: Uuid, display_name: &str) { - let _ = self.breaker_for(server_id, display_name).await; + /// Show a newly added server on the dashboard before its first call. + pub fn register(&self, server_id: Uuid, display_name: &str) { + self.announce(server_id, display_name); } } @@ -291,18 +160,18 @@ mod tests { let cb = McpCircuitBreakers::with_config(cfg()); let id = Uuid::new_v4(); for _ in 0..3 { - cb.record_failure(id, "srv-a").await; + cb.record_failure(id, "srv-a"); } - assert!(cb.check(id, "srv-a").await.is_err()); + assert!(cb.check(id, "srv-a").is_err()); } #[tokio::test] async fn closed_servers_pass_through() { let cb = McpCircuitBreakers::with_config(cfg()); let id = Uuid::new_v4(); - assert!(cb.check(id, "srv-a").await.is_ok()); - cb.record_success(id, "srv-a").await; - assert!(cb.check(id, "srv-a").await.is_ok()); + assert!(cb.check(id, "srv-a").is_ok()); + cb.record_success(id, "srv-a"); + assert!(cb.check(id, "srv-a").is_ok()); } #[tokio::test] @@ -310,18 +179,18 @@ mod tests { let cb = McpCircuitBreakers::with_config(cfg()); let id = Uuid::new_v4(); for _ in 0..3 { - cb.record_failure(id, "srv-b").await; + cb.record_failure(id, "srv-b"); } - assert!(cb.check(id, "srv-b").await.is_err()); + assert!(cb.check(id, "srv-b").is_err()); // Wait past the recovery window then probe. tokio::time::sleep(Duration::from_millis(1100)).await; - assert!(cb.check(id, "srv-b").await.is_ok()); // transitions to HalfOpen + assert!(cb.check(id, "srv-b").is_ok()); // transitions to HalfOpen - cb.record_success(id, "srv-b").await; - cb.record_success(id, "srv-b").await; // half_open_max = 2 + cb.record_success(id, "srv-b"); + cb.record_success(id, "srv-b"); // half_open_max = 2 // Should now be Closed again. - assert!(cb.check(id, "srv-b").await.is_ok()); + assert!(cb.check(id, "srv-b").is_ok()); } #[tokio::test] @@ -329,12 +198,12 @@ mod tests { let cb = McpCircuitBreakers::with_config(cfg()); let id = Uuid::new_v4(); for _ in 0..3 { - cb.record_failure(id, "srv-c").await; + cb.record_failure(id, "srv-c"); } tokio::time::sleep(Duration::from_millis(1100)).await; - assert!(cb.check(id, "srv-c").await.is_ok()); // HalfOpen - cb.record_failure(id, "srv-c").await; // probe fails - assert!(cb.check(id, "srv-c").await.is_err()); // back to Open + assert!(cb.check(id, "srv-c").is_ok()); // HalfOpen + cb.record_failure(id, "srv-c"); // probe fails + assert!(cb.check(id, "srv-c").is_err()); // back to Open } /// Concurrent failures must not bump the breaker past Open multiple @@ -347,15 +216,15 @@ mod tests { let cb2 = cb.clone(); let cb3 = cb.clone(); let (a, b, c) = tokio::join!( - tokio::spawn(async move { cb1.record_failure(id, "srv-d").await }), - tokio::spawn(async move { cb2.record_failure(id, "srv-d").await }), - tokio::spawn(async move { cb3.record_failure(id, "srv-d").await }), + tokio::spawn(async move { cb1.record_failure(id, "srv-d") }), + tokio::spawn(async move { cb2.record_failure(id, "srv-d") }), + tokio::spawn(async move { cb3.record_failure(id, "srv-d") }), ); a.unwrap(); b.unwrap(); c.unwrap(); // Threshold = 3 → all three failures together must trip Open exactly once. - assert!(cb.check(id, "srv-d").await.is_err()); + assert!(cb.check(id, "srv-d").is_err()); } /// Concurrent half-open probes must not all be allowed through at once @@ -366,7 +235,7 @@ mod tests { let cb = McpCircuitBreakers::with_config(cfg()); let id = Uuid::new_v4(); for _ in 0..3 { - cb.record_failure(id, "srv-e").await; + cb.record_failure(id, "srv-e"); } tokio::time::sleep(Duration::from_millis(1100)).await; // Three concurrent checks — all should succeed (HalfOpen lets @@ -375,9 +244,9 @@ mod tests { let cb2 = cb.clone(); let cb3 = cb.clone(); let r = tokio::join!( - tokio::spawn(async move { cb1.check(id, "srv-e").await.is_ok() }), - tokio::spawn(async move { cb2.check(id, "srv-e").await.is_ok() }), - tokio::spawn(async move { cb3.check(id, "srv-e").await.is_ok() }), + tokio::spawn(async move { cb1.check(id, "srv-e").is_ok() }), + tokio::spawn(async move { cb2.check(id, "srv-e").is_ok() }), + tokio::spawn(async move { cb3.check(id, "srv-e").is_ok() }), ); // All three should be permitted as HalfOpen probes. assert!(r.0.unwrap() && r.1.unwrap() && r.2.unwrap()); @@ -392,11 +261,11 @@ mod tests { let id_a = Uuid::new_v4(); let id_b = Uuid::new_v4(); for _ in 0..3 { - cb.record_failure(id_a, "github").await; + cb.record_failure(id_a, "github"); } - assert!(cb.check(id_a, "github").await.is_err()); + assert!(cb.check(id_a, "github").is_err()); // B has the same display name but a different ID — must remain Closed. - assert!(cb.check(id_b, "github").await.is_ok()); + assert!(cb.check(id_b, "github").is_ok()); } /// Rename: same UUID, new display name. The breaker is keyed by @@ -416,7 +285,7 @@ mod tests { let new_name = format!("rename-new-{}", id.simple()); // First touch registers under the OLD name. - cb.register(id, &old_name).await; + cb.register(id, &old_name); assert!(snapshot_cb_states().contains_key(&old_name)); // Admin renames the server. Subsequent state changes pass the @@ -425,7 +294,7 @@ mod tests { // continue to emit under the old key and `new_name` would // never appear. for _ in 0..3 { - cb.record_failure(id, &new_name).await; + cb.record_failure(id, &new_name); } let snap = snapshot_cb_states(); assert!( diff --git a/crates/mcp-gateway/src/lifecycle/mod.rs b/crates/mcp-gateway/src/lifecycle/mod.rs index 499174d3..4c58c17a 100644 --- a/crates/mcp-gateway/src/lifecycle/mod.rs +++ b/crates/mcp-gateway/src/lifecycle/mod.rs @@ -156,8 +156,7 @@ impl Surface for McpSurface { } => { deps.proxy .circuit_breakers - .record_failure(deps.server_id, &deps.server_name) - .await; + .record_failure(deps.server_id, &deps.server_name); } _ => { let response = response_for_hooks(invoked, deps); diff --git a/crates/mcp-gateway/src/lifecycle/stages/check_breaker.rs b/crates/mcp-gateway/src/lifecycle/stages/check_breaker.rs index 75955f70..97aef36c 100644 --- a/crates/mcp-gateway/src/lifecycle/stages/check_breaker.rs +++ b/crates/mcp-gateway/src/lifecycle/stages/check_breaker.rs @@ -42,7 +42,7 @@ pub async fn check_breaker( server_name: &str, audit: &AuditLogger, ) -> Result, JsonRpcResponse> { - if breakers.check(server_id, server_name).await.is_err() { + if breakers.check(server_id, server_name).is_err() { metrics::counter!("lifecycle_breaker_short_circuit_total").increment(1); tracing::warn!( trace_id = %state.trace_id, diff --git a/crates/mcp-gateway/src/proxy.rs b/crates/mcp-gateway/src/proxy.rs index f7a0065b..1e0af486 100644 --- a/crates/mcp-gateway/src/proxy.rs +++ b/crates/mcp-gateway/src/proxy.rs @@ -1112,13 +1112,9 @@ impl McpProxy { }) .unwrap_or(false); if is_server_failure { - self.circuit_breakers - .record_failure(server_id, server_name) - .await; + self.circuit_breakers.record_failure(server_id, server_name); } else { - self.circuit_breakers - .record_success(server_id, server_name) - .await; + self.circuit_breakers.record_success(server_id, server_name); } } } diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index c912b209..87744368 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -11,6 +11,7 @@ name = "think-watch-server" path = "src/main.rs" [dependencies] +tw-breaker = { workspace = true } tw-crypto = { workspace = true } think-watch-common = { workspace = true } think-watch-auth = { workspace = true } diff --git a/crates/server/src/app.rs b/crates/server/src/app.rs index 4787901f..3fe19000 100644 --- a/crates/server/src/app.rs +++ b/crates/server/src/app.rs @@ -343,10 +343,7 @@ pub async fn create_gateway_app(_config: &AppConfig, state: AppState) -> anyhow: // Pre-register a CB for every loaded server so the dashboard upstream // health panel shows them as `Closed` immediately on first paint. for server in registry.list().await { - state - .mcp_circuit_breakers - .register(server.id, &server.name) - .await; + state.mcp_circuit_breakers.register(server.id, &server.name); } // Background health check loop — keeps the in-memory registry status diff --git a/crates/server/src/handlers/admin/settings.rs b/crates/server/src/handlers/admin/settings.rs index 8d727183..d48b6245 100644 --- a/crates/server/src/handlers/admin/settings.rs +++ b/crates/server/src/handlers/admin/settings.rs @@ -706,6 +706,15 @@ fn validate_setting(key: &str, value: &serde_json::Value) -> Result<(), AppError } } + "security.hidden_text" => { + serde_json::from_value::(value.clone()) + .map_err(|_| { + AppError::BadRequest(format!( + "{key} must be one of \"off\", \"log\", \"warn\", \"block\"" + )) + })?; + } + "security.tool_inspection" => { let cfg: think_watch_gateway::tool_inspection::ToolInspectionConfig = serde_json::from_value(value.clone()) diff --git a/crates/server/src/handlers/dashboard/live.rs b/crates/server/src/handlers/dashboard/live.rs index 082ec4a1..6493b19a 100644 --- a/crates/server/src/handlers/dashboard/live.rs +++ b/crates/server/src/handlers/dashboard/live.rs @@ -121,6 +121,45 @@ pub struct DashboardLive { pub top_users: TopActiveUsersResponse, } +/// Each active AI provider's breaker state, the worst of its routes. +/// Best-effort: a failed lookup reads as closed rather than failing the +/// whole dashboard. +async fn ai_breaker_states( + state: &AppState, +) -> std::collections::HashMap { + use tw_breaker::State; + let rows: Vec<(uuid::Uuid, String)> = match sqlx::query_as( + "SELECT mr.id, p.name FROM model_routes mr \ + JOIN providers p ON p.id = mr.provider_id \ + WHERE p.is_active = true AND p.deleted_at IS NULL", + ) + .fetch_all(&state.db) + .await + { + Ok(r) => r, + Err(e) => { + tracing::warn!("dashboard: route list for breaker states failed: {e}"); + return Default::default(); + } + }; + let cfg = think_watch_gateway::health::CircuitBreakerConfig::load(&state.dynamic_config).await; + let tracker = think_watch_gateway::health::HealthTracker::new(state.redis.clone()); + let severity = |s: State| match s { + State::Closed => 0, + State::HalfOpen => 1, + State::Open => 2, + }; + let mut out = std::collections::HashMap::new(); + for (route_id, provider) in rows { + let s = tracker.state(route_id, cfg).await; + let worst = out.entry(provider).or_insert(State::Closed); + if severity(s) > severity(*worst) { + *worst = s; + } + } + out +} + /// Build a live snapshot. Reused by both the HTTP endpoint and the WS loop. /// /// `user_filter` is the result of `resolve_dashboard_user_filter` — @@ -159,6 +198,14 @@ pub(super) async fn build_live_snapshot( // Snapshot the in-process CB registry once so we can decorate every // provider row with its real state below. let cb_states = think_watch_common::cb_registry::snapshot_cb_states(); + // AI routes keep their breakers in Redis, shared by every replica; the + // registry above only holds this process's MCP breakers. A provider + // reads as its worst route. + let ai_states = ai_breaker_states(state).await; + let ai_label = |name: &str| { + think_watch_common::cb_registry::label(ai_states.get(name).copied().unwrap_or_default()) + .to_string() + }; let seed_provider = |kind: ProviderKind, name: &str| ProviderHealth { kind, @@ -171,10 +218,7 @@ pub(super) async fn build_live_snapshot( // from a healthy-but-active upstream. success_rate: None, throttled_rate: None, - cb_state: cb_states - .get(name) - .map(|c| c.as_str().to_string()) - .unwrap_or_else(|| "Closed".to_string()), + cb_state: ai_label(name), }; // MCP servers are a special case: when `mcp_servers.status` says // "disconnected" we DO want the row to read as down even with zero @@ -188,7 +232,7 @@ pub(super) async fn build_live_snapshot( } else { cb_states .get(name) - .map(|c| c.as_str().to_string()) + .map(|c| think_watch_common::cb_registry::label(*c).to_string()) .unwrap_or_else(|| "Closed".to_string()) }; ProviderHealth { @@ -549,10 +593,7 @@ pub(super) async fn build_live_snapshot( .into_iter() .map(|r| ProviderHealth { kind: ProviderKind::Ai, - cb_state: cb_states - .get(&r.provider) - .map(|c| c.as_str().to_string()) - .unwrap_or_else(|| "Closed".to_string()), + cb_state: ai_label(&r.provider), provider: r.provider, success_rate: optionalize(r.requests, r.success_rate), throttled_rate: optionalize(r.requests, r.throttled_rate), @@ -565,7 +606,7 @@ pub(super) async fn build_live_snapshot( kind: ProviderKind::Mcp, cb_state: cb_states .get(&r.provider) - .map(|c| c.as_str().to_string()) + .map(|c| think_watch_common::cb_registry::label(*c).to_string()) .unwrap_or_else(|| "Closed".to_string()), provider: r.provider, success_rate: optionalize(r.requests, r.success_rate), diff --git a/crates/server/src/handlers/mcp_servers.rs b/crates/server/src/handlers/mcp_servers.rs index cbe8633f..541e2b94 100644 --- a/crates/server/src/handlers/mcp_servers.rs +++ b/crates/server/src/handlers/mcp_servers.rs @@ -614,10 +614,7 @@ pub async fn create_server( .await { state.mcp_registry.register(registered).await; - state - .mcp_circuit_breakers - .register(server.id, &server.name) - .await; + state.mcp_circuit_breakers.register(server.id, &server.name); } // Kick off tool discovery in the background — adding a server in @@ -1094,8 +1091,7 @@ pub async fn update_server( state.mcp_registry.register(registered).await; state .mcp_circuit_breakers - .register(updated.id, &updated.name) - .await; + .register(updated.id, &updated.name); } // Wipe response cache for this server across every user. Admin diff --git a/crates/server/src/handlers/route_observability.rs b/crates/server/src/handlers/route_observability.rs index 52c41202..884b7750 100644 --- a/crates/server/src/handlers/route_observability.rs +++ b/crates/server/src/handlers/route_observability.rs @@ -69,10 +69,10 @@ pub async fn list_route_health( // window — so the UI sees the exact view the breaker uses to // make selection decisions. let tracker = think_watch_gateway::health::HealthTracker::new(state.redis.clone()); - let window_secs = state.dynamic_config.cb_window_secs().await; + let cfg = think_watch_gateway::health::CircuitBreakerConfig::load(&state.dynamic_config).await; let route_ids: Vec = rows.iter().map(|r| r.route_id).collect(); - let healths = tracker.snapshot_many(&route_ids, window_secs).await; + let healths = tracker.snapshot_many(&route_ids, cfg).await; let mut by_id: std::collections::HashMap = healths.into_iter().collect(); let entries: Vec = rows diff --git a/crates/test-support/tests/gateway_failover.rs b/crates/test-support/tests/gateway_failover.rs index 79949c27..8817c5f7 100644 --- a/crates/test-support/tests/gateway_failover.rs +++ b/crates/test-support/tests/gateway_failover.rs @@ -198,3 +198,148 @@ async fn all_providers_failing_returns_upstream_error() { resp.status ); } + +/// A tripped route comes back after the cooldown. +/// +/// The breaker used to move from open to half-open only when a request on +/// that route completed — and an open route is never picked, so it stayed +/// open until its Redis key expired, about four cooldowns later. A cooled +/// breaker now reads as half-open, the next request probes it, and a +/// success closes it. +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn a_tripped_route_is_probed_again_once_the_cooldown_is_over() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let app = TestApp::spawn().await; + for (k, v) in [ + ("gateway.cb_enabled", json!(true)), + ("gateway.cb_error_pct", json!(50)), + ("gateway.cb_min_samples", json!(2)), + ("gateway.cb_window_secs", json!(60)), + ("gateway.cb_open_secs", json!(1)), + ] { + fixtures::set_setting(&app.db, k, v).await.unwrap(); + } + app.state.dynamic_config.reload().await.unwrap(); + + // Fails twice, then recovers. + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v1/chat/completions")) + .respond_with( + ResponseTemplate::new(500).set_body_json(json!({"error": {"message": "boom"}})), + ) + .up_to_n_times(2) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/v1/chat/completions")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "id": "c", "object": "chat.completion", "created": 1, "model": "cb-model", + "choices": [{"index": 0, "message": {"role": "assistant", "content": "back"}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, + }))) + .mount(&server) + .await; + + let user = fixtures::create_random_user(&app.db).await.unwrap(); + let p = fixtures::create_provider(&app.db, &unique_name("cb"), "openai", &server.uri(), None) + .await + .unwrap(); + fixtures::create_model_route(&app.db, p.id, "cb-model", 100) + .await + .unwrap(); + app.rebuild_gateway_router().await; + let key = fixtures::create_api_key(&app.db, user.user.id, "cb", &["ai_gateway"], None, None) + .await + .unwrap(); + let gw = app.gateway_client(); + gw.set_bearer(&key.plaintext); + let ask = || { + gw.post( + "/v1/chat/completions", + json!({"model": "cb-model", "messages": [{"role": "user", "content": "ping"}]}), + ) + }; + let hits = || async { server.received_requests().await.unwrap_or_default().len() }; + + // Two failures: 100% errors over 2 samples trips it. + assert!(!ask().await.unwrap().status.is_success()); + assert!(!ask().await.unwrap().status.is_success()); + assert_eq!(hits().await, 2); + + // Open: refused without reaching the upstream. + assert!(!ask().await.unwrap().status.is_success()); + assert_eq!(hits().await, 2, "an open route was still called"); + + // Cooled: half-open, probed, recovered. + tokio::time::sleep(std::time::Duration::from_millis(1200)).await; + let resp = ask().await.unwrap(); + resp.assert_ok(); + assert_eq!(hits().await, 3); + let body: Value = resp.json().unwrap(); + assert_eq!(body["choices"][0]["message"]["content"], "back"); + + // Closed again: the next one goes straight through. + ask().await.unwrap().assert_ok(); +} + +/// The dashboard shows a tripped AI route's provider as open. Its state +/// used to come from a process-local registry only the MCP breaker wrote +/// to, so every AI provider read `Closed` whatever its routes were doing. +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn the_dashboard_shows_a_tripped_ai_provider_as_open() { + let app = TestApp::spawn_with_clickhouse().await; + for (k, v) in [ + ("gateway.cb_enabled", json!(true)), + ("gateway.cb_error_pct", json!(50)), + ("gateway.cb_min_samples", json!(2)), + ("gateway.cb_open_secs", json!(600)), + ] { + fixtures::set_setting(&app.db, k, v).await.unwrap(); + } + app.state.dynamic_config.reload().await.unwrap(); + + let bad = MockProvider::always_500().await; + let name = unique_name("tripped"); + let user = fixtures::create_random_user(&app.db).await.unwrap(); + let p = fixtures::create_provider(&app.db, &name, "openai", &bad.uri(), None) + .await + .unwrap(); + fixtures::create_model_route(&app.db, p.id, "dash-model", 100) + .await + .unwrap(); + app.rebuild_gateway_router().await; + let key = fixtures::create_api_key(&app.db, user.user.id, "dash", &["ai_gateway"], None, None) + .await + .unwrap(); + let gw = app.gateway_client(); + gw.set_bearer(&key.plaintext); + for _ in 0..2 { + let _ = gw + .post( + "/v1/chat/completions", + json!({"model": "dash-model", "messages": [{"role": "user", "content": "x"}]}), + ) + .await + .unwrap(); + } + + let con = admin_session(&app).await; + let live: Value = con + .get("/api/dashboard/live") + .await + .unwrap() + .json() + .unwrap(); + let row = live["providers"] + .as_array() + .unwrap() + .iter() + .find(|r| r["provider"] == name.as_str()) + .unwrap_or_else(|| panic!("no row for {name}: {live}")); + assert_eq!(row["cb_state"], "Open", "{row}"); +} diff --git a/crates/test-support/tests/hidden_text.rs b/crates/test-support/tests/hidden_text.rs new file mode 100644 index 00000000..f615aa1f --- /dev/null +++ b/crates/test-support/tests/hidden_text.rs @@ -0,0 +1,145 @@ +//! Hidden characters in a request, end to end at the gateway. +//! +//! Unicode tag characters can carry a whole instruction invisibly. They +//! are checked in what the caller sends, tool results included. + +use serde_json::Value; +use think_watch_test_support::prelude::*; + +/// "ignore" written in tag characters, after some ordinary text. +fn smuggled() -> String { + "summarise this page" + .chars() + .chain( + "ignore" + .chars() + .map(|c| char::from_u32(0xE0000 + c as u32).unwrap()), + ) + .collect() +} + +async fn seed(app: &TestApp, upstream: &str) -> (String, String) { + let user = fixtures::create_random_user(&app.db).await.unwrap(); + let p = fixtures::create_provider(&app.db, &unique_name("hidden"), "openai", upstream, None) + .await + .unwrap(); + fixtures::create_model_and_route(&app.db, p.id, "hidden-model") + .await + .unwrap(); + app.rebuild_gateway_router().await; + let key = + fixtures::create_api_key(&app.db, user.user.id, "hidden", &["ai_gateway"], None, None) + .await + .unwrap(); + (key.plaintext, user.user.id.to_string()) +} + +/// A tool result carrying the smuggled text, in Chat's shape. +fn with_tool_result() -> Value { + json!({ + "model": "hidden-model", + "messages": [ + {"role": "user", "content": "read the page"}, + {"role": "assistant", "content": null, "tool_calls": [ + {"id": "c1", "type": "function", "function": {"name": "fetch", "arguments": "{}"}} + ]}, + {"role": "tool", "tool_call_id": "c1", "content": smuggled()}, + ] + }) +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn block_refuses_a_tool_result_carrying_tag_characters() { + let app = TestApp::spawn().await; + fixtures::set_setting(&app.db, "security.hidden_text", json!("block")) + .await + .unwrap(); + app.state.dynamic_config.reload().await.unwrap(); + let upstream = MockProvider::openai_chat_ok("hidden-model").await; + let (key, _) = seed(&app, &upstream.uri()).await; + + let gw = app.gateway_client(); + gw.set_bearer(&key); + let resp = gw + .post("/v1/chat/completions", with_tool_result()) + .await + .unwrap(); + assert_eq!(resp.status.as_u16(), 403, "{}", resp.text()); + assert!(resp.text().contains("tool result"), "{}", resp.text()); + assert!( + upstream.received_requests().await.is_empty(), + "the upstream saw it anyway" + ); +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn warn_is_the_default_and_lets_it_through_with_an_audit_event() { + let app = TestApp::spawn_with_clickhouse().await; + let upstream = MockProvider::openai_chat_ok("hidden-model").await; + let (key, user_id) = seed(&app, &upstream.uri()).await; + + let gw = app.gateway_client(); + gw.set_bearer(&key); + gw.post("/v1/chat/completions", with_tool_result()) + .await + .unwrap() + .assert_ok(); + + let ch = app.state.clickhouse.as_ref().expect("ClickHouse wired up"); + for _ in 0..200 { + let rows: Vec = ch + .query("SELECT ifNull(detail, '') FROM audit_logs WHERE user_id = ? AND action = ?") + .bind(&user_id) + .bind("gateway.hidden_text_flagged") + .fetch_all() + .await + .expect("CH query"); + if let Some(d) = rows.first() { + let v: Value = serde_json::from_str(d).unwrap(); + assert_eq!(v["found"][0]["kind"], "tag", "{v}"); + assert_eq!(v["found"][0]["in_tool_result"], true, "{v}"); + return; + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + panic!("no gateway.hidden_text_flagged audit row"); +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn ordinary_multilingual_text_is_not_flagged_even_in_block_mode() { + let app = TestApp::spawn().await; + fixtures::set_setting(&app.db, "security.hidden_text", json!("block")) + .await + .unwrap(); + app.state.dynamic_config.reload().await.unwrap(); + let upstream = MockProvider::openai_chat_ok("hidden-model").await; + let (key, _) = seed(&app, &upstream.uri()).await; + let gw = app.gateway_client(); + gw.set_bearer(&key); + gw.post( + "/v1/chat/completions", + json!({"model": "hidden-model", "messages": [{"role": "user", + "content": "👨\u{200D}👩\u{200D}👧 Привет می\u{200C}خواهم مرحبا"}]}), + ) + .await + .unwrap() + .assert_ok(); +} + +#[ignore = "integration test — run via `make test-it`"] +#[tokio::test] +async fn the_setting_refuses_a_word_it_does_not_know() { + let app = TestApp::spawn().await; + let con = admin_session(&app).await; + let r = con + .patch( + "/api/admin/settings", + json!({"settings": {"security.hidden_text": "maybe"}}), + ) + .await + .unwrap(); + assert_eq!(r.status.as_u16(), 400, "{}", r.text()); +} diff --git a/db/seeds.sql b/db/seeds.sql index cb10fde3..eb367bf2 100644 --- a/db/seeds.sql +++ b/db/seeds.sql @@ -101,6 +101,7 @@ INSERT INTO system_settings (key, value, category, description) VALUES {"name": "phone_us", "regex": "\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b", "placeholder_prefix": "PHONE"}, {"name": "ipv4", "regex": "\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b", "placeholder_prefix": "IP"} ]', 'security', 'PII redactor patterns (JSON array)'), +('security.hidden_text', '"warn"', 'security', 'What a request carrying hidden characters (Unicode tag characters, bidi overrides) gets: off, log, warn or block'), ('security.tool_inspection', '{"mode": "observe", "disabled": [], "actions": {}, "custom": []}', 'security', 'Tool-call inspection: mode, built-in rules switched off or re-graded, custom rules (JSON object)'), ('security.budget_alert_webhook_url', '""', 'security', 'Webhook URL for budget cap alerts'), ('security.trusted_proxies', '[]', 'security', 'JSON array of trusted reverse proxy IPs') diff --git a/web/src/i18n/en.json b/web/src/i18n/en.json index 45b47168..f3859b5f 100644 --- a/web/src/i18n/en.json +++ b/web/src/i18n/en.json @@ -1425,6 +1425,13 @@ "sandboxMatchCount": "{{count}} item(s) redacted", "redactedOutput": "Redacted output (what the AI receives)" }, + "hiddenText": { + "title": "Hidden characters", + "intro": "Unicode tag characters render as nothing and still reach the model, so a whole instruction can ride along invisibly; bidirectional overrides make text read on screen in a different order than it really is. Neither has a use in a prompt, and both turn up where the caller did not write them — in a page or file a tool fetched. The caller's messages and the tool results inside them are checked; emoji, Persian and Russian text are not flagged.", + "action": "When found", + "off": "Off", + "behavior": "Warn lets the request through and writes gateway.hidden_text_flagged to the audit log; Block refuses it with 403 and writes gateway.hidden_text_blocked; Log only records it in the application log." + }, "toolInspection": { "title": "Tool-call inspection", "intro": "The upstream writes the response, so it can hand back a tool call the model never made, such as a command that downloads and runs a script. Every tool call in a response is checked against these rules. Observe records each hit in the audit log and changes nothing; Enforce also cuts the response when a rule set to Cut matches, so the client never receives a complete call. Changes apply immediately, no restart needed.", diff --git a/web/src/i18n/zh.json b/web/src/i18n/zh.json index 43c077a8..77d9f82e 100644 --- a/web/src/i18n/zh.json +++ b/web/src/i18n/zh.json @@ -1425,6 +1425,13 @@ "sandboxMatchCount": "脱敏 {{count}} 项", "redactedOutput": "脱敏后输出(AI 接收到的内容)" }, + "hiddenText": { + "title": "隐藏字符", + "intro": "Unicode 标签字符在屏幕上不显示,却会进入模型的输入,一整段指令可以藏在里面;双向覆盖符会让屏幕上的文字顺序和实际字符顺序不一致。这两种字符在提示词里都没有正当用途,而且常出现在调用方并没有写过的地方,例如工具抓取的网页或文件。检查范围是调用方的消息及其中的工具结果;表情、波斯文和俄文不会被误报。", + "action": "发现时", + "off": "关闭", + "behavior": "告警:放行请求,并在审计日志中写入 gateway.hidden_text_flagged;拦截:以 403 拒绝请求,并写入 gateway.hidden_text_blocked;记录:只写入应用日志。" + }, "toolInspection": { "title": "工具调用审查", "intro": "响应由上游写出,上游可以在其中加入模型并未发出的工具调用,例如下载并执行脚本的命令。响应中的每个工具调用都会按这些规则检查。观察档只在审计日志中记录命中,不改变响应;拦截档在处置为「切断」的规则命中时截断响应,客户端收不到完整的调用。修改立即生效,无需重启。", diff --git a/web/src/routes/admin/settings/types.ts b/web/src/routes/admin/settings/types.ts index 0847b4c4..3c3d1d3e 100644 --- a/web/src/routes/admin/settings/types.ts +++ b/web/src/routes/admin/settings/types.ts @@ -122,6 +122,13 @@ export interface PiiTestResponse { matches: PiiTestMatch[]; } +/** `security.hidden_text`: what a request carrying hidden characters gets. */ +export type HiddenTextAction = 'off' | 'log' | 'warn' | 'block'; + +export function normalizeHiddenText(raw: unknown): HiddenTextAction { + return raw === 'off' || raw === 'log' || raw === 'block' ? raw : 'warn'; +} + export type ToolInspectionMode = 'off' | 'observe' | 'enforce'; export type ToolAction = 'cut' | 'record'; diff --git a/web/src/routes/gateway/hidden-text-card.tsx b/web/src/routes/gateway/hidden-text-card.tsx new file mode 100644 index 00000000..92e3a17c --- /dev/null +++ b/web/src/routes/gateway/hidden-text-card.tsx @@ -0,0 +1,62 @@ +import { useTranslation } from 'react-i18next'; +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; +import type { HiddenTextAction } from '../admin/settings/types'; + +interface Props { + action: HiddenTextAction; + onChange: (next: HiddenTextAction) => void; + canWrite: boolean; +} + +/** + * What a request carrying hidden characters gets — Unicode tag characters + * and bidi overrides, in what the caller typed or in a tool result. Saved + * with the page. + */ +export function HiddenTextCard({ action, onChange, canWrite }: Props) { + const { t } = useTranslation(); + return ( + + +
+
+ {t('settings.hiddenText.title')} +

+ {t('settings.hiddenText.intro')} +

+
+
+ {t('settings.hiddenText.action')} + +
+
+
+ +

{t('settings.hiddenText.behavior')}

+
+
+ ); +} diff --git a/web/src/routes/gateway/security.tsx b/web/src/routes/gateway/security.tsx index d912cc66..507478d1 100644 --- a/web/src/routes/gateway/security.tsx +++ b/web/src/routes/gateway/security.tsx @@ -44,13 +44,16 @@ import { type PiiPattern, type PiiTestResponse, type SettingEntry, + type HiddenTextAction, type ToolInspectionConfig, type ToolRule, type ToolTestMatch, getSettingValue, normalizeContentRule, + normalizeHiddenText, normalizeToolInspection, } from '../admin/settings/types'; +import { HiddenTextCard } from './hidden-text-card'; import { ToolInspectionCard } from './tool-inspection-card'; type ContentFilterRuleWithId = ContentFilterRule & { _clientId: string }; @@ -74,6 +77,7 @@ export function GatewaySecurityPage() { const [piiPatterns, setPiiPatterns] = useState([]); const [toolConfig, setToolConfig] = useState(normalizeToolInspection(null)); const [toolRules, setToolRules] = useState([]); + const [hiddenText, setHiddenText] = useState('warn'); const cfPager = useClientPagination(contentFilters, 20); const piiPager = useClientPagination(piiPatterns, 20); @@ -101,6 +105,7 @@ export function GatewaySecurityPage() { const pp = getSettingValue(data, 'security', 'pii_redactor_patterns'); setPiiPatterns(Array.isArray(pp) ? pp : []); setToolConfig(normalizeToolInspection(getSettingValue(data, 'security', 'tool_inspection'))); + setHiddenText(normalizeHiddenText(getSettingValue(data, 'security', 'hidden_text'))); }) .catch((err) => { // Previously silent — left the form blank with no feedback. @@ -130,6 +135,7 @@ export function GatewaySecurityPage() { 'security.content_filter_patterns': dedupCf.map(stripClientId), 'security.pii_redactor_patterns': dedupPii, 'security.tool_inspection': toolConfig, + 'security.hidden_text': hiddenText, }, }); setStatusMsg({ type: 'success', text: t('settings.saved') }); @@ -570,6 +576,12 @@ export function GatewaySecurityPage() { + +