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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions bin/twcore/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ tw-control = { workspace = true }
tw-gateway = { workspace = true }
tw-yaml = { workspace = true }
tw-api = { workspace = true }
tw-observe = { workspace = true }
tw-store = { workspace = true }
tw-pricing = { workspace = true }
chrono = { workspace = true }
Expand Down
11 changes: 8 additions & 3 deletions bin/twcore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -668,7 +668,7 @@ fn cmd_serve(path: &Path, port: Option<u16>, safe: bool, parent: Option<u32>) ->
// body 的通道在这里建:**它是唯一同时看得见网关和存储的地方**,
// 而两边各有各的同形结构,是为了不让「观测」挂到「转发」下面。
let (body_tx, body_rx) = tokio::sync::mpsc::channel(tw_gateway::bodies::CHANNEL_CAP);
let store = build_store(&dir, state.bus.subscribe(), body_rx);
let store = build_store(&dir, state.bus.clone(), body_rx);
if store.is_some() {
state.set_body_sink(body_tx);
}
Expand Down Expand Up @@ -795,9 +795,12 @@ fn cmd_serve(path: &Path, port: Option<u16>, safe: bool, parent: Option<u32>) ->
/// 处理方式是「不转发了」。
fn build_store(
dir: &Path,
events: tokio::sync::broadcast::Receiver<tw_api::Event>,
// **收整条总线,不只是一个订阅端。**存储层算完价钱要往回报一条
// (见 `Event::RequestPriced`)—— 它是这条链上唯一知道单价的地方。
bus: tw_observe::EventBus,
bodies: tokio::sync::mpsc::Receiver<tw_gateway::BodyRecord>,
) -> Option<std::sync::Arc<tokio::sync::Mutex<tw_store::Recorder>>> {
let events = bus.subscribe();
let db = match tw_store::Db::open(&dir.join("data.db")) {
Ok(db) => db,
Err(e) => {
Expand Down Expand Up @@ -839,7 +842,9 @@ fn build_store(
}
});
Some(tw_store::task::spawn(
tw_store::Recorder::new(db, blobs, prices),
// 算完价钱往回报一条 —— 见 `Event::RequestPriced`。这里是唯一
// 同时看得见总线和存储层的地方,所以接线在这儿完成。
tw_store::Recorder::new(db, blobs, prices).reporting_to(bus),
events,
rx,
))
Expand Down
22 changes: 22 additions & 0 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,27 @@ pub enum Event {
alerts: Vec<ScanFinding>,
at_ms: u64,
},
/// 这次请求花了多少钱 —— **在它跑完之后一小会儿才知道**。
///
/// 价钱不在数据面的职责里:网关知道用了多少 token,而单价在存储层
/// 落库时才查价目表算出来。所以它是一条独立事件,而不是
/// `RequestFinished` 上的一个字段 —— 后者会要求网关依赖价目表,把
/// 「转发」挂到「计价」下面。
///
/// 没有这条的话,界面想知道价钱就只能在请求结束之后回库里再查一遍。
///
/// 三个值都可能是「算不出来」:上游没报用量、模型不在价目表里、
/// 或者那家是订阅计费 —— **那都不是零**。
RequestPriced {
id: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
cost_micros: Option<i64>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
cost_estimated: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
cache_saved_micros: Option<i64>,
at_ms: u64,
},
/// 客户端配置面上的文件动了 —— **不管改了什么**。
///
/// 和 `ScanAlert` 是两件事。那条说的是「出现了可疑内容」,值得打断
Expand Down Expand Up @@ -338,6 +359,7 @@ impl Event {
| Event::QuotaSeen { id, .. }
| Event::LeakSeen { id, .. }
| Event::ScanAlert { id, .. }
| Event::RequestPriced { id, .. }
| Event::ClientsChanged { id, .. }
| Event::HealthChanged { id, .. }
| Event::Redacted { id, .. }
Expand Down
1 change: 1 addition & 0 deletions crates/tw-store/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ description = "Request history and runtime state on SQLite and the filesystem"

[dependencies]
tw-api = { workspace = true }
tw-observe = { workspace = true }
tw-pricing = { workspace = true }
bytes = { workspace = true }
rusqlite = { workspace = true }
Expand Down
94 changes: 93 additions & 1 deletion crates/tw-store/src/recorder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ pub struct Recorder {
/// 那不理想,但比把它持久化成第四份状态好:会话是个观测概念,不是
/// 事实来源。
sessions: HashMap<String, (String, i64)>,
/// 算完价钱之后往回报一条。
///
/// **这一层是唯一知道价钱的地方** —— 网关只知道用了多少 token,
/// 单价在这里查价目表。不报的话,界面想知道花了多少就只能在请求
/// 结束之后回库里再查一遍。
///
/// `None` 表示没人要听(测试、以及不带总线的调用方)。
bus: Option<tw_observe::EventBus>,
}

/// 多久查一次磁盘。
Expand All @@ -82,9 +90,16 @@ impl Recorder {
sessions: HashMap::new(),
level: DiskLevel::Ok,
last_check_ms: 0,
bus: None,
}
}

/// 把算出来的价钱报回总线上。
pub fn reporting_to(mut self, bus: tw_observe::EventBus) -> Self {
self.bus = Some(bus);
self
}

pub fn level(&self) -> DiskLevel {
self.level
}
Expand Down Expand Up @@ -278,6 +293,17 @@ impl Recorder {
} else {
None
};
// **算完就报,不等人来问。**这是整条链上唯一知道价钱的
// 地方,而界面上那一列金额在它到达之前只能是「—」。
if let Some(bus) = &self.bus {
bus.emit(Event::RequestPriced {
id: *id,
cost_micros,
cost_estimated: estimated,
cache_saved_micros,
at_ms: p.at_ms as u64,
});
}
self.write(RequestRow {
id: *id as i64,
at_ms: p.at_ms,
Expand Down Expand Up @@ -415,7 +441,9 @@ impl Recorder {
// 客户端配置面变了、某家上游熔断了 —— 都是「现在什么情况」,
// 不是「刚才发生过什么」。这张表只装后者。
| Event::ClientsChanged { .. }
| Event::HealthChanged { .. } => {}
| Event::HealthChanged { .. }
// 自己刚报出去的那条。**不能再处理一遍** —— 那是一个回路
| Event::RequestPriced { .. } => {}
Event::ResponseInspected {
id,
tool_calls,
Expand Down Expand Up @@ -858,6 +886,70 @@ mod billing_tests {
}
}

#[cfg(test)]
mod pricing_report_tests {
use super::tests::{finished, rec, started};
use tw_api::UsageView;

/// **算完的价钱要报回去,不能等界面回头来问。**这一层是整条链上
/// 唯一知道单价的地方:网关只知道用了多少 token。不报的话,界面上
/// 那一列金额在请求结束之后只能靠再查一次库才填得上。
#[test]
fn the_price_goes_back_onto_the_bus() {
let (_d, mut r) = rec();
let bus = tw_observe::EventBus::new();
let mut rx = bus.subscribe();
r = r.reporting_to(bus);
r.on_event(&started(1, "claude-sonnet-4-5"));
r.on_event(&finished(
1,
Some(UsageView {
// 压在 200k 以下:超过之后走的是长上下文那档单价
input: 100_000,
output: 0,
..Default::default()
}),
));
let mut priced = None;
while let Ok(ev) = rx.try_recv() {
if let tw_api::Event::RequestPriced {
id, cost_micros, ..
} = ev
{
priced = Some((id, cost_micros));
}
}
// Sonnet 4.5 输入 $3/M —— 十万 token 是 $0.30
assert_eq!(priced, Some((1, Some(300_000))));
}

/// **「算不出来」要原样报出去,不能报成零。**订阅制上游、价目表里
/// 没有的模型,都是这一档 —— 报 0 的话界面会画一个「免费」。
#[test]
fn an_unpriceable_request_reports_nothing_not_zero() {
let (_d, mut r) = rec();
let bus = tw_observe::EventBus::new();
let mut rx = bus.subscribe();
r = r.reporting_to(bus);
r.on_event(&started(1, "某个中转站的模型"));
r.on_event(&finished(
1,
Some(UsageView {
input: 1000,
output: 10,
..Default::default()
}),
));
let mut priced = None;
while let Ok(ev) = rx.try_recv() {
if let tw_api::Event::RequestPriced { cost_micros, .. } = ev {
priced = Some(cost_micros);
}
}
assert_eq!(priced, Some(None));
}
}

#[cfg(test)]
mod redaction_tests {
use super::tests::{finished, rec, started};
Expand Down
Loading