Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

stop the telemetry post from blocking the first frame (#3327)

ktbc57309434ab
diff --git a/AGENTS.md b/AGENTS.md
index 3509f02c75..528d5ee61e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -83,6 +83,43 @@ Every contributor (human or agent) must read this before working on this repo.
- Explain lint exceptions next to the `#[allow(...)]` or workspace configuration; keep
exceptions narrow. Advisory ignores in `deny.toml` need a reason and review date.
+## Performance and the critical path
+
+The UI critical path is paint-latency-critical. First paint, and every
+frame the user waits on, must never block on network, disk sync, or
+background bookkeeping. The launch benchmarks measure this surface
+(cold/warm ready, first paint); a merge that regresses them undoes the
+product's core claim.
+
+Rules:
+
+- Nothing user-visible awaits the network. Any HTTP/socket call on a
+ render path (telemetry, catalog fetch, update check) runs on a
+ background worker; the paint path hands the work off and returns
+ immediately. Delivery semantics (timeout, retry, ordering) live with
+ the worker, not the caller.
+- Telemetry is fire-and-forget from user-facing code. `pa-telemetry`'s
+ background worker owns delivery end to end; no startup, session
+ create, tab open, or first-render path may hold a flush or await a
+ sink.
+- Fire-and-forget boundaries need a red-first test: a hanging sink
+ (one that never replies) must not delay paint. The test fails if any
+ await on the critical path reaches the worker's delivery.
+- Tests that mock a sink or run offline cannot prove the above (the
+ benchmark's mock hides the POST). The regression test with a hanging
+ sink is the required verifier.
+
+Example (the #3288 regression this rule exists to prevent): the
+telemetry startup flush was awaited on the interactive launch path, so
+the analytics POST — a real HTTPS round-trip, ~157 ms — ran before the
+first frame. Every CI check passed because tests set DO_NOT_TRACK=1 and
+the benchmark mocked the provider offline; only real-network launches
+paid the cost. The fix moved the flush to the background worker and
+added `the_startup_flush_never_blocks_the_first_frame` (a hanging sink
+must not delay paint) as the permanent guard. Any change touching the
+launch path must keep that test red-first.
+
+
## Merge gates
- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
@@ -115,7 +152,8 @@ Every contributor (human or agent) must read this before working on this repo.
Every user-visible feature ships its adoption telemetry event in the same PR as the feature:
the event name + properties join the versioned schema (`pa-telemetry`), and a
seam emits it from day one. Telemetry properties never carry prompt, session, or file content
-(primitives only; see `pa-telemetry`).
+(primitives only; see `pa-telemetry`); delivery is fire-and-forget from user-facing code
+(see Performance and the critical path).
## Branding
diff --git a/crates/pa-cli/src/interactive_mode.rs b/crates/pa-cli/src/interactive_mode.rs
index 7b112418e6..650c74c24a 100644
--- a/crates/pa-cli/src/interactive_mode.rs
+++ b/crates/pa-cli/src/interactive_mode.rs
@@ -90,7 +90,7 @@ pub fn run_interactive_mode(options: &RunOptions) -> Result<i32> {
} else {
"cold"
};
- let startup_telemetry = (!options.config.telemetry_disabled).then(|| {
+ let mut startup_telemetry = (!options.config.telemetry_disabled).then(|| {
let agent_dir = options.config.agent_dir.clone();
let settings =
pa_core::settings::SettingsManager::create(&options.config.cwd, &agent_dir);
@@ -137,9 +137,10 @@ pub fn run_interactive_mode(options: &RunOptions) -> Result<i32> {
}
// `startup` (schema v1): process entry to a ready interactive
// session environment (daemon listening). Emitted through a
- // one-shot client that flushes immediately; the session's own
- // telemetry rides the daemon worker.
- if let Some(client) = startup_telemetry.as_ref() {
+ // one-shot client; the session's own telemetry rides the daemon
+ // worker. The flush handle rides to the end of the run — the
+ // quick-exit join below bounds delivery on a fast quit.
+ let startup_flush = startup_telemetry.take().map(|client| {
let daemon_ready_ms = startup_started.elapsed().as_millis() as u64;
let mut properties = pa_telemetry::base_properties("interactive");
properties.set("duration_ms", serde_json::Value::from(daemon_ready_ms));
@@ -154,9 +155,9 @@ pub fn run_interactive_mode(options: &RunOptions) -> Result<i32> {
startup_kind: Some(startup_kind),
timing_scope: Some("system_work"),
}
- .track(client);
- let _ = client.shutdown().await;
- }
+ .track(&client);
+ flush_startup_telemetry(client)
+ });
// `prime-agent agents` and bare `--resume` open the agents view
// (TS `agentsViewRequested`); the view then opens sessions, and a
// session exits back into the view until the user exits it. TS gates
@@ -172,29 +173,52 @@ pub fn run_interactive_mode(options: &RunOptions) -> Result<i32> {
tui_options.onboarding.is_some(),
continue_view.is_some(),
);
- if agents_view {
- let (anchor, notice) = continue_view.map_or((None, None), |view| {
- (Some(view.session_id), Some(view.notice))
- });
- run_agents_view_flow(tui_options, anchor, notice).await
- } else {
- let outcome =
- pa_tui::interactive::run_interactive(tui_options.clone(), UiMode::Terminal).await?;
- // TS `main.ts`: a direct session run closes into the agents view
- // when the exit came through agents-back or `/resume`
- // (`launchAgentsView` anchored on the session just left); every
- // other exit (ctrl+c/ctrl+d, `/quit`) ends the process.
- if outcome.return_to_agents_view {
- // A startup attach that fell back to the view has no session
- // identity to anchor on; its notice seeds the view's status
- // line instead.
- let anchor = (!outcome.session_id.is_empty()).then(|| outcome.session_id.clone());
- run_agents_view_flow(tui_options, anchor, outcome.agents_view_notice).await
+ // The interactive dispatch, one future so EVERY exit — the view
+ // loop's, the session run's, a failed open's error return —
+ // passes the quick-exit join below.
+ let run = async {
+ if agents_view {
+ let (anchor, notice) = continue_view.map_or((None, None), |view| {
+ (Some(view.session_id), Some(view.notice))
+ });
+ run_agents_view_flow(tui_options, anchor, notice).await
} else {
- print_resume_hint(outcome.resume_hint.as_deref());
- Ok(())
+ let outcome =
+ pa_tui::interactive::run_interactive(tui_options.clone(), UiMode::Terminal)
+ .await?;
+ // TS `main.ts`: a direct session run closes into the agents view
+ // when the exit came through agents-back or `/resume`
+ // (`launchAgentsView` anchored on the session just left); every
+ // other exit (ctrl+c/ctrl+d, `/quit`) ends the process.
+ if outcome.return_to_agents_view {
+ // A startup attach that fell back to the view has no session
+ // identity to anchor on; its notice seeds the view's status
+ // line instead.
+ let anchor =
+ (!outcome.session_id.is_empty()).then(|| outcome.session_id.clone());
+ run_agents_view_flow(tui_options, anchor, outcome.agents_view_notice).await
+ } else {
+ print_resume_hint(outcome.resume_hint.as_deref());
+ Ok(())
+ }
}
+ };
+ let result = run.await;
+ // The quick-exit join: the runtime that owns the handed-off drain
+ // dies with this block, so a run that ends inside the delivery
+ // window (a fast quit — the sink allows up to 1.5s) would lose
+ // the startup events to the teardown. The same shared exit bound
+ // `tui exit` and the agents-view exit report already join under
+ // applies here: the drain delivers (typical ~150ms) or drops,
+ // bounded — never cut mid-POST.
+ if let Some(flush) = startup_flush {
+ let _ = tokio::time::timeout(
+ Duration::from_millis(pa_tui::interactive::TELEMETRY_EXIT_TIMEOUT_MS),
+ flush,
+ )
+ .await;
}
+ result
})?;
// tmux (verified on 3.2a) can drop the pane's final output when the
// process dies immediately after writing it: the just-printed resume
@@ -208,6 +232,26 @@ pub fn run_interactive_mode(options: &RunOptions) -> Result<i32> {
Ok(0)
}
+/// The one-shot startup client's final flush, handed to the runtime:
+/// fire-and-forget from the paint path's perspective — the tracked
+/// `startup` events' delivery belongs to the background worker (the
+/// sink's bounded request timeout; a re-sent batch keeps its event ids,
+/// so the backend dedupes), never to the first frame. The returned
+/// handle is the quick-exit seam: the composition root joins it under
+/// the shared exit bound when the run ends inside the delivery window,
+/// so a fast quit delivers (or drops, bounded) instead of the runtime
+/// teardown cutting the worker mid-POST.
+/// `the_startup_flush_never_blocks_the_first_frame` guards the boundary
+/// with a hanging sink: the flush hand-off must complete while delivery
+/// is still blocked.
+pub(super) fn flush_startup_telemetry(
+ client: pa_telemetry::TelemetryClient,
+) -> tokio::task::JoinHandle<()> {
+ tokio::spawn(async move {
+ let _ = client.shutdown().await;
+ })
+}
+
/// TS `shutdown` prints the dim resume hint (`formatResumeHint`) to stdout
/// after the TUI is restored; agents-view returns suppress it. Dim is the
/// TS `chalk.dim` styling (`ESC[2m` ... `ESC[22m`). The print is the last
diff --git a/crates/pa-cli/src/interactive_mode/tests.rs b/crates/pa-cli/src/interactive_mode/tests.rs
index 2624ace0e8..d44d33eab8 100644
--- a/crates/pa-cli/src/interactive_mode/tests.rs
+++ b/crates/pa-cli/src/interactive_mode/tests.rs
@@ -904,3 +904,190 @@ fn a_fork_launch_never_opens_the_agents_view() {
"a --continue with a saved candidate still opens the view"
);
}
+
+/// A sink whose `send_batch` hangs until the test releases it: the
+/// stand-in for the analytics POST's network round-trip (the same
+/// delivery contract the production sink carries, minus its own
+/// timeout — the point is that delivery takes longer than the paint).
+#[derive(Default)]
+struct GatedSink {
+ /// Send entry: `notify_one` when a batch reaches the sink; a
+ /// stored permit keeps the entry wait race-free in both orders.
+ entered_notify: tokio::sync::Notify,
+ /// The delivered batches' event names (delivery finished).
+ delivered: std::sync::Mutex<Vec<String>>,
+ /// The release flag the hanging send waits on.
+ released: std::sync::atomic::AtomicBool,
+ /// The hang gate's waker: `notify_waiters` on release, no
+ /// permits — a stale permit would unhang the sink before the
+ /// test releases it.
+ notify: tokio::sync::Notify,
+ /// Delivery completion: `notify_one` stores a permit when no
+ /// waiter is registered yet, so the completion future is
+ /// race-free in both orders and can be awaited directly.
+ delivered_notify: tokio::sync::Notify,
+}
+
+impl GatedSink {
+ fn release(&self) {
+ self.released
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ self.notify.notify_waiters();
+ }
+
+ fn delivered_names(&self) -> Vec<String> {
+ self.delivered.lock().expect("gate lock").clone()
+ }
+
+ /// The first send's entry future.
+ fn wait_until_entered(&self) -> impl std::future::Future<Output = ()> + '_ {
+ self.entered_notify.notified()
+ }
+
+ /// The first delivery's completion future.
+ fn wait_until_delivered(&self) -> impl std::future::Future<Output = ()> + '_ {
+ self.delivered_notify.notified()
+ }
+}
+
+impl pa_telemetry::TelemetrySink for GatedSink {
+ fn send_batch<'a>(
+ &'a self,
+ _install_id: &'a str,
+ events: Vec<pa_telemetry::TelemetryEvent>,
+ ) -> std::pin::Pin<Box<dyn std::future::Future<Output = pa_telemetry::SinkOutcome> + Send + 'a>>
+ {
+ Box::pin(async move {
+ self.entered_notify.notify_one();
+ // Race-free wait, tokio's documented pattern: the waiter
+ // registers (or consumes a permit) BEFORE the flag check, so
+ // a release that fires between the check and the await is
+ // never lost — a naive `while !flag { notified().await }` can
+ // miss `notify_waiters` and hang.
+ let notified = self.notify.notified();
+ tokio::pin!(notified);
+ loop {
+ notified.as_mut().enable();
+ if self.released.load(std::sync::atomic::Ordering::SeqCst) {
+ break;
+ }
+ notified.as_mut().await;
+ notified.set(self.notify.notified());
+ }
+ let mut delivered = self.delivered.lock().expect("gate lock");
+ for event in &events {
+ delivered.push(event.name.clone());
+ }
+ self.delivered_notify.notify_one();
+ pa_telemetry::SinkOutcome::Sent
+ })
+ }
+}
+
+/// The interactive startup flush is fire-and-forget from the paint
+/// path's perspective: the first frame must never await the tracked
+/// `startup` events' delivery. The gated sink stands in for the
+/// analytics POST's network round-trip: the flush hand-off must
+/// complete while delivery still hangs, and the released drain must
+/// still deliver the tracked events.
+#[test]
+fn the_startup_flush_never_blocks_the_first_frame() {
+ tokio::runtime::Runtime::new()
+ .expect("runtime")
+ .block_on(startup_flush_never_blocks_the_first_frame());
+}
+
+async fn startup_flush_never_blocks_the_first_frame() {
+ let sink = std::sync::Arc::new(GatedSink::default());
+ let mut config = pa_telemetry::TelemetryClientConfig::new("install-1");
+ config.batch_size = 20;
+ config.flush_interval = std::time::Duration::from_mins(10);
+ config.sinks = vec![sink.clone() as std::sync::Arc<dyn pa_telemetry::TelemetrySink>];
+ let client = pa_telemetry::TelemetryClient::spawn(config).expect("startup client");
+
+ // The composition root's startup tracks: the event and the ui_ready
+ // stage on the one-shot client.
+ let mut properties = pa_telemetry::base_properties("interactive");
+ properties.set("duration_ms", serde_json::Value::from(1));
+ client.track("startup", properties);
+ pa_telemetry::AgentStartupStage {
+ stage: "ui_ready",
+ outcome: "completed",
+ duration_ms: Some(1),
+ startup_kind: Some("cold"),
+ timing_scope: Some("system_work"),
+ }
+ .track(&client);
+
+ // The paint path's contract, run as its own task so a regression
+ // back to a blocking flush reds the timeout instead of wedging the
+ // suite (an inner assert failure reds through the join error).
+ let hand_off = tokio::time::timeout(
+ std::time::Duration::from_secs(2),
+ tokio::spawn(async move {
+ // The hand-off: while the sink still hangs, it must already
+ // be done — the first frame paints with delivery pending.
+ let flush = flush_startup_telemetry(client);
+ // The batch must have entered the sink before the boundary
+ // is meaningful: a release that beats the send's entry
+ // drains without ever hanging, and the hand-off below would
+ // pass vacuously. The entry deadline sits under the outer
+ // hand-off bound, so a sink that never starts reports
+ // here, not as a blocked paint path.
+ let entered = tokio::time::timeout(
+ std::time::Duration::from_millis(500),
+ sink.wait_until_entered(),
+ )
+ .await;
+ assert!(
+ entered.is_ok(),
+ "the tracked startup batch entered the gated sink"
+ );
+ assert!(
+ sink.delivered_names().is_empty(),
+ "delivery was still pending when the paint path proceeded"
+ );
+
+ // The released drain still delivers the tracked startup
+ // events: completion is awaited on the sink's own notify,
+ // the timeout only bounds failure — no polling loop.
+ sink.release();
+ let delivered = tokio::time::timeout(
+ std::time::Duration::from_secs(1),
+ sink.wait_until_delivered(),
+ )
+ .await;
+ assert!(
+ delivered.is_ok(),
+ "the released drain delivered the tracked startup events"
+ );
+ let names = sink.delivered_names();
+ assert!(
+ names.contains(&"startup".to_string()),
+ "the startup event delivered: {names:?}"
+ );
+ assert!(
+ names.contains(&"agent startup stage".to_string()),
+ "the ui_ready stage delivered: {names:?}"
+ );
+
+ // The quick-exit seam: the composition root joins this
+ // handle under the shared exit bound when a run ends inside
+ // the delivery window — the join settles with the drain, so
+ // the events never die with the runtime teardown.
+ let joined = tokio::time::timeout(std::time::Duration::from_millis(500), flush).await;
+ assert!(
+ matches!(joined, Ok(Ok(()))),
+ "the exit join settled once the drain delivered"
+ );
+ }),
+ )
+ .await;
+ match hand_off {
+ Ok(Ok(())) => {}
+ Ok(Err(joined)) => panic!("the first-paint contract task panicked: {joined}"),
+ Err(elapsed) => panic!(
+ "the flush hand-off completed while the sink still hung (the paint path never waits out delivery): {elapsed}"
+ ),
+ }
+}