mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
Measure model catalog lookups and HTTP GET attempts (#65123)
## Why A model catalog lookup can use a cached snapshot or bundled fallback without sending a request. A lookup that reaches the endpoint can send multiple requests through retries. Measuring both lets readers of the metrics distinguish cache behavior from endpoint traffic. ## What changed - Record one `codex.remote_models.lookup.outcome` observation per completed catalog lookup with its purpose, result, and the source of the snapshot actually selected. Record observations without taking the exporter lock on the lookup path. - Count dispatched requests in `codex.remote_models.http_get_attempt`, including retries. Tag them by purpose and whether they match the configured endpoint when that context is available. Keep endpoint URLs out of metric labels. - Mark background refreshes as maintenance and apply metrics enablement changes to cached global handles when the process reloads telemetry settings. ## Testing Add coverage for cache and fallback attribution, retry counts, auth failures before dispatch, and metrics collection across exporter disablement and replacement. GitOrigin-RevId: b970207a69432030b4511c7e84acb6696b6f824b
This commit is contained in:
Generated
+1
@@ -4721,6 +4721,7 @@ dependencies = [
|
||||
name = "codex-otel"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"codex-api",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_models_manager::CatalogLookupPurpose;
|
||||
use codex_models_manager::manager::RefreshStrategy;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
@@ -46,7 +47,10 @@ fn spawn_with_interval(
|
||||
let Some(model_catalog) = model_catalog.upgrade() else {
|
||||
break;
|
||||
};
|
||||
if let Err(err) = model_catalog.list_models(RefreshStrategy::Online).await {
|
||||
if let Err(err) = CatalogLookupPurpose::Maintenance
|
||||
.scope(model_catalog.list_models(RefreshStrategy::Online))
|
||||
.await
|
||||
{
|
||||
// Parser diagnostics can include provider credentials from the source TOML.
|
||||
tracing::warn!(error_kind = ?err.kind(), "model catalog refresh blocked by provider requirements");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -63,7 +63,7 @@ fn test_thread_manager(
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TestModelsEndpoint {
|
||||
fetch_count: AtomicUsize,
|
||||
fetch_purposes: Mutex<Vec<CatalogLookupPurpose>>,
|
||||
fetched: Notify,
|
||||
release_second_fetch: Notify,
|
||||
originator_endpoint: Option<Arc<TestModelsEndpoint>>,
|
||||
@@ -72,7 +72,7 @@ struct TestModelsEndpoint {
|
||||
impl TestModelsEndpoint {
|
||||
fn new() -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
fetch_count: AtomicUsize::new(0),
|
||||
fetch_purposes: Mutex::default(),
|
||||
fetched: Notify::new(),
|
||||
release_second_fetch: Notify::new(),
|
||||
originator_endpoint: None,
|
||||
@@ -81,7 +81,7 @@ impl TestModelsEndpoint {
|
||||
|
||||
async fn wait_for_fetch_count(&self, expected: usize) {
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while self.fetch_count.load(Ordering::SeqCst) < expected {
|
||||
while self.fetch_purposes.lock().unwrap().len() < expected {
|
||||
self.fetched.notified().await;
|
||||
}
|
||||
})
|
||||
@@ -118,12 +118,16 @@ impl ModelsEndpointClient for TestModelsEndpoint {
|
||||
_http_client_factory: HttpClientFactory,
|
||||
) -> ModelsEndpointFuture<'a, CoreResult<ModelsEndpointResponse>> {
|
||||
Box::pin(async move {
|
||||
let fetch_index = self.fetch_count.fetch_add(1, Ordering::SeqCst);
|
||||
let fetch_number = {
|
||||
let mut purposes = self.fetch_purposes.lock().unwrap();
|
||||
purposes.push(CatalogLookupPurpose::current());
|
||||
purposes.len()
|
||||
};
|
||||
self.fetched.notify_one();
|
||||
if fetch_index == 0 {
|
||||
if fetch_number == 1 {
|
||||
return Err(CodexErr::Io(std::io::Error::other("test failure")));
|
||||
}
|
||||
if fetch_index == 1 {
|
||||
if fetch_number == 2 {
|
||||
self.release_second_fetch.notified().await;
|
||||
}
|
||||
Ok(ModelsEndpointResponse {
|
||||
@@ -193,8 +197,12 @@ async fn refreshes_immediately_periodically_and_stops_when_dropped() {
|
||||
work_updates.changed().await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
|
||||
assert_eq!(endpoint.fetch_count.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(work_endpoint.fetch_count.load(Ordering::SeqCst), 2);
|
||||
let worker_fetches = [CatalogLookupPurpose::Maintenance; 2];
|
||||
assert_eq!(*endpoint.fetch_purposes.lock().unwrap(), worker_fetches);
|
||||
assert_eq!(
|
||||
*work_endpoint.fetch_purposes.lock().unwrap(),
|
||||
worker_fetches
|
||||
);
|
||||
|
||||
// Reloading after login preserves an embedded caller's typed --oss override.
|
||||
catalog.invalidate().await;
|
||||
@@ -222,7 +230,19 @@ async fn refreshes_immediately_periodically_and_stops_when_dropped() {
|
||||
catalog.current().await.unwrap().0.model_provider_id,
|
||||
"ollama"
|
||||
);
|
||||
assert_eq!(endpoint.fetch_count.load(Ordering::SeqCst), 2);
|
||||
// A picker refresh of the same default catalog is driven by the caller.
|
||||
catalog
|
||||
.list_models_from_snapshot(config, models_manager, RefreshStrategy::Online)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
*endpoint.fetch_purposes.lock().unwrap(),
|
||||
[
|
||||
CatalogLookupPurpose::Maintenance,
|
||||
CatalogLookupPurpose::Maintenance,
|
||||
CatalogLookupPurpose::Foreground,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -295,7 +315,7 @@ async fn background_refresh_blocks_invalid_requirements_then_recovers() -> anyho
|
||||
// Reaching the next check proves the previous refresh completed. Keep
|
||||
// this check blocked while asserting that the previous one did not fetch.
|
||||
next_check = checks_rx.recv().await.unwrap();
|
||||
assert_eq!(endpoint.fetch_count.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(endpoint.fetch_purposes.lock().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
next_check.send(/*t*/ None).unwrap();
|
||||
|
||||
@@ -86,6 +86,11 @@ where
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if next_provider.as_ref().and_then(OtelProvider::metrics).is_none()
|
||||
&& let Some(previous) = provider.as_ref().and_then(OtelProvider::metrics)
|
||||
{
|
||||
previous.disable_global_recording();
|
||||
}
|
||||
if let Err(error) = logger_reload_handle.reload(
|
||||
next_provider
|
||||
.as_ref()
|
||||
|
||||
@@ -104,6 +104,9 @@ impl<T: HttpTransport> EndpointSession<T> {
|
||||
let transport = &self.transport;
|
||||
async move {
|
||||
let req = auth.apply_auth(req).await.map_err(TransportError::from)?;
|
||||
if let Some(telemetry) = &self.request_telemetry {
|
||||
telemetry.on_dispatch();
|
||||
}
|
||||
transport.execute(req).await
|
||||
}
|
||||
},
|
||||
@@ -145,6 +148,9 @@ impl<T: HttpTransport> EndpointSession<T> {
|
||||
let transport = &self.transport;
|
||||
async move {
|
||||
let req = auth.apply_auth(req).await.map_err(TransportError::from)?;
|
||||
if let Some(telemetry) = &self.request_telemetry {
|
||||
telemetry.on_dispatch();
|
||||
}
|
||||
transport.stream(req).await
|
||||
}
|
||||
},
|
||||
|
||||
@@ -18,6 +18,8 @@ use http::Method;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
@@ -214,3 +216,85 @@ async fn models_client_hits_models_endpoint() {
|
||||
assert_eq!(received[0].method, Method::GET.as_str());
|
||||
assert_eq!(received[0].url.path(), "/api/codex/models");
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Dispatches(AtomicUsize);
|
||||
|
||||
impl codex_api::RequestTelemetry for Dispatches {
|
||||
fn on_dispatch(&self) {
|
||||
self.0.fetch_add(/*val*/ 1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn on_request(
|
||||
&self,
|
||||
_attempt: u64,
|
||||
_status: Option<http::StatusCode>,
|
||||
_error: Option<&codex_api::TransportError>,
|
||||
_duration: std::time::Duration,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Each retry represents another dispatched GET for a single catalog lookup.
|
||||
#[tokio::test]
|
||||
async fn dispatch_telemetry_counts_retried_models_requests() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/models"))
|
||||
.respond_with(ResponseTemplate::new(503))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let transport =
|
||||
ReqwestTransport::from_http_client(HttpClientBuilder::new().build_direct().unwrap());
|
||||
let provider = provider(&server.uri());
|
||||
let url = ModelsClient::<ReqwestTransport>::request_url(&provider, "0.1.0");
|
||||
let dispatches = Arc::new(Dispatches::default());
|
||||
let client = ModelsClient::new(transport, provider, Arc::new(DummyAuth))
|
||||
.with_telemetry(Some(dispatches.clone()));
|
||||
client
|
||||
.list_models(
|
||||
url,
|
||||
HeaderMap::new(),
|
||||
/*response_body_limit_bytes*/ None,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(dispatches.0.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auth_failure_before_transport_does_not_count_as_a_models_get_attempt() {
|
||||
struct FailingAuth;
|
||||
impl AuthProvider for FailingAuth {
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> {
|
||||
Err(codex_api::AuthError::Build(
|
||||
"cannot authenticate".to_owned(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
let server = MockServer::start().await;
|
||||
let provider = provider(&server.uri());
|
||||
let url = ModelsClient::<ReqwestTransport>::request_url(&provider, "0.1.0");
|
||||
let transport =
|
||||
ReqwestTransport::from_http_client(HttpClientBuilder::new().build_direct().unwrap());
|
||||
let dispatches = Arc::new(Dispatches::default());
|
||||
let client = ModelsClient::new(transport, provider, Arc::new(FailingAuth))
|
||||
.with_telemetry(Some(dispatches.clone()));
|
||||
let error = client
|
||||
.list_models(
|
||||
url,
|
||||
HeaderMap::new(),
|
||||
/*response_body_limit_bytes*/ None,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
assert!(matches!(
|
||||
error,
|
||||
codex_api::ApiError::Transport(codex_api::TransportError::Build(_))
|
||||
));
|
||||
assert_eq!(dispatches.0.load(Ordering::Relaxed), 0);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
@@ -4,6 +4,9 @@ use std::time::Duration;
|
||||
|
||||
/// API specific telemetry.
|
||||
pub trait RequestTelemetry: Send + Sync {
|
||||
/// Called at dispatch for each authenticated transport attempt, including retries.
|
||||
fn on_dispatch(&self) {}
|
||||
|
||||
fn on_request(
|
||||
&self,
|
||||
attempt: u64,
|
||||
|
||||
@@ -112,7 +112,7 @@ pub fn build_provider(
|
||||
.map_or(DEFAULT_HEADERS_HELPER_REFRESH_INTERVAL_MS, NonZeroU64::get),
|
||||
),
|
||||
});
|
||||
OtelProvider::try_new(&OtelSettings {
|
||||
OtelProvider::try_new_for_process(&OtelSettings {
|
||||
headers_helper,
|
||||
http_client_factory: config.http_client_factory(),
|
||||
service_name: service_name.to_string(),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
@@ -27,6 +28,7 @@ use codex_login::default_client::create_client_for_route_async;
|
||||
use codex_model_provider_info::CHATGPT_CODEX_BASE_URL;
|
||||
use codex_model_provider_info::GatewayOAuthConfig;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_models_manager::CatalogLookupPurpose;
|
||||
use codex_models_manager::ModelCatalogOriginator;
|
||||
use codex_models_manager::manager::ModelsEndpointClient;
|
||||
use codex_models_manager::manager::ModelsEndpointFuture;
|
||||
@@ -50,6 +52,38 @@ const MODELS_REFRESH_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const MODELS_ENDPOINT: &str = "/models";
|
||||
const FEDRAMP_CODEX_BASE_URL: &str = "https://gov.chatgpt.com/backend-api/codex";
|
||||
|
||||
fn catalog_dispatch_target(request_url: &str) -> &'static str {
|
||||
CatalogLookupPurpose::dispatch_target(|expected| {
|
||||
let (Ok(expected), Ok(request)) = (url::Url::parse(expected), url::Url::parse(request_url))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if expected[..url::Position::AfterPath] != request[..url::Position::AfterPath] {
|
||||
return false;
|
||||
}
|
||||
if expected.query().is_none() {
|
||||
return true;
|
||||
}
|
||||
let mut values_by_key = HashMap::<_, (Vec<_>, Vec<_>)>::new();
|
||||
for (key, value) in expected.query_pairs() {
|
||||
let (configured, _) = values_by_key.entry(key).or_default();
|
||||
configured.push(value);
|
||||
}
|
||||
for (key, value) in request.query_pairs() {
|
||||
if let Some((_, sent)) = values_by_key.get_mut(&key) {
|
||||
sent.push(value);
|
||||
}
|
||||
}
|
||||
values_by_key
|
||||
.values()
|
||||
.all(|(configured, sent)| match configured.as_slice() {
|
||||
// The builder can append the same provider parameter or client_version again.
|
||||
[value] => !sent.is_empty() && sent.iter().all(|sent_value| sent_value == value),
|
||||
_ => sent == configured,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Only probe routes owned by the configured gateway. An explicit URL on another
|
||||
// origin keeps its existing auth rules; automatic discovery must not widen token delivery.
|
||||
fn supports_gateway_catalog(info: &ModelProviderInfo) -> bool {
|
||||
@@ -234,6 +268,7 @@ impl OpenAiModelsEndpoint {
|
||||
};
|
||||
let provider_catalog = is_provider_catalog(&self.provider_info);
|
||||
let request_telemetry: Arc<dyn RequestTelemetry> = Arc::new(ModelsRequestTelemetry {
|
||||
target: catalog_dispatch_target(&request_url),
|
||||
include_response_debug: !provider_catalog,
|
||||
auth_mode: auth_mode.map(|mode| TelemetryAuthMode::from(mode).to_string()),
|
||||
auth_header_attached: auth_telemetry.attached,
|
||||
@@ -423,6 +458,7 @@ impl ModelsTransportBuilder for RouteAwareModelsTransportBuilder {
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ModelsRequestTelemetry {
|
||||
target: &'static str,
|
||||
include_response_debug: bool,
|
||||
auth_mode: Option<String>,
|
||||
auth_header_attached: bool,
|
||||
@@ -432,6 +468,19 @@ struct ModelsRequestTelemetry {
|
||||
}
|
||||
|
||||
impl RequestTelemetry for ModelsRequestTelemetry {
|
||||
fn on_dispatch(&self) {
|
||||
if let Some(metrics) = codex_otel::global() {
|
||||
let _ = metrics.counter(
|
||||
"codex.remote_models.http_get_attempt",
|
||||
/*inc*/ 1,
|
||||
&[
|
||||
("purpose", CatalogLookupPurpose::current().as_str()),
|
||||
("catalog_target", self.target),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn on_request(
|
||||
&self,
|
||||
attempt: u64,
|
||||
|
||||
@@ -25,6 +25,87 @@ use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
use wiremock::matchers::query_param;
|
||||
|
||||
#[tokio::test]
|
||||
async fn cold_resume_dispatch_target_honors_the_configured_route() {
|
||||
let endpoint = "https://provider.test/api/models";
|
||||
assert_eq!(catalog_dispatch_target(endpoint), "unclassified");
|
||||
for (expected_query, request_url, target) in [
|
||||
(
|
||||
"",
|
||||
"https://provider.test/api/models?client_version=1",
|
||||
"configured",
|
||||
),
|
||||
("", "https://other.test/api/models", "other"),
|
||||
("", "https://provider.test/models", "other"),
|
||||
(
|
||||
"?deployment=team%20one",
|
||||
"https://provider.test/api/models?client_version=1&deployment=team+one&api-version=2",
|
||||
"configured",
|
||||
),
|
||||
(
|
||||
"?deployment=one",
|
||||
"https://provider.test/api/models?client_version=1",
|
||||
"other",
|
||||
),
|
||||
(
|
||||
"?deployment=one",
|
||||
"https://provider.test/api/models?deployment=two",
|
||||
"other",
|
||||
),
|
||||
(
|
||||
"?deployment=one",
|
||||
"https://provider.test/api/models?deployment=one&deployment=two",
|
||||
"other",
|
||||
),
|
||||
(
|
||||
"?route=a&route=b",
|
||||
"https://provider.test/api/models?route=a&client_version=1&route=b",
|
||||
"configured",
|
||||
),
|
||||
(
|
||||
"?route=a&route=b",
|
||||
"https://provider.test/api/models?route=b&route=a",
|
||||
"other",
|
||||
),
|
||||
(
|
||||
"?route=a&route=b",
|
||||
"https://provider.test/api/models?route=a&route=b&route=b",
|
||||
"other",
|
||||
),
|
||||
] {
|
||||
let target_label = CatalogLookupPurpose::ColdResume
|
||||
.scope_with_endpoint(format!("{endpoint}{expected_query}"), async {
|
||||
catalog_dispatch_target(request_url)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(target_label, target, "{request_url}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cold_resume_dispatch_target_handles_builder_appended_values() {
|
||||
let provider = ModelProviderInfo {
|
||||
query_params: Some(HashMap::from([("deployment".to_string(), "one".into())])),
|
||||
..ModelProviderInfo::create_openai_provider(Some("https://provider.test/api".to_string()))
|
||||
};
|
||||
let provider = resolve_api_provider(&provider, /*auth*/ None).unwrap();
|
||||
for (query, expected_target) in [
|
||||
("deployment=one", "configured"),
|
||||
("deployment=two", "other"),
|
||||
("client_version=1", "configured"),
|
||||
("client_version=2", "other"),
|
||||
] {
|
||||
let endpoint = format!("https://provider.test/api/models?{query}");
|
||||
let request_url =
|
||||
ModelsClient::<ReqwestTransport>::catalog_request_url(&provider, &endpoint, "1")
|
||||
.unwrap();
|
||||
let target = CatalogLookupPurpose::ColdResume
|
||||
.scope_with_endpoint(endpoint, async { catalog_dispatch_target(&request_url) })
|
||||
.await;
|
||||
assert_eq!(target, expected_target, "{request_url}");
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RecordingTransportBuilder {
|
||||
observed_request: Arc<Mutex<Option<(OutboundProxyPolicy, String)>>>,
|
||||
|
||||
@@ -34,6 +34,42 @@ async fn api_key_discovery_disabled_preserves_command_auth_discovery_and_merging
|
||||
assert_eq!(endpoint.fetch_count(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabled_discovery_records_bypass_for_cold_and_initialized_catalogs() {
|
||||
let endpoint = TestModelsEndpoint::without_refresh(vec![vec![remote_model(
|
||||
"dynamic", "Dynamic", /*priority*/ 0,
|
||||
)]]);
|
||||
let auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-key"));
|
||||
let manager = OpenAiModelsManager::new_without_cache(endpoint.clone(), Some(auth));
|
||||
let http = DEFAULT_HTTP_CLIENT_FACTORY;
|
||||
let bundled = load_remote_models_from_file().unwrap();
|
||||
|
||||
for initialized in [false, true] {
|
||||
if initialized {
|
||||
manager.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
manager.ensure_initialized(http.clone()).await;
|
||||
manager.set_api_key_model_discovery_enabled(/*enabled*/ false);
|
||||
}
|
||||
let observed = crate::lookup::observe(async {
|
||||
manager.ensure_initialized(http.clone()).await;
|
||||
for strategy in [RefreshStrategy::InMemory, RefreshStrategy::OnlineIfUncached] {
|
||||
assert_eq!(
|
||||
manager
|
||||
.raw_model_catalog(strategy, http.clone())
|
||||
.await
|
||||
.models,
|
||||
bundled
|
||||
);
|
||||
}
|
||||
assert_eq!(manager.get_remote_models().await, bundled);
|
||||
assert_eq!(manager.try_get_remote_models().unwrap(), bundled);
|
||||
})
|
||||
.await;
|
||||
assert_eq!(observed, vec![("bypass", "fallback", "foreground"); 5]);
|
||||
assert_eq!(endpoint.fetch_count(), usize::from(initialized));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_key_discovery_flag_controls_fetches_and_cached_catalogs() {
|
||||
let home = tempdir().unwrap();
|
||||
|
||||
@@ -15,6 +15,11 @@ use std::time::Duration;
|
||||
use tokio::fs;
|
||||
use tracing::info;
|
||||
|
||||
pub use crate::lookup::CacheLayer;
|
||||
|
||||
pub type SourcedCacheLoad<'a> =
|
||||
ModelsCacheFuture<'a, Result<Option<(ModelsCacheEntry, CacheLayer)>, ModelsCacheError>>;
|
||||
|
||||
/// Asynchronous storage for model catalog snapshots used by the models manager.
|
||||
///
|
||||
/// Implementations own cache freshness and lookup partitioning. [`ModelsCache::load`] must not
|
||||
@@ -41,6 +46,16 @@ pub trait ModelsCache: fmt::Debug + Send + Sync {
|
||||
client_version: &'a str,
|
||||
) -> ModelsCacheFuture<'a, Result<Option<ModelsCacheEntry>, ModelsCacheError>>;
|
||||
|
||||
/// Load once and identify the layer that supplied the candidate for this request.
|
||||
fn load_with_source<'a>(&'a self, client_version: &'a str) -> SourcedCacheLoad<'a> {
|
||||
Box::pin(async move {
|
||||
Ok(self
|
||||
.load(client_version)
|
||||
.await?
|
||||
.map(|entry| (entry, CacheLayer::Other)))
|
||||
})
|
||||
}
|
||||
|
||||
/// Stores `entry`, replacing the snapshot for this cache implementation's lookup identity.
|
||||
///
|
||||
/// The implementation derives that identity from its own configuration and the entry metadata.
|
||||
@@ -149,6 +164,15 @@ impl FileModelsCache {
|
||||
}
|
||||
|
||||
impl ModelsCache for FileModelsCache {
|
||||
fn load_with_source<'a>(&'a self, client_version: &'a str) -> SourcedCacheLoad<'a> {
|
||||
Box::pin(async move {
|
||||
Ok(self
|
||||
.load(client_version)
|
||||
.await?
|
||||
.map(|entry| (entry, CacheLayer::Disk)))
|
||||
})
|
||||
}
|
||||
|
||||
fn for_originator(&self, originator: ModelCatalogOriginator) -> Option<Arc<dyn ModelsCache>> {
|
||||
Some(Arc::new(Self::new(
|
||||
self.cache_path
|
||||
|
||||
@@ -23,9 +23,10 @@ async fn mismatched_and_legacy_cache_entries_fetch_the_current_catalog() {
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
)),
|
||||
);
|
||||
manager
|
||||
.ensure_initialized(DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await;
|
||||
assert_eq!(
|
||||
crate::lookup::observe(manager.ensure_initialized(DEFAULT_HTTP_CLIENT_FACTORY)).await,
|
||||
vec![("miss", "endpoint", "foreground")]
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.raw_model_catalog(RefreshStrategy::InMemory, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
|
||||
@@ -10,18 +10,17 @@ use crate::cache::ModelsCacheEntry;
|
||||
pub use codex_protocol::openai_models::CatalogModel;
|
||||
pub use codex_protocol::openai_models::ModelOrigin;
|
||||
|
||||
/// Catalog authority is independent of whether its model metadata is borrowed or owned.
|
||||
pub(crate) enum SelectedCatalog<'a> {
|
||||
CurrentSnapshot(Cow<'a, [ModelInfo]>),
|
||||
Fallback(Cow<'a, [ModelInfo]>),
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum CatalogSelection {
|
||||
CurrentSnapshot,
|
||||
Fallback,
|
||||
DiscoveryDisabled,
|
||||
}
|
||||
|
||||
impl<'a> SelectedCatalog<'a> {
|
||||
pub fn into_models(self) -> Cow<'a, [ModelInfo]> {
|
||||
match self {
|
||||
Self::CurrentSnapshot(models) | Self::Fallback(models) => models,
|
||||
}
|
||||
}
|
||||
/// Keep the models and the decision that selected them in the same snapshot.
|
||||
pub(crate) struct SelectedCatalog<'a> {
|
||||
pub selection: CatalogSelection,
|
||||
pub models: Cow<'a, [ModelInfo]>,
|
||||
}
|
||||
|
||||
/// The effective catalog and the IDs in the unmerged provider response share one lock.
|
||||
@@ -31,6 +30,7 @@ pub(crate) struct CatalogState {
|
||||
pub provider_model_ids: HashSet<String>,
|
||||
// Distinguishes a successfully loaded empty catalog from the initial bundled seed.
|
||||
pub initialized: bool,
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
impl CatalogState {
|
||||
@@ -39,6 +39,7 @@ impl CatalogState {
|
||||
entry,
|
||||
provider_model_ids: HashSet::new(),
|
||||
initialized: false,
|
||||
generation: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,11 +54,12 @@ impl CatalogState {
|
||||
entry,
|
||||
provider_model_ids,
|
||||
initialized: true,
|
||||
generation: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn model_origin(&self, selected: &SelectedCatalog<'_>, slug: &str) -> ModelOrigin {
|
||||
if matches!(selected, SelectedCatalog::CurrentSnapshot(_))
|
||||
if selected.selection == CatalogSelection::CurrentSnapshot
|
||||
&& self.provider_model_ids.contains(slug)
|
||||
{
|
||||
ModelOrigin::Provider
|
||||
@@ -67,10 +69,8 @@ impl CatalogState {
|
||||
}
|
||||
|
||||
pub fn model_catalog(&self, selected: SelectedCatalog<'_>) -> Vec<CatalogModel> {
|
||||
let models = match &selected {
|
||||
SelectedCatalog::CurrentSnapshot(models) | SelectedCatalog::Fallback(models) => models,
|
||||
};
|
||||
models
|
||||
selected
|
||||
.models
|
||||
.iter()
|
||||
.map(|model| CatalogModel {
|
||||
origin: self.model_origin(&selected, &model.slug),
|
||||
|
||||
@@ -2,6 +2,7 @@ pub mod cache;
|
||||
mod catalog;
|
||||
pub mod collaboration_mode_presets;
|
||||
pub(crate) mod config;
|
||||
mod lookup;
|
||||
pub mod manager;
|
||||
pub mod model_info;
|
||||
pub mod model_presets;
|
||||
@@ -12,6 +13,7 @@ pub use catalog::CatalogModel;
|
||||
pub use catalog::ModelOrigin;
|
||||
pub use codex_protocol::auth::AuthMode;
|
||||
pub use config::ModelsManagerConfig;
|
||||
pub use lookup::CatalogLookupPurpose;
|
||||
pub use originator::ModelCatalogOriginator;
|
||||
|
||||
/// Load the bundled model catalog shipped with `codex-models-manager`.
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Measures completed full-catalog reads and initialization. Storage returns a
|
||||
//! candidate; the manager decides which snapshot actually satisfies the caller.
|
||||
|
||||
#[cfg(test)]
|
||||
use std::future::Future;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
|
||||
use crate::catalog::CatalogSelection;
|
||||
use crate::catalog::CatalogState;
|
||||
|
||||
pub use codex_otel::CatalogLookupPurpose;
|
||||
use codex_otel::CatalogLookupResult;
|
||||
use codex_otel::CatalogLookupSource;
|
||||
|
||||
/// Where the cache adapter retrieved this candidate. Only used during the read.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CacheLayer {
|
||||
StartupMemory,
|
||||
Shared,
|
||||
Disk,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl CacheLayer {
|
||||
fn source(self) -> CatalogLookupSource {
|
||||
match self {
|
||||
Self::StartupMemory => CatalogLookupSource::StartupMemory,
|
||||
Self::Shared => CatalogLookupSource::SharedCache,
|
||||
Self::Disk => CatalogLookupSource::Disk,
|
||||
Self::Other => CatalogLookupSource::OtherCache,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Track publication until the caller selects its snapshot. Another request
|
||||
/// can replace a publication between releasing the write lock and selection.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum Resolution {
|
||||
Snapshot,
|
||||
Cached(CacheLayer, u64),
|
||||
Fetched(Option<u64>),
|
||||
Disabled,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct LookupOutcome(CatalogLookupResult, CatalogLookupSource);
|
||||
|
||||
impl Resolution {
|
||||
pub(crate) fn selected(
|
||||
self,
|
||||
state: &CatalogState,
|
||||
selection: CatalogSelection,
|
||||
) -> LookupOutcome {
|
||||
let usable = selection == CatalogSelection::CurrentSnapshot
|
||||
&& state.initialized
|
||||
&& state.entry.fetched_at != DateTime::<Utc>::MIN_UTC;
|
||||
let source = if usable {
|
||||
CatalogLookupSource::CoreMemory
|
||||
} else {
|
||||
CatalogLookupSource::Fallback
|
||||
};
|
||||
match self {
|
||||
Self::Disabled => LookupOutcome(CatalogLookupResult::Bypass, source),
|
||||
Self::Snapshot if selection == CatalogSelection::DiscoveryDisabled => {
|
||||
LookupOutcome(CatalogLookupResult::Bypass, source)
|
||||
}
|
||||
Self::Failed => LookupOutcome(CatalogLookupResult::Error, source),
|
||||
Self::Fetched(generation) => {
|
||||
if usable && generation == Some(state.generation) {
|
||||
LookupOutcome(CatalogLookupResult::Miss, CatalogLookupSource::Endpoint)
|
||||
} else {
|
||||
LookupOutcome(CatalogLookupResult::Miss, source)
|
||||
}
|
||||
}
|
||||
Self::Cached(layer, generation) if usable && generation == state.generation => {
|
||||
LookupOutcome(CatalogLookupResult::Hit, layer.source())
|
||||
}
|
||||
Self::Snapshot | Self::Cached(..) => {
|
||||
if usable {
|
||||
LookupOutcome(CatalogLookupResult::Hit, source)
|
||||
} else {
|
||||
LookupOutcome(CatalogLookupResult::Fallback, source)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LookupOutcome {
|
||||
pub(crate) const BUSY: Self = Self(CatalogLookupResult::Error, CatalogLookupSource::None);
|
||||
|
||||
pub(crate) fn record(self) {
|
||||
let purpose = CatalogLookupPurpose::current();
|
||||
#[cfg(test)]
|
||||
let _ = OBSERVED.try_with(|rows| {
|
||||
rows.borrow_mut()
|
||||
.push((self.0.as_str(), self.1.as_str(), purpose.as_str()))
|
||||
});
|
||||
codex_otel::record_model_catalog_lookup(purpose, self.0, self.1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
type Observation = (&'static str, &'static str, &'static str);
|
||||
|
||||
#[cfg(test)]
|
||||
tokio::task_local! {
|
||||
static OBSERVED: std::cell::RefCell<Vec<Observation>>;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn observe<F: Future>(future: F) -> Vec<Observation> {
|
||||
OBSERVED
|
||||
.scope(Default::default(), async {
|
||||
future.await;
|
||||
OBSERVED.with(std::cell::RefCell::take)
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -3,11 +3,15 @@ use crate::ModelCatalogOriginator;
|
||||
use crate::cache::ModelsCache;
|
||||
use crate::cache::ModelsCacheEntry;
|
||||
use crate::catalog::CatalogModel;
|
||||
use crate::catalog::CatalogSelection;
|
||||
use crate::catalog::CatalogState;
|
||||
use crate::catalog::ModelOrigin;
|
||||
use crate::catalog::SelectedCatalog;
|
||||
use crate::collaboration_mode_presets::builtin_collaboration_mode_presets;
|
||||
use crate::config::ModelsManagerConfig;
|
||||
use crate::lookup::CatalogLookupPurpose;
|
||||
use crate::lookup::LookupOutcome;
|
||||
use crate::lookup::Resolution;
|
||||
use crate::model_info;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
@@ -557,15 +561,33 @@ impl ModelsManager for OpenAiModelsManager {
|
||||
Box::pin(async move {
|
||||
// Resolve lazy credentials before checking the selected catalog's identity.
|
||||
self.should_refresh_models().await;
|
||||
if self.catalog_is_initialized(&*self.remote_models.read().await) {
|
||||
let initialized = {
|
||||
let state = self.remote_models.read().await;
|
||||
self.catalog_is_initialized(&state).then(|| {
|
||||
let selection = if self.api_key_discovery_disabled() {
|
||||
CatalogSelection::DiscoveryDisabled
|
||||
} else {
|
||||
CatalogSelection::CurrentSnapshot
|
||||
};
|
||||
Resolution::Snapshot.selected(&state, selection)
|
||||
})
|
||||
};
|
||||
if let Some(outcome) = initialized {
|
||||
outcome.record();
|
||||
return;
|
||||
}
|
||||
if let Err(err) = self
|
||||
let resolution = self
|
||||
.load_catalog(CatalogLoadMode::Initialize, &http_client_factory)
|
||||
.await
|
||||
{
|
||||
error!("failed to initialize model catalog: {err}");
|
||||
}
|
||||
.unwrap_or_else(|err| {
|
||||
error!("failed to initialize model catalog: {err}");
|
||||
Resolution::Failed
|
||||
});
|
||||
let state = self.remote_models.read().await;
|
||||
let selected = self.models_for_entry(&state.entry);
|
||||
let outcome = resolution.selected(&state, selected.selection);
|
||||
drop(state);
|
||||
outcome.record();
|
||||
})
|
||||
}
|
||||
|
||||
@@ -597,8 +619,10 @@ impl ModelsManager for OpenAiModelsManager {
|
||||
.collect();
|
||||
Box::pin(async move {
|
||||
for manager in managers {
|
||||
manager
|
||||
.list_models(RefreshStrategy::Online, http_client_factory.clone())
|
||||
CatalogLookupPurpose::Maintenance
|
||||
.scope(
|
||||
manager.list_models(RefreshStrategy::Online, http_client_factory.clone()),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
})
|
||||
@@ -610,15 +634,26 @@ impl ModelsManager for OpenAiModelsManager {
|
||||
http_client_factory: HttpClientFactory,
|
||||
) -> ModelsManagerFuture<'_, Vec<CatalogModel>> {
|
||||
Box::pin(async move {
|
||||
if refresh_strategy != RefreshStrategy::InMemory
|
||||
&& let Err(err) = self
|
||||
.refresh_available_models(refresh_strategy, &http_client_factory)
|
||||
.await
|
||||
{
|
||||
error!("failed to refresh available models: {err}");
|
||||
}
|
||||
let resolution = if refresh_strategy == RefreshStrategy::InMemory {
|
||||
Resolution::Snapshot
|
||||
} else {
|
||||
self.load_catalog(
|
||||
CatalogLoadMode::Refresh(refresh_strategy),
|
||||
&http_client_factory,
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|err| {
|
||||
error!("failed to refresh available models: {err}");
|
||||
Resolution::Failed
|
||||
})
|
||||
};
|
||||
let state = self.remote_models.read().await;
|
||||
state.model_catalog(self.models_for_entry(&state.entry))
|
||||
let selected = self.models_for_entry(&state.entry);
|
||||
let outcome = resolution.selected(&state, selected.selection);
|
||||
let catalog = state.model_catalog(selected);
|
||||
drop(state);
|
||||
outcome.record();
|
||||
catalog
|
||||
})
|
||||
}
|
||||
|
||||
@@ -683,20 +718,15 @@ impl ModelsManager for OpenAiModelsManager {
|
||||
}
|
||||
|
||||
fn get_remote_models(&self) -> ModelsManagerFuture<'_, Vec<ModelInfo>> {
|
||||
Box::pin(async move {
|
||||
let entry = self.remote_models.read().await;
|
||||
self.models_for_entry(&entry.entry)
|
||||
.into_models()
|
||||
.into_owned()
|
||||
})
|
||||
Box::pin(async move { self.read_snapshot(self.remote_models.read().await) })
|
||||
}
|
||||
|
||||
fn try_get_remote_models(&self) -> Result<Vec<ModelInfo>, TryLockError> {
|
||||
let entry = self.remote_models.try_read()?;
|
||||
Ok(self
|
||||
.models_for_entry(&entry.entry)
|
||||
.into_models()
|
||||
.into_owned())
|
||||
let state = self
|
||||
.remote_models
|
||||
.try_read()
|
||||
.inspect_err(|_| LookupOutcome::BUSY.record())?;
|
||||
Ok(self.read_snapshot(state))
|
||||
}
|
||||
|
||||
fn auth_manager(&self) -> Option<&AuthManager> {
|
||||
@@ -713,10 +743,7 @@ impl ModelsManager for OpenAiModelsManager {
|
||||
let remote = {
|
||||
let entry = self.remote_models.read().await;
|
||||
let selected = self.models_for_entry(&entry.entry);
|
||||
let models = match &selected {
|
||||
SelectedCatalog::CurrentSnapshot(models)
|
||||
| SelectedCatalog::Fallback(models) => models,
|
||||
};
|
||||
let models = &selected.models;
|
||||
let model = match &self.catalog_source {
|
||||
CatalogSource::Default => find_model_from_candidates(model, models),
|
||||
CatalogSource::ExplicitProvider(_) => models
|
||||
@@ -751,6 +778,18 @@ impl ModelsManager for OpenAiModelsManager {
|
||||
}
|
||||
|
||||
impl OpenAiModelsManager {
|
||||
fn read_snapshot(
|
||||
&self,
|
||||
state: tokio::sync::RwLockReadGuard<'_, CatalogState>,
|
||||
) -> Vec<ModelInfo> {
|
||||
let selected = self.models_for_entry(&state.entry);
|
||||
let outcome = Resolution::Snapshot.selected(&state, selected.selection);
|
||||
let models = selected.models.into_owned();
|
||||
drop(state);
|
||||
outcome.record();
|
||||
models
|
||||
}
|
||||
|
||||
fn catalog_is_initialized(&self, catalog: &CatalogState) -> bool {
|
||||
catalog.initialized
|
||||
&& catalog.entry.identity.is_some()
|
||||
@@ -759,15 +798,22 @@ impl OpenAiModelsManager {
|
||||
|
||||
/// Selects the catalog available under the current provider and auth identity.
|
||||
fn models_for_entry<'a>(&self, entry: &'a ModelsCacheEntry) -> SelectedCatalog<'a> {
|
||||
if !self.api_key_discovery_disabled()
|
||||
&& entry.identity.is_some()
|
||||
&& entry.identity == self.endpoint_client.identity()
|
||||
{
|
||||
SelectedCatalog::CurrentSnapshot(Cow::Borrowed(&entry.models))
|
||||
let selection = if self.api_key_discovery_disabled() {
|
||||
CatalogSelection::DiscoveryDisabled
|
||||
} else if entry.identity.is_some() && entry.identity == self.endpoint_client.identity() {
|
||||
CatalogSelection::CurrentSnapshot
|
||||
} else {
|
||||
SelectedCatalog::Fallback(Cow::Borrowed(
|
||||
self.catalog_source.fallback_models().unwrap_or_default(),
|
||||
))
|
||||
CatalogSelection::Fallback
|
||||
};
|
||||
let models = match selection {
|
||||
CatalogSelection::CurrentSnapshot => entry.models.as_slice(),
|
||||
CatalogSelection::DiscoveryDisabled | CatalogSelection::Fallback => {
|
||||
self.catalog_source.fallback_models().unwrap_or_default()
|
||||
}
|
||||
};
|
||||
SelectedCatalog {
|
||||
selection,
|
||||
models: Cow::Borrowed(models),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -815,30 +861,32 @@ impl OpenAiModelsManager {
|
||||
refresh_strategy: RefreshStrategy,
|
||||
http_client_factory: &HttpClientFactory,
|
||||
) -> CoreResult<()> {
|
||||
self.load_catalog(
|
||||
CatalogLoadMode::Refresh(refresh_strategy),
|
||||
http_client_factory,
|
||||
)
|
||||
.await
|
||||
CatalogLookupPurpose::Maintenance
|
||||
.scope(self.load_catalog(
|
||||
CatalogLoadMode::Refresh(refresh_strategy),
|
||||
http_client_factory,
|
||||
))
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
async fn load_catalog(
|
||||
&self,
|
||||
mode: CatalogLoadMode,
|
||||
http_client_factory: &HttpClientFactory,
|
||||
) -> CoreResult<()> {
|
||||
) -> CoreResult<Resolution> {
|
||||
let _refresh_guard = self.catalog_source.refresh_lock().await;
|
||||
// API-key discovery must be enabled and supported before reusing a remote catalog.
|
||||
// Otherwise even a matching cache from an earlier run would bypass bundled-only behavior.
|
||||
// Command-auth providers retain their existing discovery behavior.
|
||||
if self.api_key_discovery_disabled() {
|
||||
return Ok(());
|
||||
return Ok(Resolution::Disabled);
|
||||
}
|
||||
let should_refresh = self.should_refresh_models().await;
|
||||
if mode == CatalogLoadMode::Initialize
|
||||
&& self.catalog_is_initialized(&*self.remote_models.read().await)
|
||||
{
|
||||
return Ok(());
|
||||
return Ok(Resolution::Snapshot);
|
||||
}
|
||||
if !should_refresh {
|
||||
if matches!(
|
||||
@@ -848,20 +896,23 @@ impl OpenAiModelsManager {
|
||||
RefreshStrategy::Offline | RefreshStrategy::OnlineIfUncached
|
||||
)
|
||||
) {
|
||||
self.try_load_cache(mode).await;
|
||||
return Ok(self
|
||||
.try_load_cache(mode)
|
||||
.await
|
||||
.unwrap_or(Resolution::Snapshot));
|
||||
}
|
||||
return Ok(());
|
||||
return Ok(Resolution::Snapshot);
|
||||
}
|
||||
match mode {
|
||||
CatalogLoadMode::Refresh(RefreshStrategy::InMemory) => Ok(()),
|
||||
CatalogLoadMode::Refresh(RefreshStrategy::Offline) => {
|
||||
self.try_load_cache(mode).await;
|
||||
Ok(())
|
||||
}
|
||||
CatalogLoadMode::Refresh(RefreshStrategy::InMemory) => Ok(Resolution::Snapshot),
|
||||
CatalogLoadMode::Refresh(RefreshStrategy::Offline) => Ok(self
|
||||
.try_load_cache(mode)
|
||||
.await
|
||||
.unwrap_or(Resolution::Snapshot)),
|
||||
CatalogLoadMode::Initialize
|
||||
| CatalogLoadMode::Refresh(RefreshStrategy::OnlineIfUncached) => {
|
||||
if self.try_load_cache(mode).await {
|
||||
return Ok(());
|
||||
if let Some(resolution) = self.try_load_cache(mode).await {
|
||||
return Ok(resolution);
|
||||
}
|
||||
self.fetch_and_update_models(http_client_factory, mode)
|
||||
.await
|
||||
@@ -877,7 +928,7 @@ impl OpenAiModelsManager {
|
||||
&self,
|
||||
http_client_factory: &HttpClientFactory,
|
||||
mode: CatalogLoadMode,
|
||||
) -> CoreResult<()> {
|
||||
) -> CoreResult<Resolution> {
|
||||
let client_version = crate::client_version_to_whole();
|
||||
let request_identity = self.endpoint_client.identity();
|
||||
let ModelsEndpointResponse {
|
||||
@@ -912,6 +963,7 @@ impl OpenAiModelsManager {
|
||||
entry: current,
|
||||
provider_model_ids,
|
||||
initialized,
|
||||
..
|
||||
} = &mut *current;
|
||||
if request_identity != self.endpoint_client.identity() {
|
||||
return Err(error);
|
||||
@@ -935,7 +987,9 @@ impl OpenAiModelsManager {
|
||||
&& let Some(cache) = self.settings.cache.as_ref()
|
||||
{
|
||||
let invalidation = async {
|
||||
if let Some(mut entry) = cache.load(&client_version).await?
|
||||
if let Some(mut entry) = CatalogLookupPurpose::Maintenance
|
||||
.scope(cache.load(&client_version))
|
||||
.await?
|
||||
&& entry.identity.as_deref() == Some(&identity)
|
||||
&& entry.client_version.as_deref() == Some(&client_version)
|
||||
{
|
||||
@@ -955,7 +1009,7 @@ impl OpenAiModelsManager {
|
||||
if implicit_gateway && !credentials_rejected {
|
||||
// Automatic discovery is optional. Let the picker use the available catalog.
|
||||
tracing::debug!(%error, "gateway model catalog unavailable");
|
||||
return Ok(());
|
||||
return Ok(Resolution::Failed);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
@@ -964,7 +1018,7 @@ impl OpenAiModelsManager {
|
||||
|| (mode == CatalogLoadMode::Initialize
|
||||
&& self.catalog_is_initialized(&*self.remote_models.read().await))
|
||||
{
|
||||
return Ok(());
|
||||
return Ok(Resolution::Fetched(None));
|
||||
}
|
||||
let refreshed = Arc::new(RefreshedModelCatalog {
|
||||
identity: identity.clone(),
|
||||
@@ -985,8 +1039,10 @@ impl OpenAiModelsManager {
|
||||
let mut current = self.remote_models.write().await;
|
||||
if self.apply_remote_models(&mut current, entry, mode) {
|
||||
self.catalog_updates.send_replace(Some(refreshed));
|
||||
Ok(Resolution::Fetched(Some(current.generation)))
|
||||
} else {
|
||||
Ok(Resolution::Fetched(None))
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn supports_api_key_discovery(&self) -> bool {
|
||||
@@ -1061,44 +1117,41 @@ impl OpenAiModelsManager {
|
||||
}
|
||||
entry.models = models;
|
||||
}
|
||||
catalog.generation = current.generation.wrapping_add(1);
|
||||
*current = catalog;
|
||||
true
|
||||
}
|
||||
|
||||
/// Attempt to satisfy the refresh from the cache when it matches the provider and TTL.
|
||||
async fn try_load_cache(&self, mode: CatalogLoadMode) -> bool {
|
||||
let Some(cache) = self.settings.cache.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
async fn try_load_cache(&self, mode: CatalogLoadMode) -> Option<Resolution> {
|
||||
let cache = self.settings.cache.as_ref()?;
|
||||
let _timer =
|
||||
codex_otel::start_global_timer("codex.remote_models.load_cache.duration_ms", &[]);
|
||||
let client_version = crate::client_version_to_whole();
|
||||
info!(client_version, "models cache: evaluating cache eligibility");
|
||||
let Some(identity) = self.endpoint_client.identity() else {
|
||||
return false;
|
||||
};
|
||||
let identity = self.endpoint_client.identity()?;
|
||||
{
|
||||
let current = self.remote_models.read().await;
|
||||
// An access rejection must not be replaced by stale cache data if invalidation failed.
|
||||
if current.entry.fetched_at == DateTime::<Utc>::MIN_UTC
|
||||
&& current.entry.identity.as_ref() == Some(&identity)
|
||||
{
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let cache_entry = match cache.load(&client_version).await {
|
||||
let (cache_entry, layer) = match cache.load_with_source(&client_version).await {
|
||||
Ok(Some(cache_entry)) => cache_entry,
|
||||
Ok(None) => {
|
||||
info!("models cache: no usable cache entry");
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("failed to load models cache: {err}");
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if cache_entry.fetched_at == DateTime::<Utc>::MIN_UTC {
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
if cache_entry.client_version.as_deref() != Some(client_version.as_str()) {
|
||||
info!(
|
||||
@@ -1106,17 +1159,20 @@ impl OpenAiModelsManager {
|
||||
cached_version = ?cache_entry.client_version,
|
||||
"models cache: cache version mismatch"
|
||||
);
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
if cache_entry.identity.as_ref() != Some(&identity)
|
||||
|| self.endpoint_client.identity().as_ref() != Some(&identity)
|
||||
{
|
||||
info!("models cache: provider or auth identity mismatch");
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
let mut current = self.remote_models.write().await;
|
||||
(mode == CatalogLoadMode::Initialize && self.catalog_is_initialized(¤t))
|
||||
|| self.apply_remote_models(&mut current, cache_entry, mode)
|
||||
if mode == CatalogLoadMode::Initialize && self.catalog_is_initialized(¤t) {
|
||||
return Some(Resolution::Snapshot);
|
||||
}
|
||||
self.apply_remote_models(&mut current, cache_entry, mode)
|
||||
.then_some(Resolution::Cached(layer, current.generation))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -100,6 +100,7 @@ fn assert_models_contain(actual: &[ModelInfo], expected: &[ModelInfo]) {
|
||||
#[derive(Debug, Default)]
|
||||
struct TestModelsEndpoint {
|
||||
has_command_auth: bool,
|
||||
supports_gateway_catalog: bool,
|
||||
uses_codex_backend: bool,
|
||||
responses: Mutex<VecDeque<CoreResult<Vec<ModelInfo>>>>,
|
||||
etag: Option<String>,
|
||||
@@ -287,6 +288,10 @@ impl ModelsEndpointClient for TestModelsEndpoint {
|
||||
true
|
||||
}
|
||||
|
||||
fn supports_gateway_catalog(&self) -> bool {
|
||||
self.supports_gateway_catalog
|
||||
}
|
||||
|
||||
fn identity(&self) -> Option<String> {
|
||||
Some("test-provider".to_string())
|
||||
}
|
||||
@@ -2031,3 +2036,108 @@ fn bundled_models_json_roundtrips() {
|
||||
"bundled models.json should contain at least one model"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_lookup_records_one_final_outcome_per_caller() {
|
||||
let endpoint =
|
||||
TestModelsEndpoint::with_command_auth(vec![Ok(Vec::new()), Err(CodexErr::RequestTimeout)]);
|
||||
let manager = OpenAiModelsManager::new_with_cache(
|
||||
Arc::new(TestModelsCache::default()),
|
||||
endpoint.clone(),
|
||||
/*auth_manager*/ None,
|
||||
)
|
||||
.with_provider_catalog();
|
||||
let http = DEFAULT_HTTP_CLIENT_FACTORY;
|
||||
let outcomes = crate::lookup::observe(async {
|
||||
manager
|
||||
.list_models(RefreshStrategy::Offline, http.clone())
|
||||
.await;
|
||||
CatalogLookupPurpose::ColdResume
|
||||
.scope(async {
|
||||
manager
|
||||
.list_models(RefreshStrategy::OnlineIfUncached, http.clone())
|
||||
.await;
|
||||
manager.ensure_initialized(http.clone()).await;
|
||||
})
|
||||
.await;
|
||||
CatalogLookupPurpose::Warmup
|
||||
.scope(manager.raw_model_catalog(RefreshStrategy::OnlineIfUncached, http.clone()))
|
||||
.await;
|
||||
manager
|
||||
.list_models(RefreshStrategy::Online, http.clone())
|
||||
.await;
|
||||
manager.get_remote_models().await;
|
||||
manager.try_list_models().unwrap();
|
||||
let _lock = manager.remote_models.write().await;
|
||||
manager.try_list_models().unwrap_err();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
outcomes,
|
||||
vec![
|
||||
("fallback", "fallback", "foreground"),
|
||||
("miss", "endpoint", "cold_resume"),
|
||||
("hit", "core_memory", "cold_resume"),
|
||||
("hit", "other_cache", "warmup"),
|
||||
("error", "core_memory", "foreground"),
|
||||
("hit", "core_memory", "foreground"),
|
||||
("hit", "core_memory", "foreground"),
|
||||
("error", "none", "foreground"),
|
||||
]
|
||||
);
|
||||
assert_eq!(endpoint.fetch_count(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unavailable_gateway_catalog_records_error_with_bundled_fallback() {
|
||||
let endpoint = Arc::new(TestModelsEndpoint {
|
||||
supports_gateway_catalog: true,
|
||||
responses: Mutex::new([Err(CodexErr::RequestTimeout)].into()),
|
||||
..TestModelsEndpoint::default()
|
||||
});
|
||||
let manager = OpenAiModelsManager::new_without_cache(endpoint, /*auth_manager*/ None);
|
||||
let outcomes = crate::lookup::observe(async {
|
||||
let catalog = manager
|
||||
.raw_model_catalog(
|
||||
RefreshStrategy::OnlineIfUncached,
|
||||
DEFAULT_HTTP_CLIENT_FACTORY,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(catalog.models, load_remote_models_from_file().unwrap());
|
||||
})
|
||||
.await;
|
||||
assert_eq!(outcomes, vec![("error", "fallback", "foreground")]);
|
||||
}
|
||||
|
||||
/// Interleave a second publication between loading a cache entry and selecting
|
||||
/// the snapshot for a caller. The first caller used the newer in-memory value.
|
||||
#[tokio::test]
|
||||
async fn catalog_lookup_attributes_a_replaced_snapshot_to_core_memory() {
|
||||
let home = tempdir().unwrap();
|
||||
let endpoint = TestModelsEndpoint::new(vec![Vec::new(), Vec::new()]);
|
||||
let cache = FileModelsCache::new(home.path().join(MODEL_CACHE_FILE), DEFAULT_MODEL_CACHE_TTL);
|
||||
let manager =
|
||||
OpenAiModelsManager::new_with_cache(Arc::new(cache), endpoint, /*auth_manager*/ None);
|
||||
let http = DEFAULT_HTTP_CLIENT_FACTORY;
|
||||
let mode = CatalogLoadMode::Refresh(RefreshStrategy::OnlineIfUncached);
|
||||
let fetched = manager.load_catalog(mode, &http).await.unwrap();
|
||||
let cached = manager.load_catalog(mode, &http).await.unwrap();
|
||||
let rows = crate::lookup::observe(async {
|
||||
manager
|
||||
.list_models(RefreshStrategy::Offline, http.clone())
|
||||
.await;
|
||||
let state = manager.remote_models.read().await;
|
||||
let selected = manager.models_for_entry(&state.entry);
|
||||
cached.selected(&state, selected.selection).record();
|
||||
fetched.selected(&state, selected.selection).record();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
rows,
|
||||
vec![
|
||||
("hit", "disk", "foreground"),
|
||||
("hit", "core_memory", "foreground"),
|
||||
("miss", "core_memory", "foreground")
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ path = "src/lib.rs"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
arc-swap = { workspace = true }
|
||||
bytes = { workspace = true }
|
||||
codex-http-client = { workspace = true }
|
||||
opentelemetry-http = "0.31.0"
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! Standalone durations and count/duration pairs share admission limits and lifecycle handling.
|
||||
//! Shutting down the active installation resumes buffering until its replacement is ready.
|
||||
|
||||
use super::ActiveMetrics;
|
||||
use super::MetricsClient;
|
||||
use super::MetricsError;
|
||||
use super::Result;
|
||||
@@ -25,7 +26,10 @@ struct PendingOperation {
|
||||
|
||||
enum State {
|
||||
Startup(Vec<PendingOperation>),
|
||||
Ready(MetricsClient),
|
||||
Ready {
|
||||
destination: MetricsClient,
|
||||
active: Option<ActiveMetrics>,
|
||||
},
|
||||
Disabled,
|
||||
}
|
||||
|
||||
@@ -116,7 +120,9 @@ impl BufferedMetrics {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
State::Ready(metrics) => record(metrics, count_name, duration_name, duration, tags),
|
||||
State::Ready { destination, .. } => {
|
||||
record(destination, count_name, duration_name, duration, tags)
|
||||
}
|
||||
State::Disabled => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -126,6 +132,10 @@ impl BufferedMetrics {
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let active = metrics.active.clone();
|
||||
if let Some(active) = &active {
|
||||
active.store(Some(Arc::clone(&metrics.inner)));
|
||||
}
|
||||
// Bind to this installation so a provider replacement cannot split a pair
|
||||
// between exporters through the redirectable global MetricsClient handle.
|
||||
let metrics = MetricsClient {
|
||||
@@ -148,14 +158,33 @@ impl BufferedMetrics {
|
||||
);
|
||||
}
|
||||
}
|
||||
*state = State::Ready(metrics);
|
||||
*state = State::Ready {
|
||||
destination: metrics,
|
||||
active,
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn disable(&self) {
|
||||
*self
|
||||
pub(crate) fn disable(&self, owner: Option<&MetricsClient>) {
|
||||
let mut state = self
|
||||
.state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = State::Disabled;
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
match (&*state, owner) {
|
||||
(State::Startup(_), None) => *state = State::Disabled,
|
||||
(
|
||||
State::Ready {
|
||||
destination,
|
||||
active,
|
||||
},
|
||||
Some(owner),
|
||||
) if Arc::ptr_eq(&owner.inner, &destination.inner) => {
|
||||
if let Some(active) = active {
|
||||
active.store(/*val*/ None);
|
||||
}
|
||||
*state = State::Disabled;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn suspend(&self, metrics: &MetricsClient) {
|
||||
@@ -165,9 +194,15 @@ impl BufferedMetrics {
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
// A replaced provider may shut down after its successor is installed.
|
||||
// It must neither detach that successor nor undo an explicit opt-out.
|
||||
if let State::Ready(current) = &*state
|
||||
&& Arc::ptr_eq(¤t.inner, &metrics.inner)
|
||||
if let State::Ready {
|
||||
destination,
|
||||
active,
|
||||
} = &*state
|
||||
&& Arc::ptr_eq(&destination.inner, &metrics.inner)
|
||||
{
|
||||
if let Some(active) = active {
|
||||
active.store(/*val*/ None);
|
||||
}
|
||||
*state = State::Startup(Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::*;
|
||||
use crate::MetricsConfig;
|
||||
use arc_swap::ArcSwapOption;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Barrier;
|
||||
use std::sync::RwLock;
|
||||
|
||||
fn client() -> MetricsClient {
|
||||
MetricsClient::new(
|
||||
@@ -143,7 +143,7 @@ fn standalone_durations_share_startup_limits_and_opt_out() {
|
||||
let metrics = client();
|
||||
buffer.enable(&metrics);
|
||||
assert_eq!(totals(&metrics), (0, 256, 1792.0));
|
||||
buffer.disable();
|
||||
buffer.disable(Some(&metrics));
|
||||
buffer
|
||||
.record(
|
||||
/*count_name*/ None,
|
||||
@@ -169,14 +169,14 @@ fn standalone_durations_share_startup_limits_and_opt_out() {
|
||||
fn opt_out_discards_pending_and_live_observations_until_reenabled() {
|
||||
let buffer = BufferedMetrics::new();
|
||||
observe(&buffer);
|
||||
buffer.disable();
|
||||
buffer.disable(/*owner*/ None);
|
||||
observe(&buffer);
|
||||
let first = client();
|
||||
buffer.enable(&first);
|
||||
assert_eq!(totals(&first), (0, 0, 0.0));
|
||||
observe(&buffer);
|
||||
assert_eq!(totals(&first), (1, 1, 7.0));
|
||||
buffer.disable();
|
||||
buffer.disable(Some(&first));
|
||||
observe(&buffer);
|
||||
assert_eq!(totals(&first), (0, 0, 0.0));
|
||||
let second = client();
|
||||
@@ -219,13 +219,13 @@ fn redirecting_a_global_handle_does_not_change_the_buffers_installation() {
|
||||
let buffer = BufferedMetrics::new();
|
||||
let first = client();
|
||||
let second = client();
|
||||
let active = Arc::new(RwLock::new(Arc::clone(&first.inner)));
|
||||
let active = Arc::new(ArcSwapOption::from(Some(Arc::clone(&first.inner))));
|
||||
let redirected = MetricsClient {
|
||||
inner: Arc::clone(&first.inner),
|
||||
active: Some(Arc::clone(&active)),
|
||||
};
|
||||
buffer.enable(&redirected);
|
||||
*active.write().unwrap() = Arc::clone(&second.inner);
|
||||
active.store(Some(Arc::clone(&second.inner)));
|
||||
observe(&buffer);
|
||||
assert_eq!(totals(&first), (1, 1, 7.0));
|
||||
assert_eq!(totals(&second), (0, 0, 0.0));
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
//! Counts catalog reads without taking an instrument or exporter lock on the caller's thread.
|
||||
//! At collection, pending lookups feed a counter shared by the periodic and runtime readers.
|
||||
|
||||
use opentelemetry::KeyValue;
|
||||
use opentelemetry::metrics::Meter;
|
||||
use std::collections::BTreeMap;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
pub(super) const METRIC: &str = "codex.remote_models.lookup.outcome";
|
||||
// The same definitions select the atomic slot at record time and label it at collection time.
|
||||
macro_rules! catalog_dimension {
|
||||
(
|
||||
$(#[$meta:meta])* $name:ident {
|
||||
$($(#[$variant_meta:meta])* $variant:ident => $label:literal),+ $(,)?
|
||||
}
|
||||
) => {
|
||||
$(#[$meta])*
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum $name {
|
||||
$($(#[$variant_meta])* $variant),+
|
||||
}
|
||||
|
||||
impl $name {
|
||||
const LABELS: &'static [&'static str] = &[$($label),+];
|
||||
|
||||
pub fn as_str(self) -> &'static str {
|
||||
Self::LABELS[self as usize]
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
catalog_dimension! {
|
||||
/// The operation driving a catalog request. Re-enter the scope in spawned work.
|
||||
#[derive(Default)]
|
||||
CatalogLookupPurpose {
|
||||
#[default]
|
||||
Foreground => "foreground",
|
||||
ThreadStart => "thread_start",
|
||||
ColdResume => "cold_resume",
|
||||
Warmup => "warmup",
|
||||
Maintenance => "maintenance",
|
||||
}
|
||||
}
|
||||
|
||||
catalog_dimension! {
|
||||
CatalogLookupResult {
|
||||
Hit => "hit",
|
||||
Miss => "miss",
|
||||
Bypass => "bypass",
|
||||
Error => "error",
|
||||
Fallback => "fallback",
|
||||
}
|
||||
}
|
||||
|
||||
catalog_dimension! {
|
||||
CatalogLookupSource {
|
||||
CoreMemory => "core_memory",
|
||||
StartupMemory => "startup_memory",
|
||||
SharedCache => "shared_cache",
|
||||
Disk => "disk",
|
||||
OtherCache => "other_cache",
|
||||
Endpoint => "endpoint",
|
||||
Fallback => "fallback",
|
||||
None => "none",
|
||||
}
|
||||
}
|
||||
|
||||
tokio::task_local! {
|
||||
static PURPOSE: CatalogLookupPurpose;
|
||||
static EXPECTED_ENDPOINT: String;
|
||||
}
|
||||
|
||||
impl CatalogLookupPurpose {
|
||||
pub async fn scope<F: Future>(self, future: F) -> F::Output {
|
||||
PURPOSE.scope(self, future).await
|
||||
}
|
||||
|
||||
/// Attribute catalog GETs to the host application's configured endpoint.
|
||||
/// The endpoint is compared locally and never emitted as a metric label.
|
||||
pub async fn scope_with_endpoint<F: Future>(self, endpoint: String, future: F) -> F::Output {
|
||||
EXPECTED_ENDPOINT.scope(endpoint, self.scope(future)).await
|
||||
}
|
||||
|
||||
pub fn dispatch_target(matches_endpoint: impl FnOnce(&str) -> bool) -> &'static str {
|
||||
match EXPECTED_ENDPOINT.try_with(|expected| matches_endpoint(expected)) {
|
||||
Ok(true) => "configured",
|
||||
Ok(false) => "other",
|
||||
Err(_) => "unclassified",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn current() -> Self {
|
||||
PURPOSE.try_with(|p| *p).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct CatalogLookups {
|
||||
pending: [[[AtomicU64; CatalogLookupSource::LABELS.len()]; CatalogLookupResult::LABELS.len()];
|
||||
CatalogLookupPurpose::LABELS.len()],
|
||||
}
|
||||
|
||||
impl CatalogLookups {
|
||||
pub(super) fn register(meter: &Meter, default_tags: &BTreeMap<String, String>) -> Arc<Self> {
|
||||
let counters = Arc::new(Self::default());
|
||||
let observed = Arc::clone(&counters);
|
||||
let default_tags: Vec<_> = default_tags
|
||||
.iter()
|
||||
.filter(|(key, _)| !matches!(key.as_str(), "purpose" | "outcome" | "source"))
|
||||
.map(|(key, value)| KeyValue::new(key.clone(), value.clone()))
|
||||
.collect();
|
||||
let counter = meter.u64_counter(METRIC).build();
|
||||
// Either reader can trigger collection. Draining once into a synchronous counter gives
|
||||
// each reader its own aggregation and leaves idle delta collections empty. The callback
|
||||
// instrument only schedules the drain and never publishes a measurement of its own.
|
||||
let _collection_hook = meter
|
||||
.u64_observable_counter("codex.remote_models.lookup.collect")
|
||||
.with_callback(move |_| {
|
||||
let mut tags = default_tags.clone();
|
||||
for (purpose, outcomes) in
|
||||
CatalogLookupPurpose::LABELS.iter().zip(&observed.pending)
|
||||
{
|
||||
for (outcome, sources) in CatalogLookupResult::LABELS.iter().zip(outcomes) {
|
||||
for (source, count) in CatalogLookupSource::LABELS.iter().zip(sources) {
|
||||
let delta = count.swap(/*val*/ 0, Ordering::Relaxed);
|
||||
if delta > 0 {
|
||||
tags.truncate(default_tags.len());
|
||||
tags.extend([
|
||||
KeyValue::new("purpose", *purpose),
|
||||
KeyValue::new("outcome", *outcome),
|
||||
KeyValue::new("source", *source),
|
||||
]);
|
||||
counter.add(delta, &tags);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.build();
|
||||
counters
|
||||
}
|
||||
|
||||
pub(super) fn record(
|
||||
&self,
|
||||
purpose: CatalogLookupPurpose,
|
||||
outcome: CatalogLookupResult,
|
||||
source: CatalogLookupSource,
|
||||
) {
|
||||
self.pending[purpose as usize][outcome as usize][source as usize]
|
||||
.fetch_add(/*val*/ 1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
use super::ActiveMetrics;
|
||||
use crate::config::OtelExporter;
|
||||
use crate::config::OtelHttpProtocol;
|
||||
use crate::config::StatsigMetricsSettings;
|
||||
use crate::headers_helper::HeadersHelper;
|
||||
use crate::metrics::MetricsError;
|
||||
use crate::metrics::Result;
|
||||
use crate::metrics::catalog_lookups::CatalogLookups;
|
||||
use crate::metrics::config::MetricsConfig;
|
||||
use crate::metrics::config::MetricsExporter;
|
||||
use crate::metrics::names::TURN_CRITICAL_PATH_COMPONENT_METRIC;
|
||||
@@ -50,7 +53,6 @@ use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::RwLock;
|
||||
use std::sync::Weak;
|
||||
use std::time::Duration;
|
||||
use tracing::debug;
|
||||
@@ -131,6 +133,7 @@ impl MetricReader for SharedManualReader {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct MetricsClientInner {
|
||||
pub(super) catalog_lookups: Option<Arc<CatalogLookups>>,
|
||||
pub(super) network_policy: codex_http_client::NetworkPolicy,
|
||||
meter_provider: SdkMeterProvider,
|
||||
meter: Meter,
|
||||
@@ -139,7 +142,7 @@ pub(super) struct MetricsClientInner {
|
||||
histograms: Mutex<HashMap<String, Histogram<f64>>>,
|
||||
duration_histograms: Mutex<HashMap<InstrumentKey, Histogram<f64>>>,
|
||||
runtime_reader: Option<Arc<ManualReader>>,
|
||||
requires_analytics_consent: bool,
|
||||
pub(super) statsig_settings: Option<StatsigMetricsSettings>,
|
||||
statsig_disabled_metrics: &'static [&'static str],
|
||||
default_tags: BTreeMap<String, String>,
|
||||
}
|
||||
@@ -348,7 +351,7 @@ pub struct MetricsClient {
|
||||
// Keep the original provider so its owner only shuts down its own exporter.
|
||||
pub(super) inner: Arc<MetricsClientInner>,
|
||||
// Installed clients share this slot, so existing clones follow account changes.
|
||||
pub(super) active: Option<Arc<RwLock<Arc<MetricsClientInner>>>>,
|
||||
pub(super) active: Option<ActiveMetrics>,
|
||||
}
|
||||
|
||||
impl MetricsClient {
|
||||
@@ -367,12 +370,17 @@ impl MetricsClient {
|
||||
exporter,
|
||||
export_interval,
|
||||
runtime_reader,
|
||||
statsig_disabled_metrics,
|
||||
statsig_settings,
|
||||
default_tags,
|
||||
} = config;
|
||||
|
||||
validate_tags(&default_tags)?;
|
||||
|
||||
let statsig_disabled_metrics = if statsig_settings.is_some() {
|
||||
super::config::STATSIG_DISABLED_METRICS
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
let mut resource_attributes = Vec::with_capacity(4);
|
||||
resource_attributes.push(KeyValue::new(
|
||||
semconv::attribute::SERVICE_VERSION,
|
||||
@@ -394,8 +402,6 @@ impl MetricsClient {
|
||||
)
|
||||
});
|
||||
|
||||
let requires_analytics_consent =
|
||||
matches!(exporter, MetricsExporter::Otlp(OtelExporter::Statsig));
|
||||
let (meter_provider, meter) = match exporter {
|
||||
MetricsExporter::InMemory(exporter) => {
|
||||
build_provider(resource, exporter, export_interval, runtime_reader.clone())
|
||||
@@ -418,8 +424,12 @@ impl MetricsClient {
|
||||
}
|
||||
};
|
||||
|
||||
let catalog_lookups = (!statsig_disabled_metrics.contains(&super::catalog_lookups::METRIC))
|
||||
.then(|| CatalogLookups::register(&meter, &default_tags));
|
||||
|
||||
Ok(Self {
|
||||
inner: Arc::new(MetricsClientInner {
|
||||
catalog_lookups,
|
||||
network_policy: http_client_factory.network_policy().clone(),
|
||||
meter_provider,
|
||||
meter,
|
||||
@@ -428,7 +438,7 @@ impl MetricsClient {
|
||||
histograms: Mutex::new(HashMap::new()),
|
||||
duration_histograms: Mutex::new(HashMap::new()),
|
||||
runtime_reader,
|
||||
requires_analytics_consent,
|
||||
statsig_settings,
|
||||
statsig_disabled_metrics,
|
||||
default_tags,
|
||||
}),
|
||||
@@ -436,20 +446,23 @@ impl MetricsClient {
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn active_inner(&self) -> Arc<MetricsClientInner> {
|
||||
fn active_inner(&self) -> Option<Arc<MetricsClientInner>> {
|
||||
match &self.active {
|
||||
Some(active) => active
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone(),
|
||||
None => Arc::clone(&self.inner),
|
||||
Some(active) => active.load_full(),
|
||||
None => Some(Arc::clone(&self.inner)),
|
||||
}
|
||||
}
|
||||
|
||||
fn record_if_active(
|
||||
&self,
|
||||
record: impl FnOnce(&MetricsClientInner) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
self.active_inner().map_or(Ok(()), |inner| record(&inner))
|
||||
}
|
||||
|
||||
/// Send a single counter increment.
|
||||
pub fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]) -> Result<()> {
|
||||
self.active_inner()
|
||||
.counter(name, /*description*/ None, inc, tags)
|
||||
self.record_if_active(|inner| inner.counter(name, /*description*/ None, inc, tags))
|
||||
}
|
||||
|
||||
/// Record a counter while applying analytics consent only to the built-in exporter.
|
||||
@@ -461,8 +474,10 @@ impl MetricsClient {
|
||||
tags: &[(&str, &str)],
|
||||
analytics_enabled: bool,
|
||||
) -> Result<()> {
|
||||
let inner = self.active_inner();
|
||||
if inner.requires_analytics_consent && !analytics_enabled {
|
||||
let Some(inner) = self.active_inner() else {
|
||||
return Ok(());
|
||||
};
|
||||
if inner.statsig_settings.is_some() && !analytics_enabled {
|
||||
return Ok(());
|
||||
}
|
||||
inner.counter(name, /*description*/ None, inc, tags)
|
||||
@@ -476,14 +491,12 @@ impl MetricsClient {
|
||||
inc: i64,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner()
|
||||
.counter(name, Some(description), inc, tags)
|
||||
self.record_if_active(|inner| inner.counter(name, Some(description), inc, tags))
|
||||
}
|
||||
|
||||
/// Send a single histogram sample.
|
||||
pub fn histogram(&self, name: &str, value: i64, tags: &[(&str, &str)]) -> Result<()> {
|
||||
self.active_inner()
|
||||
.histogram(name, value, /*boundaries*/ None, tags)
|
||||
self.record_if_active(|inner| inner.histogram(name, value, /*boundaries*/ None, tags))
|
||||
}
|
||||
|
||||
/// Send a single histogram sample using explicit bucket boundaries.
|
||||
@@ -494,14 +507,12 @@ impl MetricsClient {
|
||||
boundaries: &[f64],
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner()
|
||||
.histogram(name, value, Some(boundaries), tags)
|
||||
self.record_if_active(|inner| inner.histogram(name, value, Some(boundaries), tags))
|
||||
}
|
||||
|
||||
/// Send a single gauge measurement.
|
||||
pub fn gauge(&self, name: &str, value: i64, tags: &[(&str, &str)]) -> Result<()> {
|
||||
self.active_inner()
|
||||
.gauge(name, /*description*/ None, value, tags)
|
||||
self.record_if_active(|inner| inner.gauge(name, /*description*/ None, value, tags))
|
||||
}
|
||||
|
||||
/// Send a single gauge measurement with an instrument description.
|
||||
@@ -512,8 +523,7 @@ impl MetricsClient {
|
||||
value: i64,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner()
|
||||
.gauge(name, Some(description), value, tags)
|
||||
self.record_if_active(|inner| inner.gauge(name, Some(description), value, tags))
|
||||
}
|
||||
|
||||
/// Register a gauge callback that reports the current value on every collection.
|
||||
@@ -524,8 +534,9 @@ impl MetricsClient {
|
||||
observe: impl Fn() -> i64 + Send + Sync + 'static,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner()
|
||||
.register_observable_gauge(name, description, observe, tags)
|
||||
self.record_if_active(|inner| {
|
||||
inner.register_observable_gauge(name, description, observe, tags)
|
||||
})
|
||||
}
|
||||
|
||||
/// Record a duration in milliseconds using a histogram.
|
||||
@@ -535,19 +546,21 @@ impl MetricsClient {
|
||||
duration: Duration,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner().duration_histogram(
|
||||
name,
|
||||
duration.as_millis().min(i64::MAX as u128) as f64,
|
||||
MILLISECOND_DURATION_UNIT,
|
||||
MILLISECOND_DURATION_DESCRIPTION,
|
||||
match name {
|
||||
TURN_CRITICAL_PATH_DURATION_METRIC | TURN_CRITICAL_PATH_COMPONENT_METRIC => {
|
||||
&TURN_CRITICAL_PATH_DURATION_BOUNDARIES
|
||||
}
|
||||
_ => MILLISECOND_DURATION_BOUNDARIES,
|
||||
},
|
||||
tags,
|
||||
)
|
||||
self.record_if_active(|inner| {
|
||||
inner.duration_histogram(
|
||||
name,
|
||||
duration.as_millis().min(i64::MAX as u128) as f64,
|
||||
MILLISECOND_DURATION_UNIT,
|
||||
MILLISECOND_DURATION_DESCRIPTION,
|
||||
match name {
|
||||
TURN_CRITICAL_PATH_DURATION_METRIC | TURN_CRITICAL_PATH_COMPONENT_METRIC => {
|
||||
&TURN_CRITICAL_PATH_DURATION_BOUNDARIES
|
||||
}
|
||||
_ => MILLISECOND_DURATION_BOUNDARIES,
|
||||
},
|
||||
tags,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Record a duration supplied as fractional milliseconds using a histogram.
|
||||
@@ -557,14 +570,16 @@ impl MetricsClient {
|
||||
duration_ms: f64,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner().duration_histogram(
|
||||
name,
|
||||
duration_ms,
|
||||
MILLISECOND_DURATION_UNIT,
|
||||
MILLISECOND_DURATION_DESCRIPTION,
|
||||
MILLISECOND_DURATION_BOUNDARIES,
|
||||
tags,
|
||||
)
|
||||
self.record_if_active(|inner| {
|
||||
inner.duration_histogram(
|
||||
name,
|
||||
duration_ms,
|
||||
MILLISECOND_DURATION_UNIT,
|
||||
MILLISECOND_DURATION_DESCRIPTION,
|
||||
MILLISECOND_DURATION_BOUNDARIES,
|
||||
tags,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Record a duration in seconds using a histogram with an instrument description.
|
||||
@@ -575,14 +590,16 @@ impl MetricsClient {
|
||||
duration: Duration,
|
||||
tags: &[(&str, &str)],
|
||||
) -> Result<()> {
|
||||
self.active_inner().duration_histogram(
|
||||
name,
|
||||
duration.as_secs_f64(),
|
||||
SECOND_DURATION_UNIT,
|
||||
description,
|
||||
SECOND_DURATION_BOUNDARIES,
|
||||
tags,
|
||||
)
|
||||
self.record_if_active(|inner| {
|
||||
inner.duration_histogram(
|
||||
name,
|
||||
duration.as_secs_f64(),
|
||||
SECOND_DURATION_UNIT,
|
||||
description,
|
||||
SECOND_DURATION_BOUNDARIES,
|
||||
tags,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn start_timer(
|
||||
@@ -595,7 +612,9 @@ impl MetricsClient {
|
||||
|
||||
/// Collect a runtime metrics snapshot without shutting down the provider.
|
||||
pub fn snapshot(&self) -> Result<ResourceMetrics> {
|
||||
let inner = self.active_inner();
|
||||
let inner = self
|
||||
.active_inner()
|
||||
.ok_or(MetricsError::RuntimeSnapshotUnavailable)?;
|
||||
let Some(reader) = &inner.runtime_reader else {
|
||||
return Err(MetricsError::RuntimeSnapshotUnavailable);
|
||||
};
|
||||
@@ -606,6 +625,12 @@ impl MetricsClient {
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
/// Stop recording into this installation immediately when its owner reloads with metrics disabled.
|
||||
/// A newer installation, including an externally managed host exporter, keeps recording.
|
||||
pub fn disable_global_recording(&self) {
|
||||
super::buffered::GLOBAL.disable(Some(self));
|
||||
}
|
||||
|
||||
/// Flush metrics and stop the underlying OTEL meter provider.
|
||||
pub fn shutdown(&self) -> Result<()> {
|
||||
super::buffered::GLOBAL.suspend(self);
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
//! Consent follows the actual counter destination across exporter replacements.
|
||||
|
||||
use super::*;
|
||||
use crate::CatalogLookupPurpose;
|
||||
use crate::CatalogLookupResult;
|
||||
use crate::CatalogLookupSource;
|
||||
use arc_swap::ArcSwapOption;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use opentelemetry_sdk::metrics::data::ScopeMetrics;
|
||||
@@ -9,18 +13,14 @@ use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn counter_consent_uses_the_active_exporter() -> Result<()> {
|
||||
let mut builtin = MetricsClient::new(
|
||||
MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(),
|
||||
)?;
|
||||
// Use the existing in-memory exporter to observe the built-in consent policy without
|
||||
// contacting Statsig (the real Statsig exporter is disabled in debug builds).
|
||||
Arc::get_mut(&mut builtin.inner)
|
||||
.expect("unique provider")
|
||||
.requires_analytics_consent = true;
|
||||
let mut config =
|
||||
MetricsConfig::otlp("test", "test", "1", OtelExporter::Statsig).with_runtime_reader();
|
||||
config.exporter = MetricsExporter::InMemory(Default::default());
|
||||
let builtin = MetricsClient::new(config)?;
|
||||
let custom = MetricsClient::new(
|
||||
MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(),
|
||||
)?;
|
||||
let active = Arc::new(RwLock::new(Arc::clone(&builtin.inner)));
|
||||
let active = Arc::new(ArcSwapOption::from(Some(Arc::clone(&builtin.inner))));
|
||||
let metrics = MetricsClient {
|
||||
inner: Arc::clone(&builtin.inner),
|
||||
active: Some(Arc::clone(&active)),
|
||||
@@ -35,7 +35,7 @@ fn counter_consent_uses_the_active_exporter() -> Result<()> {
|
||||
analytics_enabled,
|
||||
)?;
|
||||
}
|
||||
*active.write().unwrap() = Arc::clone(&custom.inner);
|
||||
active.store(Some(Arc::clone(&custom.inner)));
|
||||
metrics.counter_with_analytics_consent(
|
||||
"test.observations",
|
||||
/*inc*/ 1,
|
||||
@@ -55,3 +55,140 @@ fn counter_consent_uses_the_active_exporter() -> Result<()> {
|
||||
assert_eq!(counts, vec![1, 1]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_lookups_proceed_while_another_recorder_holds_the_instrument_mutex() -> Result<()> {
|
||||
let exporter = opentelemetry_sdk::metrics::InMemoryMetricExporter::default();
|
||||
let metrics = MetricsClient::new(
|
||||
MetricsConfig::in_memory("test", "test", "1", exporter.clone())
|
||||
.with_runtime_reader()
|
||||
.with_tag("host", "test-host")?,
|
||||
)?;
|
||||
let active = Arc::new(ArcSwapOption::from(Some(Arc::clone(&metrics.inner))));
|
||||
std::thread::scope(|scope| {
|
||||
let instruments = metrics.inner.counters.lock().unwrap();
|
||||
let (done, completed) = std::sync::mpsc::channel();
|
||||
for _ in 0..4 {
|
||||
let done = done.clone();
|
||||
let active = &active;
|
||||
scope.spawn(move || {
|
||||
for _ in 0..200 {
|
||||
crate::metrics::record_catalog_lookup_on(
|
||||
active,
|
||||
CatalogLookupPurpose::Foreground,
|
||||
CatalogLookupResult::Hit,
|
||||
CatalogLookupSource::CoreMemory,
|
||||
);
|
||||
crate::metrics::record_catalog_lookup_on(
|
||||
active,
|
||||
CatalogLookupPurpose::Foreground,
|
||||
CatalogLookupResult::Error,
|
||||
CatalogLookupSource::None,
|
||||
);
|
||||
}
|
||||
done.send(()).unwrap();
|
||||
});
|
||||
}
|
||||
for _ in 0..4 {
|
||||
completed
|
||||
.recv_timeout(Duration::from_secs(/*secs*/ 5))
|
||||
.expect("record while mutex is held");
|
||||
}
|
||||
drop(instruments);
|
||||
});
|
||||
let snapshot = metrics.snapshot()?;
|
||||
let metric = snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(ScopeMetrics::metrics)
|
||||
.next()
|
||||
.unwrap();
|
||||
assert_eq!(metric.name(), crate::metrics::catalog_lookups::METRIC);
|
||||
let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() else {
|
||||
panic!("expected an unsigned counter");
|
||||
};
|
||||
let mut rows = Vec::new();
|
||||
for point in sum.data_points() {
|
||||
let tags: BTreeMap<_, _> = point
|
||||
.attributes()
|
||||
.map(|tag| (tag.key.as_str(), tag.value.to_string()))
|
||||
.collect();
|
||||
rows.push((tags, point.value()));
|
||||
}
|
||||
rows.sort();
|
||||
let row = |outcome: &str, source: &str| {
|
||||
(
|
||||
BTreeMap::from([
|
||||
("host", "test-host".to_string()),
|
||||
("outcome", outcome.to_owned()),
|
||||
("purpose", "foreground".to_string()),
|
||||
("source", source.to_owned()),
|
||||
]),
|
||||
800,
|
||||
)
|
||||
};
|
||||
assert_eq!(rows, vec![row("error", "none"), row("hit", "core_memory")]);
|
||||
// The manual delta reader above must leave all counts available to the periodic exporter.
|
||||
metrics.inner.meter_provider.force_flush().unwrap();
|
||||
let batches = exporter.get_finished_metrics().unwrap();
|
||||
let mut counts: Vec<_> = batches
|
||||
.iter()
|
||||
.flat_map(ResourceMetrics::scope_metrics)
|
||||
.flat_map(ScopeMetrics::metrics)
|
||||
.filter_map(|metric| match metric.data() {
|
||||
AggregatedMetrics::U64(MetricData::Sum(sum)) => {
|
||||
Some(sum.data_points().map(SumDataPoint::value))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.collect();
|
||||
counts.sort_unstable();
|
||||
assert_eq!(counts, vec![800, 800]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delta_readers_skip_idle_catalog_lookups_and_resume_with_only_new_counts() -> Result<()> {
|
||||
let exporter = opentelemetry_sdk::metrics::InMemoryMetricExporterBuilder::new()
|
||||
.with_temporality(Temporality::Delta)
|
||||
.build();
|
||||
let metrics = MetricsClient::new(
|
||||
MetricsConfig::in_memory("test", "test", "1", exporter.clone()).with_runtime_reader(),
|
||||
)?;
|
||||
let lookups = metrics.inner.catalog_lookups.as_ref().unwrap();
|
||||
let values = |snapshot: &ResourceMetrics| {
|
||||
snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(ScopeMetrics::metrics)
|
||||
.flat_map(|metric| {
|
||||
assert_eq!(metric.name(), crate::metrics::catalog_lookups::METRIC);
|
||||
let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() else {
|
||||
panic!("expected an unsigned counter");
|
||||
};
|
||||
sum.data_points().map(SumDataPoint::value)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
for count in [2, 0, 1] {
|
||||
for _ in 0..count {
|
||||
lookups.record(
|
||||
CatalogLookupPurpose::Foreground,
|
||||
CatalogLookupResult::Hit,
|
||||
CatalogLookupSource::CoreMemory,
|
||||
);
|
||||
}
|
||||
let expected = if count == 0 { vec![] } else { vec![count] };
|
||||
metrics.inner.meter_provider.force_flush().unwrap();
|
||||
assert_eq!(values(&metrics.snapshot()?), expected);
|
||||
let batches = exporter.get_finished_metrics().unwrap();
|
||||
if count == 0 {
|
||||
assert!(batches.is_empty(), "idle processes should not export");
|
||||
} else {
|
||||
assert_eq!(batches.len(), 1);
|
||||
assert_eq!(values(&batches[0]), expected);
|
||||
}
|
||||
exporter.reset();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::config::OtelExporter;
|
||||
use crate::config::StatsigMetricsSettings;
|
||||
use crate::headers_helper::HeadersHelper;
|
||||
use crate::metrics::Result;
|
||||
use crate::metrics::names::API_CALL_COUNT_METRIC;
|
||||
@@ -22,7 +23,7 @@ const CONVERSATION_TURN_COUNT_METRIC: &str = "codex.conversation.turn.count";
|
||||
|
||||
// Metrics intentionally not sent through Codex's built-in Statsig route.
|
||||
// Keep this as an exact-name list so custom OTLP exporters still receive them.
|
||||
const STATSIG_DISABLED_METRICS: &[&str] = &[
|
||||
pub(super) const STATSIG_DISABLED_METRICS: &[&str] = &[
|
||||
API_CALL_COUNT_METRIC,
|
||||
API_CALL_DURATION_METRIC,
|
||||
CONVERSATION_TURN_COUNT_METRIC,
|
||||
@@ -53,7 +54,7 @@ pub struct MetricsConfig {
|
||||
pub(crate) exporter: MetricsExporter,
|
||||
pub(crate) export_interval: Option<Duration>,
|
||||
pub(crate) runtime_reader: bool,
|
||||
pub(crate) statsig_disabled_metrics: &'static [&'static str],
|
||||
pub(super) statsig_settings: Option<StatsigMetricsSettings>,
|
||||
pub(crate) default_tags: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
@@ -72,23 +73,23 @@ impl MetricsConfig {
|
||||
service_version: impl Into<String>,
|
||||
exporter: OtelExporter,
|
||||
) -> Self {
|
||||
let statsig_disabled_metrics = if matches!(exporter, OtelExporter::Statsig) {
|
||||
STATSIG_DISABLED_METRICS
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
let environment = environment.into();
|
||||
let statsig_settings =
|
||||
matches!(exporter, OtelExporter::Statsig).then(|| StatsigMetricsSettings {
|
||||
environment: environment.clone(),
|
||||
});
|
||||
Self {
|
||||
headers_helper: None,
|
||||
http_client_factory: codex_http_client::HttpClientFactory::new(
|
||||
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
),
|
||||
environment: environment.into(),
|
||||
environment,
|
||||
service_name: service_name.into(),
|
||||
service_version: service_version.into(),
|
||||
exporter: MetricsExporter::Otlp(exporter),
|
||||
export_interval: None,
|
||||
runtime_reader: false,
|
||||
statsig_disabled_metrics,
|
||||
statsig_settings,
|
||||
default_tags: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -111,7 +112,7 @@ impl MetricsConfig {
|
||||
exporter: MetricsExporter::InMemory(exporter),
|
||||
export_interval: None,
|
||||
runtime_reader: false,
|
||||
statsig_disabled_metrics: &[],
|
||||
statsig_settings: None,
|
||||
default_tags: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub(crate) mod buffered;
|
||||
mod catalog_lookups;
|
||||
mod client;
|
||||
mod config;
|
||||
mod error;
|
||||
@@ -9,54 +10,75 @@ pub(crate) mod tags;
|
||||
pub(crate) mod timer;
|
||||
pub(crate) mod validation;
|
||||
|
||||
use self::client::MetricsClientInner;
|
||||
use crate::config::StatsigMetricsSettings;
|
||||
pub use crate::metrics::buffered::record_global_duration;
|
||||
pub use crate::metrics::buffered::record_global_operation;
|
||||
pub use crate::metrics::catalog_lookups::CatalogLookupPurpose;
|
||||
pub use crate::metrics::catalog_lookups::CatalogLookupResult;
|
||||
pub use crate::metrics::catalog_lookups::CatalogLookupSource;
|
||||
pub use crate::metrics::client::MetricsClient;
|
||||
pub use crate::metrics::config::MetricsConfig;
|
||||
pub use crate::metrics::config::MetricsExporter;
|
||||
pub use crate::metrics::error::MetricsError;
|
||||
pub use crate::metrics::error::Result;
|
||||
pub use crate::metrics::process::record_process_start_once;
|
||||
use arc_swap::ArcSwapOption;
|
||||
pub use names::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::RwLock;
|
||||
pub use tags::ORIGINATOR_TAG;
|
||||
pub use tags::SessionMetricTagValues;
|
||||
pub use tags::bounded_originator_tag_value;
|
||||
|
||||
static GLOBAL_METRICS: OnceLock<MetricsClient> = OnceLock::new();
|
||||
static GLOBAL_STATSIG_METRICS_SETTINGS: OnceLock<StatsigMetricsSettings> = OnceLock::new();
|
||||
type ActiveMetrics = Arc<ArcSwapOption<MetricsClientInner>>;
|
||||
|
||||
static GLOBAL_METRICS: OnceLock<ActiveMetrics> = OnceLock::new();
|
||||
|
||||
pub(crate) fn install_global(mut metrics: MetricsClient) -> MetricsClient {
|
||||
let active = GLOBAL_METRICS
|
||||
.get()
|
||||
.and_then(|current| current.active.clone())
|
||||
.unwrap_or_else(|| Arc::new(RwLock::new(Arc::clone(&metrics.inner))));
|
||||
*active
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::clone(&metrics.inner);
|
||||
metrics.active = Some(active);
|
||||
let _ = GLOBAL_METRICS.set(metrics.clone());
|
||||
let active = GLOBAL_METRICS.get_or_init(Default::default);
|
||||
metrics.active = Some(Arc::clone(active));
|
||||
buffered::GLOBAL.enable(&metrics);
|
||||
metrics
|
||||
}
|
||||
|
||||
pub fn global() -> Option<MetricsClient> {
|
||||
GLOBAL_METRICS.get().cloned()
|
||||
let active = GLOBAL_METRICS.get()?;
|
||||
Some(MetricsClient {
|
||||
inner: active.load_full()?,
|
||||
active: Some(Arc::clone(active)),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn install_global_statsig_settings(settings: StatsigMetricsSettings) {
|
||||
let _ = GLOBAL_STATSIG_METRICS_SETTINGS.set(settings);
|
||||
/// Count a completed catalog lookup on the current exporter without blocking a synchronous read.
|
||||
pub fn record_model_catalog_lookup(
|
||||
purpose: CatalogLookupPurpose,
|
||||
outcome: CatalogLookupResult,
|
||||
source: CatalogLookupSource,
|
||||
) {
|
||||
if let Some(active) = GLOBAL_METRICS.get() {
|
||||
record_catalog_lookup_on(active, purpose, outcome, source);
|
||||
}
|
||||
}
|
||||
|
||||
fn record_catalog_lookup_on(
|
||||
active: &ActiveMetrics,
|
||||
purpose: CatalogLookupPurpose,
|
||||
outcome: CatalogLookupResult,
|
||||
source: CatalogLookupSource,
|
||||
) {
|
||||
if let Some(inner) = active.load().as_ref()
|
||||
&& let Some(lookups) = &inner.catalog_lookups
|
||||
{
|
||||
lookups.record(purpose, outcome, source);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn global_statsig_settings() -> Option<StatsigMetricsSettings> {
|
||||
if GLOBAL_METRICS
|
||||
.get()
|
||||
.is_some_and(|metrics| metrics.active_inner().network_policy.is_managed())
|
||||
{
|
||||
let active = GLOBAL_METRICS.get()?.load();
|
||||
let inner = active.as_ref()?;
|
||||
if inner.network_policy.is_managed() {
|
||||
return None;
|
||||
}
|
||||
GLOBAL_STATSIG_METRICS_SETTINGS.get().cloned()
|
||||
inner.statsig_settings.clone()
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ mod exporters;
|
||||
use crate::config::OtelExporter;
|
||||
use crate::config::OtelHttpProtocol;
|
||||
use crate::config::OtelSettings;
|
||||
use crate::config::StatsigMetricsSettings;
|
||||
use crate::headers_helper::HeadersHelper;
|
||||
use crate::metrics::MetricsClient;
|
||||
use crate::metrics::MetricsConfig;
|
||||
@@ -213,6 +212,16 @@ impl OtelProvider {
|
||||
Self::try_new_with_exporters::<AllExporters>(settings)
|
||||
}
|
||||
|
||||
/// Apply the process owner's settings. A disabled configuration discards buffered startup
|
||||
/// operations. Constructing a secondary provider with `try_new` leaves that decision to its host.
|
||||
pub fn try_new_for_process(settings: &OtelSettings) -> Result<Option<Self>, Box<dyn Error>> {
|
||||
let provider = Self::try_new(settings)?;
|
||||
if provider.as_ref().and_then(Self::metrics).is_none() {
|
||||
crate::metrics::buffered::GLOBAL.disable(/*owner*/ None);
|
||||
}
|
||||
Ok(provider)
|
||||
}
|
||||
|
||||
/// Builds a provider for traces over OTLP/HTTP.
|
||||
/// Returns an error if any other signal or transport is configured.
|
||||
pub fn try_new_http_traces(settings: &OtelSettings) -> Result<Option<Self>, Box<dyn Error>> {
|
||||
@@ -249,7 +258,6 @@ impl OtelProvider {
|
||||
// Tracestate propagation is process-global; clear it when these
|
||||
// settings do not install an active provider.
|
||||
crate::trace_context::set_tracestate_entries(BTreeMap::new())?;
|
||||
crate::metrics::buffered::GLOBAL.disable();
|
||||
install_global_tracer_provider(/*tracer_provider*/ None);
|
||||
debug!("No OTEL exporter enabled in settings.");
|
||||
return Ok(None);
|
||||
@@ -353,13 +361,6 @@ impl OtelProvider {
|
||||
install_global_tracer_provider(provider.tracer_provider.clone());
|
||||
if let Some(metrics) = provider.metrics.as_mut() {
|
||||
*metrics = crate::metrics::install_global(metrics.clone());
|
||||
if matches!(settings.metrics_exporter, OtelExporter::Statsig) {
|
||||
crate::metrics::install_global_statsig_settings(StatsigMetricsSettings {
|
||||
environment: settings.environment.clone(),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
crate::metrics::buffered::GLOBAL.disable();
|
||||
}
|
||||
Ok(Some(provider))
|
||||
}
|
||||
@@ -818,34 +819,42 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn cached_global_metrics_follow_reinstalled_provider() -> Result<(), Box<dyn Error>> {
|
||||
let initial =
|
||||
crate::metrics::install_global(MetricsClient::new(MetricsConfig::in_memory(
|
||||
"test",
|
||||
"codex-test",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
InMemoryMetricExporter::default(),
|
||||
))?);
|
||||
crate::metrics::install_global_statsig_settings(StatsigMetricsSettings {
|
||||
environment: "test".to_string(),
|
||||
});
|
||||
assert!(crate::metrics::global_statsig_settings().is_some());
|
||||
let mut builtin = MetricsConfig::otlp(
|
||||
"test",
|
||||
"codex-test",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
OtelExporter::Statsig,
|
||||
);
|
||||
builtin.exporter = MetricsExporter::InMemory(InMemoryMetricExporter::default());
|
||||
let initial = crate::metrics::install_global(MetricsClient::new(builtin.clone())?);
|
||||
assert_eq!(
|
||||
crate::metrics::global_statsig_settings()
|
||||
.unwrap()
|
||||
.environment,
|
||||
"test"
|
||||
);
|
||||
let cached = crate::metrics::global().expect("initial global metrics client");
|
||||
initial.disable_global_recording();
|
||||
assert!(crate::metrics::global_statsig_settings().is_none());
|
||||
let custom = crate::metrics::install_global(MetricsClient::new(MetricsConfig::in_memory(
|
||||
"test",
|
||||
"custom",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
InMemoryMetricExporter::default(),
|
||||
))?);
|
||||
assert!(crate::metrics::global_statsig_settings().is_none());
|
||||
custom.shutdown()?;
|
||||
let controller = codex_http_client::NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
controller.publish(
|
||||
policy.revision(),
|
||||
codex_http_client::DestinationPolicy::Unrestricted,
|
||||
);
|
||||
let cached = crate::metrics::global().expect("initial global metrics client");
|
||||
|
||||
let exporter = InMemoryMetricExporter::default();
|
||||
builtin.exporter = MetricsExporter::InMemory(exporter.clone());
|
||||
let replacement = crate::metrics::install_global(MetricsClient::new(
|
||||
MetricsConfig::in_memory(
|
||||
"test",
|
||||
"codex-test",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
exporter.clone(),
|
||||
)
|
||||
.with_http_client_factory(
|
||||
builtin.with_http_client_factory(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
.with_network_policy(policy),
|
||||
),
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_otel::CatalogLookupPurpose;
|
||||
use codex_otel::CatalogLookupResult;
|
||||
use codex_otel::CatalogLookupSource;
|
||||
use codex_otel::MetricsClient;
|
||||
use codex_otel::MetricsConfig;
|
||||
use codex_otel::OtelExporter;
|
||||
@@ -10,6 +13,7 @@ use codex_otel::OtelProvider;
|
||||
use codex_otel::OtelSettings;
|
||||
use codex_otel::install_global_metrics;
|
||||
use codex_otel::record_global_operation;
|
||||
use codex_otel::record_model_catalog_lookup;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use pretty_assertions::assert_eq;
|
||||
@@ -99,7 +103,10 @@ fn rejected_opt_out_preserves_recording_and_accepted_opt_out_survives_shutdown()
|
||||
tracestate: BTreeMap::new(),
|
||||
};
|
||||
assert_eq!(
|
||||
OtelProvider::try_new(&settings).err().unwrap().to_string(),
|
||||
OtelProvider::try_new_for_process(&settings)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string(),
|
||||
"configured span attribute key must not be empty"
|
||||
);
|
||||
observe();
|
||||
@@ -107,20 +114,65 @@ fn rejected_opt_out_preserves_recording_and_accepted_opt_out_survives_shutdown()
|
||||
|
||||
metrics.shutdown().unwrap();
|
||||
observe();
|
||||
assert!(OtelProvider::try_new(&settings).is_err());
|
||||
assert!(OtelProvider::try_new_for_process(&settings).is_err());
|
||||
let replacement = install();
|
||||
assert_eq!(totals(&replacement), (1, 1, 7.0));
|
||||
replacement.shutdown().unwrap();
|
||||
|
||||
settings.span_attributes.clear();
|
||||
// A secondary signal provider can also start before the host: preserve its pending counts.
|
||||
observe();
|
||||
let _secondary = OtelProvider::try_new(&settings).unwrap();
|
||||
let host = install();
|
||||
assert_eq!(totals(&host), (1, 1, 7.0));
|
||||
host.shutdown().unwrap();
|
||||
observe();
|
||||
let _process = OtelProvider::try_new_for_process(&settings).unwrap();
|
||||
let host = install();
|
||||
assert_eq!(totals(&host), (0, 0, 0.0));
|
||||
host.shutdown().unwrap();
|
||||
|
||||
for trace_exporter in [settings.trace_exporter.clone(), OtelExporter::None] {
|
||||
let metrics = install();
|
||||
let original = MetricsClient::new(
|
||||
MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(),
|
||||
)
|
||||
.unwrap();
|
||||
let metrics = install_global_metrics(original.clone());
|
||||
settings.trace_exporter = trace_exporter;
|
||||
let _provider = OtelProvider::try_new(&settings).unwrap();
|
||||
metrics.shutdown().unwrap();
|
||||
// Constructing an unrelated log/trace-only provider leaves the host exporter live.
|
||||
observe();
|
||||
record_model_catalog_lookup(
|
||||
CatalogLookupPurpose::Foreground,
|
||||
CatalogLookupResult::Hit,
|
||||
CatalogLookupSource::CoreMemory,
|
||||
);
|
||||
assert_eq!(totals(&metrics), (2, 1, 7.0));
|
||||
|
||||
// Only the owner can accept a transition to disabled. New observations stop at this
|
||||
// boundary, even for handles cached before it and before asynchronous shutdown.
|
||||
let cached = codex_otel::global().unwrap();
|
||||
metrics.disable_global_recording();
|
||||
assert!(codex_otel::global().is_none());
|
||||
cached.counter("test.disabled", /*inc*/ 1, &[]).unwrap();
|
||||
record_model_catalog_lookup(
|
||||
CatalogLookupPurpose::Foreground,
|
||||
CatalogLookupResult::Hit,
|
||||
CatalogLookupSource::CoreMemory,
|
||||
);
|
||||
observe();
|
||||
assert_eq!(totals(&original), (0, 0, 0.0));
|
||||
let replacement = install();
|
||||
metrics.disable_global_recording();
|
||||
metrics.shutdown().unwrap();
|
||||
assert_eq!(totals(&replacement), (0, 0, 0.0));
|
||||
cached.counter("test.enabled", /*inc*/ 1, &[]).unwrap();
|
||||
record_model_catalog_lookup(
|
||||
CatalogLookupPurpose::Foreground,
|
||||
CatalogLookupResult::Hit,
|
||||
CatalogLookupSource::CoreMemory,
|
||||
);
|
||||
assert_eq!(totals(&replacement), (2, 0, 0.0));
|
||||
replacement.shutdown().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user