1use serde_json::Value;
4use thiserror::Error;
5
6mod report;
7
8pub use report::{
9 BoundRunReportV2, ExpectedProviderBinding, ExpectedReportIdentity, LegacyV1AdapterError,
10 MAX_REPORT_COUNT, MAX_REPORT_FAILURE_MESSAGE_BYTES, MAX_REPORT_IDENTIFIER_BYTES,
11 MAX_REPORT_SAMPLES, ProviderReportBinding, REPORT_SCHEMA_V2, ReducedProvenanceReport,
12 ReportBindingError, ReportConstructionError, ReportCount, ReportCounts, ReportEnvelopeV2,
13 ReportFailure, ReportIdentifier, ReportIdentifierError, ReportIdentity, ReportOutcome,
14 ReportValidationError, adapt_legacy_v1_json,
15};
16
17pub const MAX_ANDROID_BENCH_PAYLOAD_BYTES: usize = 1024 * 1024;
19
20#[derive(Debug, Error, PartialEq, Eq)]
22pub enum AndroidBenchFrameError {
23 #[error("Android benchmark frame contains invalid JSON: {0}")]
24 InvalidJson(String),
25 #[error("Android benchmark chunk at line {line} appeared before a start marker")]
26 UnexpectedChunk { line: usize },
27 #[error("Android benchmark end marker at line {line} appeared before a start marker")]
28 UnexpectedEnd { line: usize },
29 #[error("Android benchmark frame starting at line {start_line} is incomplete")]
30 IncompleteFrame { start_line: usize },
31 #[error(
32 "Android benchmark frame at line {line} interleaves with frame starting at line {start_line}"
33 )]
34 InterleavedFrame { start_line: usize, line: usize },
35 #[error("Android benchmark payload at line {line} exceeds the {limit}-byte size limit")]
36 PayloadTooLarge { line: usize, limit: usize },
37 #[error("Android benchmark marker at line {line} is malformed")]
38 MalformedMarker { line: usize },
39}
40
41struct OpenAndroidFrame {
42 payload: String,
43 start_line: usize,
44}
45
46pub fn decode_android_bench_frames(logs: &str) -> Result<Vec<Value>, AndroidBenchFrameError> {
52 let mut values = Vec::new();
53 let mut open_frame = None::<OpenAndroidFrame>;
54
55 for (index, line) in logs.lines().enumerate() {
56 let line_number = index + 1;
57 let Some(message) = android_protocol_message(line) else {
58 continue;
59 };
60 if message == "BENCH_JSON_START" {
61 if let Some(frame) = &open_frame {
62 return Err(AndroidBenchFrameError::InterleavedFrame {
63 start_line: frame.start_line,
64 line: line_number,
65 });
66 }
67 open_frame = Some(OpenAndroidFrame {
68 payload: String::new(),
69 start_line: line_number,
70 });
71 } else if let Some(chunk) = message.strip_prefix("BENCH_JSON_CHUNK ") {
72 if let Some(frame) = open_frame.as_mut() {
73 if frame.payload.len().saturating_add(chunk.len()) > MAX_ANDROID_BENCH_PAYLOAD_BYTES
74 {
75 return Err(AndroidBenchFrameError::PayloadTooLarge {
76 line: line_number,
77 limit: MAX_ANDROID_BENCH_PAYLOAD_BYTES,
78 });
79 }
80 frame.payload.push_str(chunk);
81 } else {
82 return Err(AndroidBenchFrameError::UnexpectedChunk { line: line_number });
83 }
84 } else if message == "BENCH_JSON_END" {
85 let Some(frame) = open_frame.take() else {
86 return Err(AndroidBenchFrameError::UnexpectedEnd { line: line_number });
87 };
88 values.push(
89 serde_json::from_str(&frame.payload)
90 .map_err(|error| AndroidBenchFrameError::InvalidJson(error.to_string()))?,
91 );
92 } else if let Some(payload) = message.strip_prefix("BENCH_JSON ") {
93 if let Some(frame) = &open_frame {
94 return Err(AndroidBenchFrameError::InterleavedFrame {
95 start_line: frame.start_line,
96 line: line_number,
97 });
98 }
99 if payload.len() > MAX_ANDROID_BENCH_PAYLOAD_BYTES {
100 return Err(AndroidBenchFrameError::PayloadTooLarge {
101 line: line_number,
102 limit: MAX_ANDROID_BENCH_PAYLOAD_BYTES,
103 });
104 }
105 values.push(
106 serde_json::from_str(payload)
107 .map_err(|error| AndroidBenchFrameError::InvalidJson(error.to_string()))?,
108 );
109 } else {
110 return Err(AndroidBenchFrameError::MalformedMarker { line: line_number });
111 }
112 }
113
114 if let Some(frame) = open_frame {
115 return Err(AndroidBenchFrameError::IncompleteFrame {
116 start_line: frame.start_line,
117 });
118 }
119
120 Ok(values)
121}
122
123fn android_protocol_message(line: &str) -> Option<&str> {
124 const MARKERS: [&str; 4] = [
125 "BENCH_JSON_START",
126 "BENCH_JSON_CHUNK",
127 "BENCH_JSON_END",
128 "BENCH_JSON ",
129 ];
130 let trimmed = line.trim();
131 let (index, _) = MARKERS
132 .iter()
133 .filter_map(|marker| trimmed.find(marker).map(|index| (index, marker)))
134 .min_by_key(|(index, _)| *index)?;
135 if index == 0 {
136 return Some(trimmed);
137 }
138
139 let prefix = trimmed[..index].trim_end();
140 let marker_is_log_message = prefix.contains("BenchRunner")
141 && (prefix.ends_with(':')
142 || matches!(
143 prefix.split_whitespace().last(),
144 Some("V" | "D" | "I" | "W" | "E")
145 ));
146 marker_is_log_message.then_some(&trimmed[index..])
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152
153 #[test]
154 fn decodes_generated_android_chunk_frame() {
155 let logs = r#"
1562026-07-15 I/BenchRunner: BENCH_JSON_START
1572026-07-15 I/BenchRunner: BENCH_JSON_CHUNK {"function":"sample_fns::checksum",
1582026-07-15 I/BenchRunner: BENCH_JSON_CHUNK "samples_ns":[1000,2000]}
1592026-07-15 I/BenchRunner: BENCH_JSON_END
160"#;
161
162 let values = decode_android_bench_frames(logs).expect("decode generated frame");
163
164 assert_eq!(values.len(), 1);
165 assert_eq!(values[0]["function"], "sample_fns::checksum");
166 assert_eq!(values[0]["samples_ns"], serde_json::json!([1000, 2000]));
167 }
168
169 #[test]
170 fn decodes_released_android_legacy_frame() {
171 let logs =
172 r#"2026-01-20 I/BenchRunner: BENCH_JSON {"function":"legacy::bench","samples_ns":[7]}"#;
173
174 let values = decode_android_bench_frames(logs).expect("decode legacy frame");
175
176 assert_eq!(
177 values,
178 vec![serde_json::json!({
179 "function": "legacy::bench",
180 "samples_ns": [7]
181 })]
182 );
183 }
184
185 #[test]
186 fn rejects_android_chunk_before_start() {
187 let logs = r#"I/BenchRunner: BENCH_JSON_CHUNK {"function":"forged"}"#;
188
189 assert_eq!(
190 decode_android_bench_frames(logs),
191 Err(AndroidBenchFrameError::UnexpectedChunk { line: 1 })
192 );
193 }
194
195 #[test]
196 fn rejects_truncated_android_chunk_frame() {
197 let logs = r#"
198I/BenchRunner: BENCH_JSON_START
199I/BenchRunner: BENCH_JSON_CHUNK {"function":"truncated"
200"#;
201
202 assert_eq!(
203 decode_android_bench_frames(logs),
204 Err(AndroidBenchFrameError::IncompleteFrame { start_line: 2 })
205 );
206 }
207
208 #[test]
209 fn rejects_interleaved_android_chunk_frames() {
210 let logs = r#"
211I/BenchRunner: BENCH_JSON_START
212I/BenchRunner: BENCH_JSON_CHUNK {"function":"first"}
213I/BenchRunner: BENCH_JSON_START
214"#;
215
216 assert_eq!(
217 decode_android_bench_frames(logs),
218 Err(AndroidBenchFrameError::InterleavedFrame {
219 start_line: 2,
220 line: 4,
221 })
222 );
223 }
224
225 #[test]
226 fn rejects_android_payload_over_size_bound() {
227 let oversized = "x".repeat(MAX_ANDROID_BENCH_PAYLOAD_BYTES + 1);
228 let logs = format!("I/BenchRunner: BENCH_JSON {{\"payload\":\"{oversized}\"}}");
229
230 assert_eq!(
231 decode_android_bench_frames(&logs),
232 Err(AndroidBenchFrameError::PayloadTooLarge {
233 line: 1,
234 limit: MAX_ANDROID_BENCH_PAYLOAD_BYTES,
235 })
236 );
237 }
238
239 #[test]
240 fn rejects_android_end_before_start() {
241 assert_eq!(
242 decode_android_bench_frames("I/BenchRunner: BENCH_JSON_END"),
243 Err(AndroidBenchFrameError::UnexpectedEnd { line: 1 })
244 );
245 }
246
247 #[test]
248 fn ignores_protocol_words_inside_other_log_messages() {
249 let logs = r#"E/BenchRunner: BENCH_FAILURE_JSON {"message":"worker exited before BENCH_JSON was emitted"}"#;
250
251 assert_eq!(decode_android_bench_frames(logs), Ok(Vec::new()));
252 }
253
254 #[test]
255 fn rejects_android_marker_with_trailing_data() {
256 assert_eq!(
257 decode_android_bench_frames("I/BenchRunner: BENCH_JSON_START forged"),
258 Err(AndroidBenchFrameError::MalformedMarker { line: 1 })
259 );
260 }
261}