Avoid model lookups for thread metadata and goal updates (#63655)

## Why

A slow model lookup can delay thread metadata reads and goal updates even
though both operations have the settings and data they need locally.

## What changed

Use locally configured settings for app-server thread reads, enrichment,
and direct-input checks. The effective configuration snapshot still
validates the service tier against the selected model.

Record goal updates and emit their raw response events using an internal
submission ID without constructing a turn context.

## Testing

Add a regression test that gates model lookup and checks that the local
snapshot and goal recording complete without requesting model info. It
also checks that the goal event matches the history item and that the
effective snapshot filters out an unsupported service tier.

GitOrigin-RevId: 7d008edd775ae459a1fd1e3db79f38f2d9b5ca30
This commit is contained in:
Charlie Marsh
2026-11-24 14:52:00 +00:00
committed by copyberry
parent 53fe98bdc2
commit 3e6daebb48
7 changed files with 84 additions and 20 deletions
@@ -55,7 +55,7 @@ async fn enrich_loaded_thread(
let Ok(loaded_thread) = thread_manager.get_thread(thread_id).await else {
return;
};
let config_snapshot = loaded_thread.config_snapshot().await;
let config_snapshot = loaded_thread.configured_snapshot().await;
apply_live_thread_settings(thread, &loaded_thread, &config_snapshot);
if !matches!(
&thread.source,
@@ -23,7 +23,7 @@ pub(super) fn can_accept_direct_input(
pub(super) async fn ensure_direct_input_allowed(
thread: &CodexThread,
) -> Result<(), JSONRPCErrorError> {
let config_snapshot = thread.config_snapshot().await;
let config_snapshot = thread.configured_snapshot().await;
if !can_accept_direct_input(
thread.multi_agent_version(),
&config_snapshot.session_source,
@@ -3396,7 +3396,7 @@ impl ThreadRequestProcessor {
let persisted = self
.load_persisted_thread_for_read(thread_id, /*include_turns*/ false)
.await?;
let config_snapshot = loaded_thread.config_snapshot().await;
let config_snapshot = loaded_thread.configured_snapshot().await;
if include_turns && config_snapshot.ephemeral {
return Err(ThreadReadViewError::InvalidRequest(
"ephemeral threads do not support includeTurns".to_string(),
+7
View File
@@ -1407,6 +1407,13 @@ impl CodexThread {
.await
}
/// Captures local settings for thread views and input ownership checks.
/// The service tier is the configured selection. Use [`Self::config_snapshot`]
/// when the tier must be validated against the selected model.
pub async fn configured_snapshot(&self) -> ThreadConfigSnapshot {
self.session.configured_snapshot().await
}
pub async fn config_snapshot(&self) -> ThreadConfigSnapshot {
self.session.thread_config_snapshot().await
}
+13 -11
View File
@@ -2395,6 +2395,12 @@ impl Session {
.model
}
pub(crate) async fn configured_snapshot(&self) -> ThreadConfigSnapshot {
let state = self.state.lock().await;
let configuration = &state.session_configuration;
configuration.thread_config_snapshot(configuration.environments.clone())
}
pub(crate) async fn thread_config_snapshot(&self) -> ThreadConfigSnapshot {
self.resume_config_snapshot().await.0
}
@@ -4316,7 +4322,7 @@ impl Session {
{
mark_thread_memory_mode_polluted_if_external_context(self, turn_context, item).await;
}
self.send_raw_response_items(turn_context, &response_items)
self.send_raw_response_items(&turn_context.sub_id, &response_items)
.await;
Ok(recorded_through)
}
@@ -5186,19 +5192,15 @@ impl Session {
}
#[tracing::instrument(level = "trace", skip_all, fields(item_count = items.len()))]
async fn send_raw_response_items(&self, turn_context: &TurnContext, items: &[ResponseItem]) {
async fn send_raw_response_items(&self, sub_id: &str, items: &[ResponseItem]) {
for item in items {
self.services
.rollout_thread_trace
.record_history_item_accepted(
&turn_context.sub_id,
item,
/*source_tool_call_id*/ None,
);
self.send_event(
turn_context,
EventMsg::RawResponseItem(RawResponseItemEvent { item: item.clone() }),
)
.record_history_item_accepted(sub_id, item, /*source_tool_call_id*/ None);
self.send_event_raw(Event {
id: sub_id.to_owned(),
msg: EventMsg::RawResponseItem(RawResponseItemEvent { item: item.clone() }),
})
.await;
}
}
@@ -19,6 +19,7 @@ use codex_history::RetainedUserMessage;
use codex_history::RolloutItem;
use codex_protocol::models::ResponseItem;
use codex_thread_store::PersistContext;
use codex_utils_output_truncation::TruncationPolicy;
use tokio::sync::Semaphore;
use tokio::sync::watch;
use tokio::task::JoinHandle;
@@ -85,14 +86,12 @@ impl Session {
&self,
update: UserGoalUpdate,
) -> std::io::Result<()> {
// Goal metadata must not initialize a model step, even on a goal-first thread.
// Keep context construction off callers' stacks, including the TUI RPC dispatcher.
let context = Box::pin(self.new_inject_items_context()).await;
let sub_id = self.next_internal_sub_id();
// Earlier Code Mode messages may need the persistence lock before this can return.
let user_input_order = self.reserve_user_input_order().await;
let _guard = thread_settings::acquire_persistence_lock(self).await;
let mut item = ContextualUserFragment::into(update);
Self::stamp_response_item_for_history(&mut item, &context.sub_id);
Self::stamp_response_item_for_history(&mut item, &sub_id);
self.assign_missing_response_item_id(&mut item);
let mut item = ResponseItemEnvelope {
item,
@@ -117,9 +116,10 @@ impl Session {
.await?;
self.state.lock().await.history.record_annotated_items(
std::slice::from_mut(&mut item),
context.model_info().truncation_policy.into(),
// This is a user message. Only tool outputs use the truncation policy.
TruncationPolicy::Bytes(0),
);
self.send_raw_response_items(&context, std::slice::from_ref(&item.item))
self.send_raw_response_items(&sub_id, std::slice::from_ref(&item.item))
.await;
Ok(())
}
@@ -2,6 +2,7 @@ use super::*;
use crate::McpRefreshReason;
use crate::agents_md_manager::AgentsMdManager;
use crate::agents_md_manager::SessionInstructions;
use crate::context::UserGoalUpdate;
use crate::session::Submission;
use crate::session::handlers::submission_loop;
use crate::session::step_context::StepContext;
@@ -48,6 +49,7 @@ use codex_protocol::openai_models::ModelTokenBudgetConfig;
use codex_protocol::openai_models::ModelsResponse;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::TurnAbortReason;
use pretty_assertions::assert_eq;
@@ -418,6 +420,59 @@ impl ModelsManager for GatedModelsManager {
}
}
#[tokio::test]
async fn thread_metadata_and_goal_recording_do_not_resolve_the_selected_model() {
let (mut session, _) = make_session_and_context().await;
let (tx_event, rx_event) = async_channel::unbounded();
session.tx_event = tx_event;
let (models, lookup) = GatedModelsManager::new(activation_models());
session.services.models_manager = models;
let configuration = &mut session.state.get_mut().session_configuration;
let settings = Arc::make_mut(&mut configuration.step_settings);
settings.collaboration_mode = settings.collaboration_mode.with_updates(
Some(MODEL_B.to_owned()),
/*effort*/ None,
/*developer_instructions*/ None,
);
settings.service_tier = Some("unsupported".into());
// The first lookup of MODEL_B blocks until we release it.
let local = tokio::select! {
snapshot = session.configured_snapshot() => snapshot,
_ = lookup.started.notified() => panic!("thread metadata requested model info"),
};
assert_eq!(local.model, MODEL_B);
assert_eq!(local.service_tier.as_deref(), Some("unsupported"));
let update = UserGoalUpdate::Set {
objective: Some("Keep the existing tests".into()),
status: None,
};
tokio::select! {
result = session.record_user_goal_update(update) => result.expect("record goal"),
_ = lookup.started.notified() => panic!("goal recording requested model info"),
}
let event = rx_event.try_recv().expect("goal event");
let EventMsg::RawResponseItem(raw) = event.msg else {
panic!("expected raw goal instruction");
};
assert_eq!(raw.item.turn_id(), Some(event.id.as_str()));
assert!(
UserGoalUpdate::message_text(&raw.item)
.unwrap()
.contains("Keep the existing tests")
);
assert_eq!(
session.clone_history().await.raw_items().last(),
Some(&raw.item)
);
lookup.release();
let effective = session.thread_config_snapshot().await;
assert_eq!(effective.model, local.model);
assert_eq!(effective.service_tier, None);
}
struct ActivationFixture {
session: Arc<Session>,
turn: Arc<TurnContext>,