fix(astrbot): give each stream its own frame trace
一些检测仍在等待运行
ci / Portable quality checks (push) Waiting to run
ci / Windows Tauri build (push) Waiting to run

The trace lived in a thread_local, but the SSE read loop is a tokio task
that moves between worker threads across await points, so the
accumulated text was split across several copies. It reported 139 and 57
streamed characters for replies that the raw frames show as 417 and 266,
which made every containment result from it unusable — including the
ones the segmentation question depends on.

Own it in the stream instead. The raw frame lines were unaffected, so
the frame-shape findings still hold; only the per-stream summary was
wrong.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
这个提交存在于:
YokiiroBW 2026-07-27 02:45:27 +08:00
父节点 2ba07bda9d
当前提交 f666a3a041

查看文件

@ -596,6 +596,11 @@ impl AstrBotClient {
// event of the second and later messages on this connection.
let stream_id = uuid::Uuid::new_v4().to_string();
let mut mapper = AstrBotStreamMapper::new(server_instance_id.clone(), stream_id);
// Owned by this stream. It used to live in a thread_local, but the read
// loop is a tokio task that moves between worker threads across await
// points, so the accumulated text was split across several copies and the
// reported totals were a fraction of the real ones.
let mut trace = FrameTrace::default();
if let Some(existing) = session_id {
let seed = serde_json::json!({
"type": "session_id",
@ -648,7 +653,7 @@ impl AstrBotClient {
.await;
}
while let Some(line) = buffer.next_line() {
trace_frame_shape(&line);
trace.observe(&line);
match mapper.push_line(&line) {
Ok(events) => self.dispatch_events(events, sender).await?,
Err(error) => {
@ -667,7 +672,7 @@ impl AstrBotClient {
}
if let Some(remainder) = buffer.take_remainder() {
trace_frame_shape(&remainder);
trace.observe(&remainder);
match mapper.push_line(&remainder) {
Ok(events) => self.dispatch_events(events, sender).await?,
Err(error) => {
@ -760,25 +765,20 @@ impl AstrBotClient {
/// it must stay in sync with `docs/q9-local-acceptance.md`.
const FRAME_TRACE_TARGET: &str = "astrbot::frame";
/// Records the *shape* of one SSE frame at debug level.
/// Per-stream record of the SSE frames, at debug level.
///
/// Deliberately logs no payload text — only the frame type, which identity
/// fields are present, and the key names inside `data`. That is enough to
/// answer the two questions the mapper cannot answer on its own: whether every
/// streaming frame carries a `message_id` (if not, the client cannot key a
/// reply to a single message and splits it), and what shape a plugin's
/// attachment frames actually take.
/// Logs no payload text — only frame types, which identity fields are present,
/// the key names inside `data`, and lengths. Enable with
/// `RUST_LOG=astrbot::frame=debug`; off by default.
///
/// Enable with `RUST_LOG=astrbot::frame=debug`. Off by default.
/// One instance belongs to one stream. It must not be a `thread_local`: the
/// read loop is a tokio task that moves between worker threads across await
/// points, so a thread-local split the accumulated text across several copies
/// and reported totals that were a fraction of the real ones.
///
/// The guard must name the same target as the event. `enabled!` defaults to the
/// module path, so without it the filter would enable the event while the guard
/// still returned false and nothing would ever be written.
fn trace_frame_shape(line: &str) {
FRAME_TRACE.with(|trace| trace.borrow_mut().observe(line));
}
/// Per-stream state for the one question frame shapes cannot answer.
/// Every `enabled!` guard here names the same target as the event it guards.
/// `enabled!` otherwise defaults to the module path, and a filter naming the
/// target would leave the guard returning false with nothing ever written.
///
/// AstrBot interleaves `plain` frames carrying incremental deltas
/// (`streaming: true`) with `plain` frames carrying a whole block
@ -796,11 +796,6 @@ struct FrameTrace {
blocks: Vec<String>,
}
thread_local! {
static FRAME_TRACE: std::cell::RefCell<FrameTrace> =
std::cell::RefCell::new(FrameTrace::default());
}
impl FrameTrace {
/// Structural description of an attachment reference.
///
@ -1080,11 +1075,12 @@ mod tests {
.with_writer(sink.clone())
.finish();
let mut trace = FrameTrace::default();
tracing::subscriber::with_default(subscriber, || {
trace_frame_shape(
trace.observe(
r#"data: {"type":"plain","data":"你好","streaming":true,"message_id":"42"}"#,
);
trace_frame_shape(r#"data: {"type":"image","data":{"url":"http://x/y.png"}}"#);
trace.observe(r#"data: {"type":"image","data":{"url":"http://x/y.png"}}"#);
});
let output = sink.contents();
@ -1118,6 +1114,7 @@ mod tests {
.with_writer(sink.clone())
.finish();
let mut trace = FrameTrace::default();
tracing::subscriber::with_default(subscriber, || {
for line in [
r#"data: {"type":"session_id","session_id":"s1"}"#,
@ -1129,7 +1126,7 @@ mod tests {
r#"data: {"type":"plain","data":"GAMMAWORD","streaming":false}"#,
r#"data: {"type":"complete","data":"ALPHAWORDBETAWORD"}"#,
] {
trace_frame_shape(line);
trace.observe(line);
}
});
@ -1180,8 +1177,9 @@ mod tests {
.with_writer(sink.clone())
.finish();
let mut trace = FrameTrace::default();
tracing::subscriber::with_default(subscriber, || {
trace_frame_shape(r#"data: {"type":"plain","message_id":"42"}"#);
trace.observe(r#"data: {"type":"plain","message_id":"42"}"#);
});
assert!(sink.contents().is_empty());