Skip shadow skill selection without a metrics client (#63832)

## Why

Shadow skill selection can rank skills even when no metrics client is
available to record the results.

## What changed

Create the shadow selection experiment only when a metrics client is
installed, and run it only when `shadow_selection_enabled` is also set.

## Testing

Add a regression test that enables shadow selection without a metrics
client and verifies that turns create no shadow selection state.

GitOrigin-RevId: 7913c039cb7b8135a4e7a776f47142e853dcf966
This commit is contained in:
Charlie Marsh
2026-11-25 05:48:26 +00:00
committed by copyberry
parent 3f65e9f131
commit 62f3c95af4
4 changed files with 62 additions and 36 deletions
+1 -1
View File
@@ -15,6 +15,6 @@ pub struct SkillsExtensionConfig {
pub bundled_skills_enabled: bool,
/// Whether cloud skills are discovered and exposed to the model.
pub cloud_skill_enabled: bool,
/// Whether cheap skill selectors run in shadow mode without changing prompt contents.
/// Whether to evaluate skill selectors in the background when a metrics client is installed.
pub shadow_selection_enabled: bool,
}
+7 -4
View File
@@ -77,7 +77,7 @@ struct SkillsExtension<C> {
providers: SkillProviders,
event_sink: Arc<dyn ExtensionEventSink>,
config_from_host: Arc<dyn Fn(&C) -> SkillsExtensionConfig + Send + Sync>,
shadow_selection: Arc<ShadowSelectionExperiment>,
shadow_selection: Option<Arc<ShadowSelectionExperiment>>,
}
#[derive(Default)]
@@ -376,14 +376,16 @@ where
}
let selected_entries = collect_explicit_skill_mentions(input.user_input, &catalog);
let shadow_selection_turn = if config.shadow_selection_enabled {
let shadow_selection_turn = if config.shadow_selection_enabled
&& let Some(experiment) = &self.shadow_selection
{
let mut shadow_catalog = catalog.clone();
if let Some(host_skills) = host_skills {
shadow_catalog.extend(host_skills.clone());
}
let shadow_selected_entries =
collect_explicit_skill_mentions(input.user_input, &shadow_catalog);
Some(self.shadow_selection.start(
Some(experiment.start(
&input,
shadow_catalog,
&shadow_selected_entries,
@@ -627,7 +629,8 @@ pub fn install_with_providers_and_metrics<C>(
providers,
event_sink: registry.event_sink(),
config_from_host: Arc::new(config_from_host),
shadow_selection: Arc::new(ShadowSelectionExperiment::new(metrics_client)),
shadow_selection: metrics_client
.map(|metrics| Arc::new(ShadowSelectionExperiment::new(metrics))),
});
registry.thread_lifecycle_contributor(extension.clone());
registry.turn_lifecycle_contributor(Arc::new(SkillTelemetry));
@@ -31,21 +31,35 @@ fn rank_buckets_distinguish_results_above_twenty() {
static RANKING_TESTS: Semaphore = Semaphore::const_new(1);
#[tokio::test]
async fn turn_input_and_history_advance_while_ranking_is_blocked()
-> Result<(), Box<dyn std::error::Error>> {
use std::collections::BTreeMap;
async fn turns_without_metrics_skip_shadow_selection() -> Result<(), Box<dyn std::error::Error>> {
contribute_turns(/*metrics*/ None).await
}
fn test_metrics() -> MetricsClient {
use codex_otel::MetricsConfig;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
MetricsClient::new(
MetricsConfig::in_memory(
"test",
"codex-skills-extension",
env!("CARGO_PKG_VERSION"),
InMemoryMetricExporter::default(),
)
.with_runtime_reader(),
)
.unwrap()
}
async fn contribute_turns(
metrics: Option<&MetricsClient>,
) -> Result<(), Box<dyn std::error::Error>> {
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::SkillInvocationInput;
use codex_extension_api::SkillInvocationKind;
use codex_extension_api::ThreadStartInput;
use codex_otel::MetricsConfig;
use codex_protocol::protocol::SessionSource;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use opentelemetry_sdk::metrics::data::ScopeMetrics;
use crate::SkillProviders;
use crate::SkillsExtensionConfig;
@@ -57,22 +71,11 @@ async fn turn_input_and_history_advance_while_ranking_is_blocked()
use crate::step_state::CatalogStatus;
use crate::step_state::SkillsStepState;
let _serial = RANKING_TESTS.acquire().await.unwrap();
let slots = RANKING_SLOTS.acquire_many(2).await?;
let metrics = MetricsClient::new(
MetricsConfig::in_memory(
"test",
"codex-skills-extension",
env!("CARGO_PKG_VERSION"),
InMemoryMetricExporter::default(),
)
.with_runtime_reader(),
)?;
let mut builder = ExtensionRegistryBuilder::new();
install_with_providers_and_metrics(
&mut builder,
SkillProviders::new(),
Some(metrics.clone()),
metrics.cloned(),
SkillsExtensionConfig::clone,
);
let registry = builder.build();
@@ -155,6 +158,16 @@ async fn turn_input_and_history_advance_while_ranking_is_blocked()
)
.await?;
assert!(fragments.is_empty());
let Some(metrics) = metrics else {
assert!(
thread_store
.get::<SkillsThreadState>()
.unwrap()
.shadow_selection_turn(turn_id)
.is_none()
);
continue;
};
tokio::task::yield_now().await;
// Synchronous ranking would emit run metrics despite the occupied budget;
// awaiting admission in contribute would instead time out above.
@@ -190,9 +203,24 @@ async fn turn_input_and_history_advance_while_ranking_is_blocked()
.snapshot()
);
}
Ok(())
}
#[tokio::test]
async fn turn_input_and_history_advance_while_ranking_is_blocked()
-> Result<(), Box<dyn std::error::Error>> {
use std::collections::BTreeMap;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use opentelemetry_sdk::metrics::data::ScopeMetrics;
let _serial = RANKING_TESTS.acquire().await.unwrap();
let slots = RANKING_SLOTS.acquire_many(2).await?;
let metrics = test_metrics();
contribute_turns(Some(&metrics)).await?;
// Both observers disappear before either ranking starts. Their queued unique
// invocations must still be scored against their own turn-start histories.
drop(thread_store);
drop(slots);
let mut runs = BTreeMap::new();
@@ -307,7 +335,7 @@ async fn ranking_budget_is_shared_and_held_until_blocking_work_finishes() {
started,
release: Mutex::new(releases),
})],
metrics_client: None,
metrics_client: test_metrics(),
});
let query = ShadowQuery {
text: "test".to_string(),
@@ -56,11 +56,11 @@ const REDUCTION_BPS_METRIC: &str = "codex.skills.shadow_selection.reduction_bps"
pub(crate) struct ShadowSelectionExperiment {
selectors: Vec<Box<dyn CheapSkillSelector>>,
metrics_client: Option<MetricsClient>,
metrics_client: MetricsClient,
}
impl ShadowSelectionExperiment {
pub(crate) fn new(metrics_client: Option<MetricsClient>) -> Self {
pub(crate) fn new(metrics_client: MetricsClient) -> Self {
Self {
selectors: vec![
Box::new(WeightedLexicalSkillSelector),
@@ -178,9 +178,6 @@ impl ShadowSelectionExperiment {
return;
}
};
let Some(metrics_client) = self.metrics_client.as_ref() else {
return;
};
while let Some(skill_resource) = invocations.recv().await {
for selection in &ranked_selections {
let rank = selection
@@ -194,7 +191,7 @@ impl ShadowSelectionExperiment {
("rank", rank_bucket(rank)),
("query_script", query_script),
];
let _ = metrics_client.counter(
let _ = self.metrics_client.counter(
"codex.skills.shadow_selection.invocation",
/*inc*/ 1,
&tags,
@@ -325,9 +322,7 @@ impl ShadowSelectionExperiment {
}
fn record_metrics(&self, observation: ShadowSelectionObservation<'_>) {
let Some(metrics_client) = self.metrics_client.as_ref() else {
return;
};
let metrics_client = &self.metrics_client;
let ShadowSelectionObservation {
method,
selection,