Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Measure deferred tool namespace fragments before and after truncation (#47873)

Matthew Zeng4021746a1568
diff --git a/codex-rs/core/src/context/world_state/tools.rs b/codex-rs/core/src/context/world_state/tools.rs
index f43c3420fd..2751d3fe1d 100644
--- a/codex-rs/core/src/context/world_state/tools.rs
+++ b/codex-rs/core/src/context/world_state/tools.rs
@@ -3,24 +3,43 @@ use super::WorldStateContextFragment;
use super::WorldStateSection;
use crate::context::ContextualUserFragment;
use crate::context::environment_context::push_xml_escaped_text;
+use codex_extension_api::ExtensionMetrics;
use codex_extension_api::RenderedWorldStateFragment;
+use codex_otel::CONTEXT_FRAGMENT_BYTES_BUCKETS;
+use codex_otel::THREAD_TOOLS_FRAGMENT_BYTES_METRIC;
+use codex_otel::THREAD_TOOLS_NAMESPACES_TOTAL_METRIC;
use codex_protocol::models::ContentItemKind;
use codex_protocol::protocol::TOOLS_CLOSE_TAG;
use codex_protocol::protocol::TOOLS_OPEN_TAG;
use std::collections::BTreeMap;
+use std::sync::Arc;
const MAX_RENDERED_FRAGMENT_BYTES: usize = 4 * 1024;
const MAX_NAMESPACE_DESCRIPTION_CHARS: usize = 250;
const OMITTED_LINE_RESERVE_BYTES: usize = 64;
/// Deferred tool namespaces visible to the model for one sampling step.
-#[derive(Debug, Default)]
pub(crate) struct ToolsState {
deferred_namespaces: BTreeMap<String, String>,
+ metrics: Arc<dyn ExtensionMetrics>,
+}
+
+struct FragmentSize {
+ namespaces: usize,
+ bytes: usize,
+}
+
+struct RenderedNamespaces {
+ body: String,
+ before: FragmentSize,
+ after: FragmentSize,
}
impl ToolsState {
- pub(crate) fn new(deferred_namespaces: impl IntoIterator<Item = (String, String)>) -> Self {
+ pub(crate) fn new(
+ deferred_namespaces: impl IntoIterator<Item = (String, String)>,
+ metrics: Arc<dyn ExtensionMetrics>,
+ ) -> Self {
Self {
deferred_namespaces: deferred_namespaces
.into_iter()
@@ -36,6 +55,7 @@ impl ToolsState {
(namespace, description)
})
.collect(),
+ metrics,
}
}
}
@@ -68,7 +88,7 @@ impl WorldStateSection for ToolsState {
return None;
}
- let body = match previous {
+ let rendered = match previous {
PreviousSectionState::Absent | PreviousSectionState::Unknown => {
render_namespace_groups(
&[("Deferred tool namespaces", &self.deferred_namespaces)],
@@ -98,11 +118,12 @@ impl WorldStateSection for ToolsState {
)
}
};
+ record_fragment_metrics(self.metrics.as_ref(), previous, &rendered);
Some(Box::new(WorldStateContextFragment {
fragment: RenderedWorldStateFragment::new(
"developer",
(TOOLS_OPEN_TAG, TOOLS_CLOSE_TAG),
- body,
+ rendered.body,
),
content_kind: ContentItemKind("tools.deferred_namespaces".to_string()),
}))
@@ -112,7 +133,7 @@ impl WorldStateSection for ToolsState {
fn render_namespace_groups(
groups: &[(&'static str, &BTreeMap<String, String>)],
current_is_empty: bool,
-) -> String {
+) -> RenderedNamespaces {
let body_budget =
MAX_RENDERED_FRAGMENT_BYTES.saturating_sub(TOOLS_OPEN_TAG.len() + TOOLS_CLOSE_TAG.len());
let empty_state = current_is_empty.then_some("No deferred tool namespaces remain.\n");
@@ -125,6 +146,11 @@ fn render_namespace_groups(
+ empty_state.map_or(0, str::len);
let mut remaining_entry_bytes = body_budget.saturating_sub(fixed_bytes);
let mut rendered = "\n".to_string();
+ let mut before = FragmentSize {
+ namespaces: 0,
+ bytes: TOOLS_OPEN_TAG.len() + TOOLS_CLOSE_TAG.len() + 1 + empty_state.map_or(0, str::len),
+ };
+ let mut kept = 0;
for (label, namespaces) in groups {
if namespaces.is_empty() {
@@ -132,9 +158,12 @@ fn render_namespace_groups(
}
rendered.push_str(label);
rendered.push_str(":\n");
+ before.namespaces += namespaces.len();
+ before.bytes += label.len() + ":\n".len();
let mut omitted = 0usize;
for (namespace, description) in *namespaces {
let entry = rendered_namespace(namespace, description);
+ before.bytes += entry.len();
if entry.len() <= remaining_entry_bytes {
remaining_entry_bytes -= entry.len();
rendered.push_str(&entry);
@@ -142,6 +171,7 @@ fn render_namespace_groups(
omitted += 1;
}
}
+ kept += namespaces.len() - omitted;
if omitted > 0 {
rendered.push_str("... ");
rendered.push_str(&omitted.to_string());
@@ -151,7 +181,14 @@ fn render_namespace_groups(
if let Some(empty_state) = empty_state {
rendered.push_str(empty_state);
}
- rendered
+ RenderedNamespaces {
+ before,
+ after: FragmentSize {
+ namespaces: kept,
+ bytes: TOOLS_OPEN_TAG.len() + rendered.len() + TOOLS_CLOSE_TAG.len(),
+ },
+ body: rendered,
+ }
}
fn rendered_namespace(namespace: &str, description: &str) -> String {
@@ -165,6 +202,32 @@ fn rendered_namespace(namespace: &str, description: &str) -> String {
rendered
}
+// Measures the rendered namespace block before/after the byte cap, after description normalization.
+fn record_fragment_metrics(
+ metrics: &dyn ExtensionMetrics,
+ previous: PreviousSectionState<'_, BTreeMap<String, String>>,
+ rendered: &RenderedNamespaces,
+) {
+ let kind = match previous {
+ PreviousSectionState::Absent | PreviousSectionState::Unknown => "snapshot",
+ PreviousSectionState::Known(_) => "delta",
+ };
+ for (stage, size) in [("before", &rendered.before), ("after", &rendered.after)] {
+ let tags = [("stage", stage), ("kind", kind)];
+ metrics.histogram(
+ THREAD_TOOLS_NAMESPACES_TOTAL_METRIC,
+ i64::try_from(size.namespaces).unwrap_or(i64::MAX),
+ &tags,
+ );
+ metrics.histogram_with_boundaries(
+ THREAD_TOOLS_FRAGMENT_BYTES_METRIC,
+ i64::try_from(size.bytes).unwrap_or(i64::MAX),
+ CONTEXT_FRAGMENT_BYTES_BUCKETS,
+ &tags,
+ );
+ }
+}
+
#[cfg(test)]
#[path = "tools_tests.rs"]
mod tests;
diff --git a/codex-rs/core/src/context/world_state/tools_tests.rs b/codex-rs/core/src/context/world_state/tools_tests.rs
index 5177832508..0e3ff92374 100644
--- a/codex-rs/core/src/context/world_state/tools_tests.rs
+++ b/codex-rs/core/src/context/world_state/tools_tests.rs
@@ -3,22 +3,30 @@ use super::MAX_RENDERED_FRAGMENT_BYTES;
use super::ToolsState;
use crate::context::world_state::PreviousSectionState;
use crate::context::world_state::WorldStateSection;
+use codex_extension_api::ExtensionMetrics;
+use codex_otel::THREAD_TOOLS_FRAGMENT_BYTES_METRIC;
+use codex_otel::THREAD_TOOLS_NAMESPACES_TOTAL_METRIC;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
+use std::sync::Arc;
+use std::sync::Mutex;
#[test]
fn renders_first_line_of_namespace_descriptions() {
- let tools = ToolsState::new([
- (
- "app".to_string(),
- " control the Codex App \nAdditional instructions.".to_string(),
- ),
- (
- "gmail".to_string(),
- "access your Google Gmail Account & labels".to_string(),
- ),
- ("hotline".to_string(), String::new()),
- ]);
+ let tools = ToolsState::new(
+ [
+ (
+ "app".to_string(),
+ " control the Codex App \nAdditional instructions.".to_string(),
+ ),
+ (
+ "gmail".to_string(),
+ "access your Google Gmail Account & labels".to_string(),
+ ),
+ ("hotline".to_string(), String::new()),
+ ],
+ Arc::new(RecordingMetrics::default()),
+ );
let rendered = tools
.render_diff(PreviousSectionState::Absent)
@@ -33,14 +41,20 @@ fn renders_first_line_of_namespace_descriptions() {
#[test]
fn renders_added_removed_and_updated_namespace_descriptions() {
- let tools = ToolsState::new([
- ("app".to_string(), "control the Codex App".to_string()),
- (
- "gmail".to_string(),
- "access your Google Gmail Account".to_string(),
- ),
- ]);
+ let metrics = Arc::new(RecordingMetrics::default());
+ let tools = ToolsState::new(
+ [
+ ("app".to_string(), "control the Codex App".to_string()),
+ ("kept".to_string(), "unchanged".to_string()),
+ (
+ "gmail".to_string(),
+ "access your Google Gmail Account".to_string(),
+ ),
+ ],
+ metrics.clone(),
+ );
let previous = BTreeMap::from([
+ ("kept".to_string(), "unchanged".to_string()),
("gmail".to_string(), "old Gmail description".to_string()),
(
"hotline".to_string(),
@@ -57,12 +71,27 @@ fn renders_added_removed_and_updated_namespace_descriptions() {
rendered,
"<tools>\nAdded deferred tool namespaces:\n- app: control the Codex App\n- gmail: access your Google Gmail Account\nRemoved deferred tool namespaces:\n- hotline: access hotline information\n</tools>"
);
+
+ // Delta samples count the emitted additions/removals, excluding unchanged entries.
+ assert_eq!(
+ metrics.take(),
+ expected_metrics("delta", (3, &rendered), (3, &rendered))
+ );
+ assert!(
+ tools
+ .render_diff(PreviousSectionState::Known(&tools.snapshot()))
+ .is_none()
+ );
+ assert!(metrics.take().is_empty());
}
#[test]
fn caps_namespace_descriptions_by_character_count() {
let description = "πŸ¦€".repeat(MAX_NAMESPACE_DESCRIPTION_CHARS + 1);
- let tools = ToolsState::new([("app".to_string(), description)]);
+ let tools = ToolsState::new(
+ [("app".to_string(), description)],
+ Arc::new(RecordingMetrics::default()),
+ );
assert_eq!(
tools.snapshot(),
@@ -75,13 +104,27 @@ fn caps_namespace_descriptions_by_character_count() {
#[test]
fn caps_rendered_tools_fragment_after_xml_escaping() {
- let tools = ToolsState::new((0..100).map(|index| {
- (
- format!("namespace_{index}"),
- "&".repeat(MAX_NAMESPACE_DESCRIPTION_CHARS),
- )
- }));
-
+ let metrics = Arc::new(RecordingMetrics::default());
+ let namespaces = (0..100)
+ .map(|index| {
+ (
+ format!("namespace_{index}"),
+ format!("{}\nsecond line", "η•Œ&<>'\"".repeat(100)),
+ )
+ })
+ .collect::<BTreeMap<_, _>>();
+ let normalized_entries = namespaces
+ .keys()
+ .map(|name| {
+ format!(
+ "- {name}: {}η•Œ&amp;&lt;&gt;\n",
+ "η•Œ&amp;&lt;&gt;&apos;&quot;".repeat(41)
+ )
+ })
+ .collect::<String>();
+ // Before the byte cap, after first-line/250-character description normalization.
+ let before = format!("<tools>\nDeferred tool namespaces:\n{normalized_entries}</tools>");
+ let tools = ToolsState::new(namespaces, metrics.clone());
let rendered = tools
.render_diff(PreviousSectionState::Absent)
.expect("tools state should render")
@@ -89,4 +132,71 @@ fn caps_rendered_tools_fragment_after_xml_escaping() {
assert!(rendered.len() <= MAX_RENDERED_FRAGMENT_BYTES);
assert!(rendered.contains(" additional namespaces omitted.\n"));
+ let included = rendered
+ .lines()
+ .filter(|line| line.starts_with("- "))
+ .count();
+ assert_eq!(
+ metrics.take(),
+ expected_metrics("snapshot", (100, &before), (included, &rendered))
+ );
+}
+
+#[derive(Default)]
+struct RecordingMetrics {
+ samples: Mutex<BTreeMap<(String, String, String), i64>>,
+}
+
+impl ExtensionMetrics for RecordingMetrics {
+ fn counter(&self, name: &str, _inc: i64, _tags: &[(&str, &str)]) {
+ panic!("unexpected counter: {name}");
+ }
+
+ fn histogram_with_boundaries(
+ &self,
+ name: &str,
+ value: i64,
+ _boundaries: &[f64],
+ tags: &[(&str, &str)],
+ ) {
+ self.histogram(name, value, tags);
+ }
+
+ fn histogram(&self, name: &str, value: i64, tags: &[(&str, &str)]) {
+ let [("stage", stage), ("kind", kind)] = tags else {
+ panic!("unexpected tags: {tags:?}")
+ };
+ self.samples.lock().expect("metric samples lock").insert(
+ (name.to_string(), (*stage).to_string(), (*kind).to_string()),
+ value,
+ );
+ }
+}
+
+impl RecordingMetrics {
+ fn take(&self) -> BTreeMap<(String, String, String), i64> {
+ std::mem::take(&mut *self.samples.lock().expect("metric samples lock"))
+ }
+}
+
+fn expected_metrics(
+ kind: &str,
+ before: (usize, &str),
+ after: (usize, &str),
+) -> BTreeMap<(String, String, String), i64> {
+ [("before", before), ("after", after)]
+ .into_iter()
+ .flat_map(|(stage, (count, text))| {
+ [
+ (THREAD_TOOLS_NAMESPACES_TOTAL_METRIC, count),
+ (THREAD_TOOLS_FRAGMENT_BYTES_METRIC, text.len()),
+ ]
+ .map(|(name, value)| {
+ (
+ (name.to_string(), stage.to_string(), kind.to_string()),
+ value as i64,
+ )
+ })
+ })
+ .collect()
}
diff --git a/codex-rs/core/src/session/world_state.rs b/codex-rs/core/src/session/world_state.rs
index d72080027b..a50a36acb6 100644
--- a/codex-rs/core/src/session/world_state.rs
+++ b/codex-rs/core/src/session/world_state.rs
@@ -271,6 +271,9 @@ impl Session {
world_state.add_section(PluginsInstructionsState::new(
plugins_usage_instructions_available,
));
+ let extension_metrics = super::extension_metrics::from_session_telemetry(
+ step_context.session_telemetry.clone(),
+ );
if turn_context
.config
.features
@@ -278,6 +281,7 @@ impl Session {
{
world_state.add_section(ToolsState::new(
step_context.tool_router.deferred_tool_namespaces(),
+ Arc::clone(&extension_metrics),
));
}
let environments = step_context.environments.to_selections();
@@ -286,9 +290,6 @@ impl Session {
.iter()
.map(|root| root.selected_root().clone())
.collect::<Vec<_>>();
- let extension_metrics = super::extension_metrics::from_session_telemetry(
- step_context.session_telemetry.clone(),
- );
for contributor in self.services.extensions.context_contributors() {
for section in contributor
.contribute_world_state(WorldStateContributionInput {
diff --git a/codex-rs/otel/src/metrics/names.rs b/codex-rs/otel/src/metrics/names.rs
index 31b2aad09c..f27d77a27b 100644
--- a/codex-rs/otel/src/metrics/names.rs
+++ b/codex-rs/otel/src/metrics/names.rs
@@ -68,3 +68,10 @@ pub const THREAD_SKILLS_KEPT_TOTAL_METRIC: &str = "codex.thread.skills.kept_tota
pub const THREAD_SKILLS_DESCRIPTION_TRUNCATED_CHARS_METRIC: &str =
"codex.thread.skills.description_truncated_chars";
pub const THREAD_SKILLS_TRUNCATED_METRIC: &str = "codex.thread.skills.truncated";
+// Tools measure the rendered block; kind=snapshot|delta distinguishes full catalogs from updates.
+pub const THREAD_TOOLS_NAMESPACES_TOTAL_METRIC: &str = "codex.thread.tools.namespaces_total";
+pub const THREAD_TOOLS_FRAGMENT_BYTES_METRIC: &str = "codex.thread.tools.fragment_bytes";
+
+/// Byte buckets for context-budget planning, with larger fragments in the overflow bucket.
+pub const CONTEXT_FRAGMENT_BYTES_BUCKETS: &[f64] =
+ &[256., 512., 1_024., 2_048., 4_096., 8_192., 16_384.];