a2a-protocol-server 0.9.0

Agent2Agent (A2A) protocol v1.0 — server framework (hyper-backed)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Tom F. <tomf@tomtomtech.net> (https://github.com/tomtom215)

//! Tests for the OpenTelemetry metrics exporter.
//!
//! Split from `mod.rs` to keep the exporter itself readable.
//!
//! Two layers, because neither alone is sufficient:
//!
//! * Noop-meter tests prove the instruments exist and accept the labels the
//!   call sites pass. They cannot prove a value leaves the process.
//! * `scripts/check_otel_metrics_coverage.py` proves every `Metrics` callback
//!   is *present* in the impl, catching the one a defaulted trait method would
//!   silently swallow. It cannot prove the body does anything.
//! * Real-meter tests (bottom of this file) collect from a `ManualReader` and
//!   assert the counter moved.
//!
//! The third layer exists because mutation testing showed the first two miss
//! the same thing: replacing the bodies of `on_persistence_error` and
//! `on_push_delivery` with `()` left every other test in the workspace green.
//! A present-but-empty method satisfies a structural check by construction.

use super::super::*;
use std::time::Duration;

/// Creates an `OtelMetrics` backed by a noop meter (no collector needed).
fn noop_otel_metrics() -> OtelMetrics {
    let meter = opentelemetry::global::meter("test");
    OtelMetrics::from_meter(&meter)
}

#[test]
fn from_meter_creates_all_instruments() {
    let metrics = noop_otel_metrics();
    let debug = format!("{metrics:?}");
    assert!(debug.contains("OtelMetrics"));
}

/// The two failure callbacks reach the exporter's instruments.
///
/// A noop meter cannot prove the values leave the process, so the real
/// guard against this exporter ignoring a callback is
/// `scripts/check_otel_metrics_coverage.py`. This covers the other half:
/// that the instruments exist and accept the labels the call sites pass.
#[test]
fn failure_callbacks_reach_their_instruments() {
    let metrics = noop_otel_metrics();
    metrics.on_persistence_error(
        crate::metrics::persistence_operation::ARTIFACT_APPEND,
        "internal_error",
    );
    metrics.on_persistence_error(
        crate::metrics::persistence_operation::STATUS_UPDATE,
        "internal_error",
    );
    for outcome in [
        crate::metrics::push_outcome::DELIVERED,
        crate::metrics::push_outcome::FAILED,
        crate::metrics::push_outcome::TIMEOUT,
    ] {
        metrics.on_push_delivery(outcome);
    }
}

#[test]
fn on_request_does_not_panic() {
    let metrics = noop_otel_metrics();
    metrics.on_request("message/send");
    metrics.on_request("tasks/get");
}

#[test]
fn on_response_does_not_panic() {
    let metrics = noop_otel_metrics();
    metrics.on_response("message/send");
}

#[test]
fn on_error_does_not_panic() {
    let metrics = noop_otel_metrics();
    metrics.on_error("message/send", "timeout");
    metrics.on_error("tasks/get", "not_found");
}

#[test]
fn on_latency_does_not_panic() {
    let metrics = noop_otel_metrics();
    metrics.on_latency("message/send", Duration::from_millis(42));
    metrics.on_latency("message/send", Duration::from_secs(0));
}

#[test]
fn on_queue_depth_change_does_not_panic() {
    let metrics = noop_otel_metrics();
    metrics.on_queue_depth_change(0);
    metrics.on_queue_depth_change(100);
}

#[test]
fn on_connection_pool_stats_does_not_panic() {
    let metrics = noop_otel_metrics();
    metrics.on_connection_pool_stats(&ConnectionPoolStats {
        active_connections: 5,
        idle_connections: 10,
        total_connections_created: 42,
        connections_closed: 3,
    });
}

// ── Observable-effect tests ─────────────────────────────────────────────

use opentelemetry::metrics::MeterProvider;
use opentelemetry_sdk::metrics::data::{
    AggregatedMetrics, GaugeDataPoint, HistogramDataPoint, MetricData, ResourceMetrics,
    SumDataPoint,
};
use opentelemetry_sdk::metrics::reader::MetricReader;
use opentelemetry_sdk::metrics::{ManualReader, SdkMeterProvider};
use opentelemetry_sdk::Resource;

struct CloneableReader(std::sync::Arc<ManualReader>);

impl std::fmt::Debug for CloneableReader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("CloneableReader")
    }
}

