Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

telemetry: dedupe persistent-agent failures per hour, mark SDK test runs synthetic, cause word for failed agent runs (CUA-1918, CUA-1919) (#5554)

Francesco Bonacci4d959bbfa57f
diff --git a/libs/cua/crates/cua-sdk/src/native/agents.rs b/libs/cua/crates/cua-sdk/src/native/agents.rs
index a383f1fe44..f7e313fdcf 100644
--- a/libs/cua/crates/cua-sdk/src/native/agents.rs
+++ b/libs/cua/crates/cua-sdk/src/native/agents.rs
@@ -411,7 +411,7 @@ fn observe(info: &ca::RunInfo) {
if let Some((outcome, variant)) = cua_telemetry::events::agent_run_end(
info.status.as_str(),
info.stop_reason.as_deref(),
- info.error.is_some(),
+ info.error.as_deref(),
) {
cua_telemetry::global().agent_run_finished(&info.run_id, outcome, variant);
}
diff --git a/libs/cua/crates/cua-spaces/src/agents/mod.rs b/libs/cua/crates/cua-spaces/src/agents/mod.rs
index 0a42d47433..fed52ac3ce 100644
--- a/libs/cua/crates/cua-spaces/src/agents/mod.rs
+++ b/libs/cua/crates/cua-spaces/src/agents/mod.rs
@@ -112,7 +112,7 @@ pub mod telemetry {
if let Some((outcome, variant)) = cua_telemetry::events::agent_run_end(
info.status.as_str(),
info.stop_reason.as_deref(),
- info.error.is_some(),
+ info.error.as_deref(),
) {
cua_telemetry::global().agent_run_finished(&info.run_id, outcome, variant);
}
diff --git a/libs/cua/crates/cua-telemetry/src/client.rs b/libs/cua/crates/cua-telemetry/src/client.rs
index f3922df9c9..d800c5d48f 100644
--- a/libs/cua/crates/cua-telemetry/src/client.rs
+++ b/libs/cua/crates/cua-telemetry/src/client.rs
@@ -42,6 +42,7 @@ const SPOOL_FILE: &str = "spool.jsonl";
const LAST_FILE: &str = "last_events.jsonl";
const FIRST_RUN_FILE: &str = "first_run_recorded";
const FUNNEL_DIR: &str = "funnel";
+const HOURLY_DIR: &str = "hourly";
/// The UTC day (days since the epoch) `cua_app_active` was last sent.
const ACTIVE_DAY_FILE: &str = "active_day";
/// The UTC day of the last `cua_agent_used_space`.
@@ -595,7 +596,9 @@ impl Telemetry {
self.env(config::ENV_SYNTHETIC)
.as_deref()
.and_then(config::parse_bool)
- .unwrap_or(false),
+ .unwrap_or_else(|| {
+ self.product().starts_with("sdk_") && config::is_test_run(&|k| self.env(k))
+ }),
),
);
put(
@@ -654,11 +657,44 @@ impl Telemetry {
self.show_notice_if_needed();
return Captured::NoticePending;
}
+ if self.repeated_within_hour(&event) {
+ return Captured::AlreadyRecorded;
+ }
self.record_first_run();
self.identify_if_needed();
self.capture_inner(event)
}
+ /// A failing persistent agent (a resume retried every few seconds sent
+ /// 86,000 events in a week) reports each distinct failure at most once
+ /// per install per hour. The marker is the file's modified time.
+ fn repeated_within_hour(&self, event: &Event) -> bool {
+ if event.name != schema::event::PERSISTENT_AGENT
+ || event.props.get("outcome").and_then(Value::as_str) != Some("error")
+ {
+ return false;
+ }
+ let Some(dir) = self.state_dir() else {
+ return false;
+ };
+ let key: String = ["action", "harness", "error_kind"]
+ .iter()
+ .map(|k| event.props.get(*k).and_then(Value::as_str).unwrap_or("-"))
+ .collect::<Vec<_>>()
+ .join("_");
+ let marker = dir.join(HOURLY_DIR).join(format!("{}_{key}", event.name));
+ let fresh = std::fs::metadata(&marker)
+ .and_then(|m| m.modified())
+ .ok()
+ .and_then(|t| SystemTime::now().duration_since(t).ok())
+ .is_some_and(|age| age < Duration::from_secs(3600));
+ if fresh {
+ return true;
+ }
+ let _ = fsutil::write_replace(&marker, b"1\n");
+ false
+ }
+
fn capture_inner(&self, event: Event) -> Captured {
let Some(spec) = schema::spec(event.name) else {
return Captured::Invalid(format!("unknown event {}", event.name));
diff --git a/libs/cua/crates/cua-telemetry/src/config.rs b/libs/cua/crates/cua-telemetry/src/config.rs
index 3b0d5ced6e..199d8ab103 100644
--- a/libs/cua/crates/cua-telemetry/src/config.rs
+++ b/libs/cua/crates/cua-telemetry/src/config.rs
@@ -156,6 +156,19 @@ pub fn is_ci(env: Env<'_>) -> bool {
})
}
+/// Whether this process is a test run: pytest, vitest, jest, a Node test
+/// environment or `cargo test`. SDK processes under a test harness are
+/// marked synthetic so reports leave them out.
+pub fn is_test_run(env: Env<'_>) -> bool {
+ let set = |v: &str| env(v).is_some_and(|s| !s.trim().is_empty());
+ set("PYTEST_CURRENT_TEST")
+ || set("PYTEST_VERSION")
+ || set("VITEST")
+ || set("JEST_WORKER_ID")
+ || set("RUST_TEST_THREADS")
+ || env("NODE_ENV").is_some_and(|s| s.trim().eq_ignore_ascii_case("test"))
+}
+
/// The cua home: `$CUA_HOME`, else `~/.cua`.
pub fn cua_home(env: Env<'_>) -> Option<PathBuf> {
if let Some(h) = env("CUA_HOME").filter(|h| !h.trim().is_empty()) {
diff --git a/libs/cua/crates/cua-telemetry/src/events.rs b/libs/cua/crates/cua-telemetry/src/events.rs
index b07f9a5fad..71debfd068 100644
--- a/libs/cua/crates/cua-telemetry/src/events.rs
+++ b/libs/cua/crates/cua-telemetry/src/events.rs
@@ -725,21 +725,65 @@ pub fn agent_run_completed(
.s("duration_bucket", duration_bucket(elapsed))
}
+/// A fixed cause word for a failed agent run, chosen from its recorded
+/// error text: `no_api_key`, `provider_error`, `timeout`, `user_cancelled`,
+/// else `AgentFailed`. The text is only matched, never kept or sent.
+pub fn agent_failure_cause(error: Option<&str>) -> &'static str {
+ let t = error.unwrap_or_default().to_ascii_lowercase();
+ let has = |words: &[&str]| words.iter().any(|w| t.contains(w));
+ if has(&["cancelled", "canceled", "interrupted by user"]) {
+ "user_cancelled"
+ } else if has(&["timed out", "timeout", "deadline"]) {
+ "timeout"
+ } else if has(&[
+ "api key",
+ "api_key",
+ "apikey",
+ "credential",
+ "unauthorized",
+ "authentication",
+ "401",
+ "403",
+ "not logged in",
+ "login required",
+ ]) {
+ "no_api_key"
+ } else if has(&[
+ "rate limit",
+ "429",
+ "overloaded",
+ "quota",
+ "provider",
+ "500",
+ "502",
+ "503",
+ "504",
+ "service unavailable",
+ ]) {
+ "provider_error"
+ } else {
+ "AgentFailed"
+ }
+}
+
/// How an agent run ended, from its published status (`cua_agents`
-/// `RunStatus::as_str`), the ACP stop reason of its last turn and whether
-/// it recorded an error. None while it still runs (or cannot be read).
+/// `RunStatus::as_str`), the ACP stop reason of its last turn and its
+/// recorded error text (only classified into a cause word). None while it
+/// still runs (or cannot be read).
pub fn agent_run_end(
status: &str,
stop_reason: Option<&str>,
- recorded_error: bool,
+ recorded_error: Option<&str>,
) -> Option<(Outcome, Option<&'static str>)> {
match status.trim() {
"idle" if stop_reason.is_some_and(|r| r.trim() == "cancelled") => {
Some((Outcome::Cancelled, None))
}
- "idle" if recorded_error => Some((Outcome::Error, Some("AgentFailed"))),
+ "idle" if recorded_error.is_some() => {
+ Some((Outcome::Error, Some(agent_failure_cause(recorded_error))))
+ }
"idle" => Some((Outcome::Ok, None)),
- "failed" => Some((Outcome::Error, Some("AgentFailed"))),
+ "failed" => Some((Outcome::Error, Some(agent_failure_cause(recorded_error)))),
"crashed" => Some((Outcome::Error, Some("AgentCrashed"))),
_ => None,
}
diff --git a/libs/cua/crates/cua-telemetry/src/schema.rs b/libs/cua/crates/cua-telemetry/src/schema.rs
index 5bf3634f4d..176923ca04 100644
--- a/libs/cua/crates/cua-telemetry/src/schema.rs
+++ b/libs/cua/crates/cua-telemetry/src/schema.rs
@@ -185,6 +185,12 @@ pub const ERROR_KINDS: &[&str] = &[
"agent",
"agent_failed",
"agent_crashed",
+ // Why an agent run failed or stopped, a fixed word chosen on device
+ // from the run's recorded error (never the text itself).
+ "no_api_key",
+ "provider_error",
+ "timeout",
+ "user_cancelled",
"other",
];
pub const DURATIONS: &[&str] = &[
diff --git a/libs/cua/crates/cua-telemetry/tests/privacy.rs b/libs/cua/crates/cua-telemetry/tests/privacy.rs
index c4f3f5e4ee..638d063b87 100644
--- a/libs/cua/crates/cua-telemetry/tests/privacy.rs
+++ b/libs/cua/crates/cua-telemetry/tests/privacy.rs
@@ -1459,25 +1459,37 @@ fn agent_runs_respect_every_opt_out_and_never_count_inside_a_run() {
#[test]
fn agent_run_end_follows_the_published_status() {
- assert_eq!(events::agent_run_end("running", None, false), None);
- assert_eq!(events::agent_run_end("unknown", None, false), None);
+ assert_eq!(events::agent_run_end("running", None, None), None);
+ assert_eq!(events::agent_run_end("unknown", None, None), None);
assert_eq!(
- events::agent_run_end("idle", Some("end_turn"), false),
+ events::agent_run_end("idle", Some("end_turn"), None),
Some((Outcome::Ok, None))
);
assert_eq!(
- events::agent_run_end("idle", Some("cancelled"), false),
+ events::agent_run_end("idle", Some("cancelled"), None),
Some((Outcome::Cancelled, None))
);
assert_eq!(
- events::agent_run_end("failed", None, true),
+ events::agent_run_end("failed", None, Some("boom")),
Some((Outcome::Error, Some("AgentFailed")))
);
assert_eq!(
- events::agent_run_end("crashed", None, false),
+ events::agent_run_end("crashed", None, None),
Some((Outcome::Error, Some("AgentCrashed")))
);
assert_eq!(events::error_kind("AgentFailed"), "agent_failed");
+ let cause = |t| {
+ events::agent_run_end("failed", None, Some(t))
+ .unwrap()
+ .1
+ .unwrap()
+ };
+ assert_eq!(cause("ANTHROPIC_API_KEY is not set"), "no_api_key");
+ assert_eq!(cause("429 rate limit from provider"), "provider_error");
+ assert_eq!(cause("request timed out"), "timeout");
+ assert_eq!(cause("cancelled by user"), "user_cancelled");
+ assert_eq!(cause("something else"), "AgentFailed");
+ assert_eq!(events::error_kind("no_api_key"), "no_api_key");
assert_eq!(events::error_kind("Agent"), "agent");
}
@@ -1616,3 +1628,64 @@ fn space_tool_groups_cover_the_tools_that_act_inside_a_space() {
assert_eq!(g(admin), None, "{admin}");
}
}
+
+#[test]
+fn a_repeating_persistent_agent_failure_is_sent_once_per_hour() {
+ let h = tempfile::tempdir().unwrap();
+ let daemon = |home: &Path| {
+ let sink = Arc::new(MemorySink::new());
+ let t = Telemetry::builder()
+ .env(env_of(&[]))
+ .home(home)
+ .sink(sink.clone())
+ .product("daemon", "1.2.3")
+ .foreground()
+ .build();
+ t.acknowledge_notice();
+ (t, sink)
+ };
+ let (t, sink) = daemon(h.path());
+ let resume =
+ || events::persistent_agent("resume", None, Outcome::Error, Some("other")).unwrap();
+ assert_eq!(t.capture(resume()), Captured::Queued);
+ assert_eq!(t.capture(resume()), Captured::AlreadyRecorded);
+ // Another process of the same install is held back too.
+ let (t2, _s2) = daemon(h.path());
+ assert_eq!(t2.capture(resume()), Captured::AlreadyRecorded);
+ // A different failure, and successes, still go through.
+ let pause = events::persistent_agent("pause", None, Outcome::Error, Some("other")).unwrap();
+ assert_eq!(t.capture(pause), Captured::Queued);
+ let ok = events::persistent_agent("resume", None, Outcome::Ok, None).unwrap();
+ assert_eq!(t.capture(ok.clone()), Captured::Queued);
+ assert_eq!(t.capture(ok), Captured::Queued);
+ t.flush(Duration::from_secs(1));
+ let sent = sink
+ .events()
+ .iter()
+ .filter(|e| e["event"] == "cua_persistent_agent")
+ .count();
+ assert_eq!(sent, 4);
+}
+
+#[test]
+fn sdk_test_runs_are_marked_synthetic() {
+ let synthetic = |product: &str, env: &[(&str, &str)]| {
+ let h = tempfile::tempdir().unwrap();
+ let t = Telemetry::builder()
+ .env(env_of(env))
+ .home(h.path())
+ .sink(Arc::new(MemorySink::new()))
+ .product(product, "1.2.3")
+ .foreground()
+ .build();
+ t.envelope_preview()["is_synthetic"].as_bool().unwrap()
+ };
+ assert!(synthetic(
+ "sdk_python",
+ &[("PYTEST_CURRENT_TEST", "t.py::x")]
+ ));
+ assert!(synthetic("sdk_typescript", &[("VITEST", "true")]));
+ assert!(!synthetic("sdk_python", &[]));
+ assert!(!synthetic("cli", &[("PYTEST_CURRENT_TEST", "t.py::x")]));
+ assert!(synthetic("cli", &[("CUA_TELEMETRY_SYNTHETIC", "1")]));
+}