1use std::io::Read;
9use std::path::{Path, PathBuf};
10
11use jiff::{SignedDuration, Timestamp};
12use serde::{Deserialize, Serialize};
13
14use crate::atomic::write_atomic;
15use crate::error::Error;
16use crate::lock::{RunLock, Shared};
17use crate::paths::{nofollow, reject_symlink, RunPaths};
18use crate::projections::read_node;
19use crate::schema::{NodeId, RunId, Status};
20
21pub const TELEMETRY_SCHEMA_VERSION: u32 = 1;
23pub const TELEMETRY_PROTOCOL_VERSION: u32 = 1;
25pub const TELEMETRY_MAX_BYTES: usize = 4 * 1024;
27pub const TELEMETRY_FRESHNESS_SECS: i64 = 90;
29
30pub trait TelemetryClock {
32 fn now(&self) -> Timestamp;
34}
35
36#[derive(Debug, Clone, Copy, Default)]
38pub struct SystemTelemetryClock;
39
40impl TelemetryClock for SystemTelemetryClock {
41 fn now(&self) -> Timestamp {
42 Timestamp::now()
43 }
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "snake_case")]
49pub enum TelemetryState {
50 AgentActive,
52 ToolRunning,
54 Settled,
56 Shutdown,
58}
59
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(deny_unknown_fields)]
63pub struct TelemetryUpdate {
64 pub schema_version: u32,
66 pub protocol_version: u32,
68 pub run_id: RunId,
70 pub node_id: NodeId,
72 pub attempt: u32,
74 pub state: TelemetryState,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub active_tool_count: Option<u8>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub tool_name: Option<String>,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct TelemetryAccepted {
87 pub accepted: bool,
89 pub run_id: RunId,
91 pub node_id: NodeId,
93 pub attempt: u32,
95 pub received_at: Timestamp,
97 pub expires_at: Timestamp,
99}
100
101#[derive(Debug, thiserror::Error)]
103pub enum TelemetryError {
104 #[error(transparent)]
106 Core(#[from] Error),
107 #[error("invalid telemetry request: {0}")]
109 InvalidRequest(serde_json::Error),
110 #[error("telemetry {what} exceeds {TELEMETRY_MAX_BYTES} bytes (got {bytes})")]
112 TooLarge {
113 what: &'static str,
115 bytes: usize,
117 },
118 #[error("unsupported telemetry schema_version {found}; expected {TELEMETRY_SCHEMA_VERSION}")]
120 UnsupportedSchema {
121 found: u32,
123 },
124 #[error(
126 "unsupported telemetry protocol_version {found}; expected {TELEMETRY_PROTOCOL_VERSION}"
127 )]
128 UnsupportedProtocol {
129 found: u32,
131 },
132 #[error("invalid telemetry tool metadata: {0}")]
134 InvalidMetadata(&'static str),
135 #[error("telemetry run_id {found} does not match current run {expected}")]
137 RunMismatch {
138 expected: RunId,
140 found: RunId,
142 },
143 #[error("canonical run state is not synchronized with the event log")]
146 RunStateNotCurrent,
147 #[error("no node {node_id} in this run")]
149 NodeNotFound {
150 node_id: NodeId,
152 },
153 #[error("node {node_id} is terminal ({status:?})")]
155 TerminalNode {
156 node_id: NodeId,
158 status: Status,
160 },
161 #[error("telemetry attempt {found} does not match current attempt {expected}")]
163 AttemptMismatch {
164 expected: u32,
166 found: u32,
168 },
169 #[error("server clock cannot represent telemetry expiry")]
171 ClockOverflow,
172}
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
176#[serde(rename_all = "snake_case")]
177pub enum TelemetrySampleStatus {
178 Absent,
180 Current,
182 Stale,
184 ClockUnreliable,
186 Invalid,
188}
189
190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
192pub struct TelemetryView {
193 pub sample: TelemetrySampleStatus,
195 #[serde(skip_serializing_if = "Option::is_none")]
197 pub state: Option<TelemetryState>,
198 #[serde(skip_serializing_if = "Option::is_none")]
200 pub age_ms: Option<i64>,
201 #[serde(skip_serializing_if = "Option::is_none")]
203 pub state_elapsed_ms: Option<i64>,
204 #[serde(skip_serializing_if = "Option::is_none")]
206 pub attempt: Option<u32>,
207 #[serde(skip_serializing_if = "Option::is_none")]
209 pub active_tool_count: Option<u8>,
210 #[serde(skip_serializing_if = "Option::is_none")]
212 pub tool_name: Option<String>,
213}
214
215impl TelemetryView {
216 fn bare(sample: TelemetrySampleStatus) -> Self {
217 Self {
218 sample,
219 state: None,
220 age_ms: None,
221 state_elapsed_ms: None,
222 attempt: None,
223 active_tool_count: None,
224 tool_name: None,
225 }
226 }
227}
228
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231#[serde(deny_unknown_fields)]
232struct StoredTelemetrySample {
233 schema_version: u32,
234 protocol_version: u32,
235 run_id: RunId,
236 node_id: NodeId,
237 attempt: u32,
238 state: TelemetryState,
239 #[serde(default, skip_serializing_if = "Option::is_none")]
240 active_tool_count: Option<u8>,
241 #[serde(default, skip_serializing_if = "Option::is_none")]
242 tool_name: Option<String>,
243 state_since: Timestamp,
244 received_at: Timestamp,
245 expires_at: Timestamp,
246}
247
248pub fn parse_telemetry_update(bytes: &[u8]) -> Result<TelemetryUpdate, TelemetryError> {
251 ensure_size("request", bytes.len())?;
252 let update: TelemetryUpdate =
253 serde_json::from_slice(bytes).map_err(TelemetryError::InvalidRequest)?;
254 validate_update_shape(&update)?;
255 let normalized = serde_json::to_vec(&update).map_err(TelemetryError::InvalidRequest)?;
256 ensure_size("normalized request", normalized.len())?;
257 Ok(update)
258}
259
260pub fn update_telemetry(
263 paths: &RunPaths,
264 update: &TelemetryUpdate,
265) -> Result<TelemetryAccepted, TelemetryError> {
266 update_telemetry_with_clock(paths, update, &SystemTelemetryClock)
267}
268
269pub fn update_telemetry_with_clock(
272 paths: &RunPaths,
273 update: &TelemetryUpdate,
274 clock: &impl TelemetryClock,
275) -> Result<TelemetryAccepted, TelemetryError> {
276 validate_update_shape(update)?;
277 let normalized = serde_json::to_vec(update).map_err(TelemetryError::InvalidRequest)?;
278 ensure_size("normalized request", normalized.len())?;
279 if update.run_id != paths.run_id {
280 return Err(TelemetryError::RunMismatch {
281 expected: paths.run_id.clone(),
282 found: update.run_id.clone(),
283 });
284 }
285
286 let guard = RunLock::acquire_existing(&paths.lock())?;
289 if !canonical_projections_current(paths)? {
293 return Err(TelemetryError::RunStateNotCurrent);
294 }
295 let node = match crate::read_node_opt(paths, &update.node_id)? {
296 Some(node) => node,
297 None => {
298 return Err(TelemetryError::NodeNotFound {
299 node_id: update.node_id.clone(),
300 })
301 }
302 };
303 if node.status.is_terminal() {
304 return Err(TelemetryError::TerminalNode {
305 node_id: node.node_id,
306 status: node.status,
307 });
308 }
309 if update.attempt != node.retry_attempts {
310 return Err(TelemetryError::AttemptMismatch {
311 expected: node.retry_attempts,
312 found: update.attempt,
313 });
314 }
315
316 let received_at = clock.now();
317 let expires_at = received_at
318 .checked_add(SignedDuration::from_secs(TELEMETRY_FRESHNESS_SECS))
319 .ok()
320 .ok_or(TelemetryError::ClockOverflow)?;
321 let path = checked_telemetry_file(paths, &update.node_id)?;
322 let prior = match read_stored(&path)? {
323 StoredRead::Valid(sample) => Some(sample),
324 StoredRead::Absent | StoredRead::Corrupt => None,
325 };
326 let state_since = prior
327 .filter(|sample| {
328 valid_stored_shape(sample, paths, &update.node_id)
329 && sample.attempt == update.attempt
330 && sample.state == update.state
331 })
332 .map_or(received_at, |sample| sample.state_since);
333 let sample = StoredTelemetrySample {
334 schema_version: TELEMETRY_SCHEMA_VERSION,
335 protocol_version: TELEMETRY_PROTOCOL_VERSION,
336 run_id: update.run_id.clone(),
337 node_id: update.node_id.clone(),
338 attempt: update.attempt,
339 state: update.state,
340 active_tool_count: update.active_tool_count,
341 tool_name: update.tool_name.clone(),
342 state_since,
343 received_at,
344 expires_at,
345 };
346 let stored = serde_json::to_vec(&sample).map_err(TelemetryError::InvalidRequest)?;
347 ensure_size("stored sample", stored.len())?;
348 write_atomic(&path, &stored)?;
349 drop(guard);
350
351 Ok(TelemetryAccepted {
352 accepted: true,
353 run_id: update.run_id.clone(),
354 node_id: update.node_id.clone(),
355 attempt: update.attempt,
356 received_at,
357 expires_at,
358 })
359}
360
361pub fn read_telemetry(paths: &RunPaths, node_id: &NodeId) -> Result<TelemetryView, TelemetryError> {
363 read_telemetry_with_clock(paths, node_id, &SystemTelemetryClock)
364}
365
366pub fn read_telemetry_with_clock(
369 paths: &RunPaths,
370 node_id: &NodeId,
371 clock: &impl TelemetryClock,
372) -> Result<TelemetryView, TelemetryError> {
373 let result = RunLock::<Shared>::with_shared_lock(&paths.lock(), || {
374 if !canonical_projections_current(paths)? {
375 return Ok(None);
376 }
377 read_telemetry_locked(paths, node_id, clock.now()).map(Some)
378 })?;
379 result.ok_or(TelemetryError::RunStateNotCurrent)
380}
381
382pub fn read_all_telemetry(
393 paths: &RunPaths,
394) -> Result<Vec<(NodeId, TelemetryView)>, TelemetryError> {
395 read_all_telemetry_with_clock(paths, &SystemTelemetryClock)
396}
397
398pub fn read_all_telemetry_with_clock(
400 paths: &RunPaths,
401 clock: &impl TelemetryClock,
402) -> Result<Vec<(NodeId, TelemetryView)>, TelemetryError> {
403 let result = RunLock::<Shared>::with_shared_lock(&paths.lock(), || {
404 let node_ids = projected_node_ids(paths)?;
405 if !canonical_projections_current(paths)? {
406 return Ok(None);
407 }
408 let now = clock.now();
409 let mut rows = Vec::with_capacity(node_ids.len());
410 for node_id in node_ids {
411 let view = read_telemetry_locked(paths, &node_id, now)?;
412 rows.push((node_id, view));
413 }
414 Ok(Some(rows))
415 })?;
416 result.ok_or(TelemetryError::RunStateNotCurrent)
417}
418
419fn read_telemetry_locked(
420 paths: &RunPaths,
421 node_id: &NodeId,
422 now: Timestamp,
423) -> Result<TelemetryView, Error> {
424 let node = read_node(paths, node_id)?;
425 let path = checked_telemetry_file(paths, node_id)?;
426 let sample = match read_stored(&path)? {
427 StoredRead::Absent => return Ok(TelemetryView::bare(TelemetrySampleStatus::Absent)),
428 StoredRead::Corrupt => return Ok(TelemetryView::bare(TelemetrySampleStatus::Invalid)),
429 StoredRead::Valid(sample) => sample,
430 };
431 if !valid_stored_shape(&sample, paths, node_id) {
432 return Ok(TelemetryView::bare(TelemetrySampleStatus::Invalid));
433 }
434 if sample.attempt != node.retry_attempts {
435 return Ok(TelemetryView::bare(TelemetrySampleStatus::Absent));
436 }
437 let clock_bad = now < sample.received_at || now < sample.state_since;
438 let status = if clock_bad {
439 TelemetrySampleStatus::ClockUnreliable
440 } else if now >= sample.expires_at {
441 TelemetrySampleStatus::Stale
442 } else {
443 TelemetrySampleStatus::Current
444 };
445 Ok(TelemetryView {
446 sample: status,
447 state: Some(sample.state),
448 age_ms: (!clock_bad).then(|| now.duration_since(sample.received_at).as_millis() as i64),
449 state_elapsed_ms: (!clock_bad)
450 .then(|| now.duration_since(sample.state_since).as_millis() as i64),
451 attempt: Some(sample.attempt),
452 active_tool_count: sample.active_tool_count,
453 tool_name: sample.tool_name,
454 })
455}
456
457fn canonical_projections_current(paths: &RunPaths) -> Result<bool, Error> {
458 let Some(manifest) = crate::read_manifest_opt(paths)? else {
459 return Ok(false);
460 };
461 let events = paths.checked_events()?;
462 Ok(manifest.applied_seq == crate::recover_last_seq(&events)?)
463}
464
465fn validate_update_shape(update: &TelemetryUpdate) -> Result<(), TelemetryError> {
466 if update.schema_version != TELEMETRY_SCHEMA_VERSION {
467 return Err(TelemetryError::UnsupportedSchema {
468 found: update.schema_version,
469 });
470 }
471 if update.protocol_version != TELEMETRY_PROTOCOL_VERSION {
472 return Err(TelemetryError::UnsupportedProtocol {
473 found: update.protocol_version,
474 });
475 }
476 validate_metadata(
477 update.state,
478 update.active_tool_count,
479 update.tool_name.as_deref(),
480 )
481}
482
483fn validate_metadata(
484 state: TelemetryState,
485 count: Option<u8>,
486 name: Option<&str>,
487) -> Result<(), TelemetryError> {
488 if state != TelemetryState::ToolRunning && (count.is_some() || name.is_some()) {
489 return Err(TelemetryError::InvalidMetadata(
490 "tool metadata is allowed only for tool_running",
491 ));
492 }
493 if let Some(count) = count {
494 if !(1..=32).contains(&count) {
495 return Err(TelemetryError::InvalidMetadata(
496 "active_tool_count must be between 1 and 32",
497 ));
498 }
499 }
500 if let Some(name) = name {
501 if count != Some(1) {
502 return Err(TelemetryError::InvalidMetadata(
503 "tool_name requires active_tool_count=1",
504 ));
505 }
506 if !valid_tool_name(name) {
507 return Err(TelemetryError::InvalidMetadata(
508 "tool_name must match ^[A-Za-z0-9_.:-]{1,64}$",
509 ));
510 }
511 }
512 Ok(())
513}
514
515fn valid_tool_name(name: &str) -> bool {
516 (1..=64).contains(&name.len())
517 && name
518 .bytes()
519 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b':' | b'-'))
520}
521
522fn valid_stored_shape(sample: &StoredTelemetrySample, paths: &RunPaths, node_id: &NodeId) -> bool {
523 sample.schema_version == TELEMETRY_SCHEMA_VERSION
524 && sample.protocol_version == TELEMETRY_PROTOCOL_VERSION
525 && sample.run_id == paths.run_id
526 && sample.node_id == *node_id
527 && sample
528 .received_at
529 .checked_add(SignedDuration::from_secs(TELEMETRY_FRESHNESS_SECS))
530 .is_ok_and(|expected| sample.expires_at == expected)
531 && validate_metadata(
532 sample.state,
533 sample.active_tool_count,
534 sample.tool_name.as_deref(),
535 )
536 .is_ok()
537}
538
539fn ensure_size(what: &'static str, bytes: usize) -> Result<(), TelemetryError> {
540 if bytes <= TELEMETRY_MAX_BYTES {
541 Ok(())
542 } else {
543 Err(TelemetryError::TooLarge { what, bytes })
544 }
545}
546
547fn projected_node_ids(paths: &RunPaths) -> Result<Vec<NodeId>, Error> {
548 paths.guard_root()?;
549 let dir = paths.nodes_dir();
550 reject_symlink(&dir, || Error::SymlinkSubdir {
551 name: "nodes",
552 path: dir.clone(),
553 })?;
554 let entries = match std::fs::read_dir(&dir) {
555 Ok(entries) => entries,
556 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
557 Err(error) => return Err(Error::io(&dir, error)),
558 };
559 let mut ids = Vec::new();
560 for entry in entries {
561 let entry = entry.map_err(|error| Error::io(&dir, error))?;
562 let path = entry.path();
563 if path.extension().and_then(|value| value.to_str()) != Some("json") {
564 continue;
565 }
566 let Some(stem) = path.file_stem().and_then(|value| value.to_str()) else {
567 continue;
568 };
569 if let Ok(node_id) = NodeId::parse_str(stem) {
570 ids.push(node_id);
571 }
572 }
573 ids.sort_by(|left, right| left.as_str().cmp(right.as_str()));
574 Ok(ids)
575}
576
577fn checked_telemetry_file(paths: &RunPaths, node_id: &NodeId) -> Result<PathBuf, Error> {
578 paths.guard_root()?;
579 let dir = paths.root.join("telemetry");
580 reject_symlink(&dir, || Error::SymlinkSubdir {
581 name: "telemetry",
582 path: dir.clone(),
583 })?;
584 let path = dir.join(format!("{}.json", node_id.as_str()));
585 reject_symlink(&path, || Error::SymlinkStateFile {
586 name: "telemetry",
587 path: path.clone(),
588 })?;
589 Ok(path)
590}
591
592enum StoredRead {
593 Absent,
594 Corrupt,
595 Valid(StoredTelemetrySample),
596}
597
598fn read_stored(path: &Path) -> Result<StoredRead, Error> {
599 let mut options = std::fs::OpenOptions::new();
600 options.read(true);
601 nofollow(&mut options);
602 let mut file = match options.open(path) {
603 Ok(file) => file,
604 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
605 return Ok(StoredRead::Absent)
606 }
607 Err(error) => return Err(Error::io(path, error)),
608 };
609 let mut bytes = Vec::new();
610 file.by_ref()
611 .take((TELEMETRY_MAX_BYTES + 1) as u64)
612 .read_to_end(&mut bytes)
613 .map_err(|error| Error::io(path, error))?;
614 if bytes.len() > TELEMETRY_MAX_BYTES {
615 return Ok(StoredRead::Corrupt);
616 }
617 Ok(match serde_json::from_slice(&bytes) {
618 Ok(sample) => StoredRead::Valid(sample),
619 Err(_) => StoredRead::Corrupt,
620 })
621}