impl Clone for CloneableReader {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl MetricReader for CloneableReader {
    fn register_pipeline(&self, pipeline: std::sync::Weak<opentelemetry_sdk::metrics::Pipeline>) {
        self.0.register_pipeline(pipeline);
    }
    fn collect(&self, rm: &mut ResourceMetrics) -> opentelemetry_sdk::error::OTelSdkResult {
        self.0.collect(rm)
    }
    fn force_flush(&self) -> opentelemetry_sdk::error::OTelSdkResult {
        self.0.force_flush()
    }
    fn shutdown_with_timeout(
        &self,
        timeout: std::time::Duration,
    ) -> opentelemetry_sdk::error::OTelSdkResult {
        self.0.shutdown_with_timeout(timeout)
    }
    fn temporality(
        &self,
        kind: opentelemetry_sdk::metrics::InstrumentKind,
    ) -> opentelemetry_sdk::metrics::Temporality {
        self.0.temporality(kind)
    }
}

fn metrics_with_reader() -> (OtelMetrics, CloneableReader) {
    let reader = CloneableReader(std::sync::Arc::new(ManualReader::default()));
    let provider = SdkMeterProvider::builder()
        .with_reader(reader.clone())
        .with_resource(Resource::builder().build())
        .build();
    let meter = provider.meter("test");
    let metrics = OtelMetrics::from_meter(&meter);
    std::mem::forget(provider);
    (metrics, reader)
}

fn collect_metrics(reader: &CloneableReader) -> ResourceMetrics {
    let mut rm = ResourceMetrics::default();
    reader.collect(&mut rm).expect("collect");
    rm
}

fn find_sum_u64(rm: &ResourceMetrics, name: &str) -> u64 {
    for scope in rm.scope_metrics() {
        for metric in scope.metrics() {
            if metric.name() == name {
                if let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() {
                    return sum.data_points().map(SumDataPoint::value).sum();
                }
            }
        }
    }
    0
}

#[test]
fn on_request_increments_counter() {
    let (metrics, reader) = metrics_with_reader();
    metrics.on_request("test/method");
    let rm = collect_metrics(&reader);
    assert!(
        find_sum_u64(&rm, "a2a.server.requests") > 0,
        "request counter should be incremented"
    );
}

#[test]
fn on_response_increments_counter() {
    let (metrics, reader) = metrics_with_reader();
    metrics.on_response("test/method");
    let rm = collect_metrics(&reader);
    assert!(
        find_sum_u64(&rm, "a2a.server.responses") > 0,
        "response counter should be incremented"
    );
}

#[test]
fn on_error_increments_counter() {
    let (metrics, reader) = metrics_with_reader();
    metrics.on_error("test/method", "timeout");
    let rm = collect_metrics(&reader);
    assert!(
        find_sum_u64(&rm, "a2a.server.errors") > 0,
        "error counter should be incremented"
    );
}

#[test]
fn on_latency_records_histogram() {
    let (metrics, reader) = metrics_with_reader();
    metrics.on_latency("test/method", Duration::from_millis(42));
    let rm = collect_metrics(&reader);

    let mut found = false;
    for scope in rm.scope_metrics() {
        for metric in scope.metrics() {
            if metric.name() == "a2a.server.latency" {
                if let AggregatedMetrics::F64(MetricData::Histogram(hist)) = metric.data() {
                    let count: u64 = hist.data_points().map(HistogramDataPoint::count).sum();
                    assert!(count > 0, "histogram should have recorded a value");
                    found = true;
                }
            }
        }
    }
    assert!(found, "latency histogram metric should exist");
}

#[test]
fn on_queue_depth_records_gauge() {
    let (metrics, reader) = metrics_with_reader();
    metrics.on_queue_depth_change(42);
    let rm = collect_metrics(&reader);

    let mut found = false;
    for scope in rm.scope_metrics() {
        for metric in scope.metrics() {
            if metric.name() == "a2a.server.queue_depth" {
                if let AggregatedMetrics::U64(MetricData::Gauge(gauge)) = metric.data() {
                    let val: u64 = gauge.data_points().map(GaugeDataPoint::value).sum();
                    assert_eq!(val, 42, "gauge should record 42");
                    found = true;
                }
            }
        }
    }
    assert!(found, "queue_depth gauge metric should exist");
}

#[test]
fn on_connection_pool_stats_records_all_instruments() {
    let (metrics, reader) = metrics_with_reader();
    metrics.on_connection_pool_stats(&ConnectionPoolStats {
        active_connections: 5,
        idle_connections: 10,
        total_connections_created: 42,
        connections_closed: 3,
    });
    let rm = collect_metrics(&reader);

    assert!(
        find_sum_u64(&rm, "a2a.server.pool.created") > 0,
        "pool.created counter should be incremented"
    );
    assert!(
        find_sum_u64(&rm, "a2a.server.pool.closed") > 0,
        "pool.closed counter should be incremented"
    );
}

// ── Real-meter assertions ────────────────────────────────────────────────────
//
// Everything above runs against a noop meter, which cannot tell a callback that
// records from one that does nothing. `check_otel_metrics_coverage.py` does not
// close that gap either: it proves the method is *present* in the impl, and a
// present-but-empty body satisfies it.
//
// Mutation testing found exactly that hole — replacing the bodies of
// `on_persistence_error` and `on_push_delivery` with `()` survived the entire
// workspace suite. These tests collect from a real `ManualReader` and assert the
// counter actually moved, which is the only formulation that fails when the
// body is emptied.

// `AggregatedMetrics`, `MetricData`, `ResourceMetrics`, `ManualReader` and
// `SdkMeterProvider` all arrive through the `use super::super::*;` glob above.
use std::sync::Arc;

/// `SdkMeterProvider::with_reader` takes ownership, so the reader is shared
/// through an `Arc` to stay readable after the provider is built.
#[derive(Debug, Clone)]
struct SharedReader(Arc<ManualReader>);

impl opentelemetry_sdk::metrics::reader::MetricReader for SharedReader {
    fn register_pipeline(&self, pipeline: std::sync::Weak<opentelemetry_sdk::metrics::Pipeline>) {
        self.0.register_pipeline(pipeline);
    }
    fn collect(&self, rm: &mut ResourceMetrics) -> opentelemetry_sdk::error::OTelSdkResult {
        self.0.collect(rm)
    }
    fn force_flush(&self) -> opentelemetry_sdk::error::OTelSdkResult {
        self.0.force_flush()
    }
    fn shutdown_with_timeout(&self, timeout: Duration) -> opentelemetry_sdk::error::OTelSdkResult {
        self.0.shutdown_with_timeout(timeout)
    }
    fn temporality(
        &self,
        kind: opentelemetry_sdk::metrics::InstrumentKind,
    ) -> opentelemetry_sdk::metrics::Temporality {
        self.0.temporality(kind)
    }
}

/// Builds an `OtelMetrics` over a real SDK meter, returning the reader so the
/// caller can collect what was recorded.
fn recording_otel_metrics() -> (OtelMetrics, Arc<ManualReader>, SdkMeterProvider) {
    let reader = Arc::new(ManualReader::builder().build());
    let provider = SdkMeterProvider::builder()
        .with_reader(SharedReader(Arc::clone(&reader)))
        .build();
    let meter = opentelemetry::metrics::MeterProvider::meter(&provider, "a2a-otel-record-test");
    (OtelMetrics::from_meter(&meter), reader, provider)
}

/// Total of every u64 sum data point recorded under `name`.
///
/// `None` means the instrument never appeared, which is a different failure
/// from appearing with a zero total and is reported as such by the callers.
fn sum_for(reader: &ManualReader, name: &str) -> Option<u64> {
    use opentelemetry_sdk::metrics::reader::MetricReader as _;

    let mut collected = ResourceMetrics::default();
    reader.collect(&mut collected).expect("collect should work");

    let mut found = None;
    for scope in collected.scope_metrics() {
        for metric in scope.metrics() {
            if metric.name() != name {
                continue;
            }
            let mut total = 0_u64;
            if let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() {
                total += sum
                    .data_points()
                    .map(opentelemetry_sdk::metrics::data::SumDataPoint::value)
                    .sum::<u64>();
            }
            found = Some(found.unwrap_or(0) + total);
        }
    }
    found
}

/// `on_persistence_error` must actually increment `a2a.server.persistence_errors`.
///
/// This is the SDK's one silent-data-loss path: the streaming reader is a
/// separate subscriber and receives the event whether or not the store accepted
/// it, so a dropped persistence error is invisible to the client. An exporter
/// that accepts the callback and records nothing reproduces exactly the bug the
/// callback was added to fix.
#[test]
fn on_persistence_error_increments_its_counter() {
    let (metrics, reader, provider) = recording_otel_metrics();

    metrics.on_persistence_error(
        crate::metrics::persistence_operation::ARTIFACT_APPEND,
        "internal_error",
    );
    metrics.on_persistence_error(
        crate::metrics::persistence_operation::STATUS_UPDATE,
        "internal_error",
    );

    let total = sum_for(&reader, "a2a.server.persistence_errors")
        .expect("a2a.server.persistence_errors should have been exported");
    assert_eq!(
        total, 2,
        "two persistence errors were reported but the counter totals {total}"
    );

    let _ = provider.shutdown();
}

/// `on_push_delivery` must actually increment `a2a.server.push_deliveries`,
/// once per call, whatever the outcome label.
#[test]
fn on_push_delivery_increments_its_counter() {
    let (metrics, reader, provider) = recording_otel_metrics();

    let outcomes = [
        crate::metrics::push_outcome::DELIVERED,
        crate::metrics::push_outcome::FAILED,
    ];
    for outcome in outcomes {
        metrics.on_push_delivery(outcome);
    }

    let total = sum_for(&reader, "a2a.server.push_deliveries")
        .expect("a2a.server.push_deliveries should have been exported");
    assert_eq!(
        total,
        outcomes.len() as u64,
        "{} deliveries were reported but the counter totals {total}",
        outcomes.len()
    );

    let _ = provider.shutdown();
}