mirror of
https://github.com/openai/codex.git
synced 2026-11-26 07:26:11 +00:00
Add task context to shadow skill selection (#39008)
## Why Short continuation prompts such as `continue` do not contain enough context for skill selection on their own. ## What changed - Add the `task_context_fusion_v1` shadow selector, combining the current request with up to two prior substantive requests and recently relevant skills. - Record explicit skill intent and successful skill invocations for future turns, while excluding same-turn observations from predictions. - Bound retained requests, augmented queries, and skill history, including safe truncation at UTF-8 character boundaries. ## Testing Add unit and extension tests for continuation prompts, explicit intent, turn isolation, cold thread state, bounded history, and unchanged control selectors. GitOrigin-RevId: 72eca3f0d64620a0d24e95d5675f126ac982f8c7
This commit is contained in:
1 parent
def7ed5572
commit
21cfd369ef
8 files changed
+524
-9
No files matched your search
@@ -0,0 +1,27 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recent_invocations_refresh_recency_and_evict_old_skills() {
|
||||
let history = RecentSkillInvocations::default();
|
||||
for index in 0..=MAX_SHADOW_RESULTS {
|
||||
history.record(format!("skill-{index}"));
|
||||
}
|
||||
history.record("skill-1".to_string());
|
||||
|
||||
let recent = history.snapshot();
|
||||
|
||||
assert_eq!(MAX_SHADOW_RESULTS, recent.len());
|
||||
assert_eq!(Some("skill-1"), recent.first().map(String::as_str));
|
||||
assert_eq!(Some("skill-2"), recent.last().map(String::as_str));
|
||||
assert!(!recent.iter().any(|skill| skill == "skill-0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rank_buckets_distinguish_results_above_twenty() {
|
||||
assert_eq!("11_20", rank_bucket(Some(20)));
|
||||
assert_eq!("21_50", rank_bucket(Some(21)));
|
||||
assert_eq!("21_50", rank_bucket(Some(50)));
|
||||
assert_eq!("miss", rank_bucket(Some(51)));
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
// This shadow-selection experiment is temporary and should be removed after evaluation.
|
||||
|
||||
mod task_context;
|
||||
|
||||
pub(crate) use task_context::ShadowTaskContext;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::HostSkillsSnapshot;
|
||||
use codex_extension_api::TurnInputContext;
|
||||
use codex_otel::MetricsClient;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
|
||||
use crate::catalog::SkillCatalog;
|
||||
use crate::catalog::SkillCatalogEntry;
|
||||
use crate::catalog::SkillSourceKind;
|
||||
use crate::dynamic_skill_selector::CharacterNgramSkillSelector;
|
||||
use crate::dynamic_skill_selector::CharacterRoutingCardSkillSelector;
|
||||
use crate::dynamic_skill_selector::CheapSkillSelection;
|
||||
use crate::dynamic_skill_selector::CheapSkillSelector;
|
||||
use crate::dynamic_skill_selector::FieldedBm25SkillSelector;
|
||||
use crate::dynamic_skill_selector::LruPlusCharacterRoutingSkillSelector;
|
||||
use crate::dynamic_skill_selector::LruPlusLexicalCharacterRoutingSkillSelector;
|
||||
use crate::dynamic_skill_selector::LruPlusLexicalSkillSelector;
|
||||
use crate::dynamic_skill_selector::LruSkillSelector;
|
||||
use crate::dynamic_skill_selector::MultiQueryLexicalSkillSelector;
|
||||
use crate::dynamic_skill_selector::RoutingCardLexicalSkillSelector;
|
||||
use crate::dynamic_skill_selector::RrfLexicalCharSkillSelector;
|
||||
use crate::dynamic_skill_selector::SkillSelectionDocument;
|
||||
use crate::dynamic_skill_selector::WeightedLexicalSkillSelector;
|
||||
|
||||
const MAX_SHADOW_QUERY_BYTES: usize = 16 * 1024;
|
||||
const MAX_SHADOW_RESULTS: usize = 50;
|
||||
|
||||
const RUN_METRIC: &str = "codex.skills.shadow_selection";
|
||||
const DURATION_METRIC: &str = "codex.skills.shadow_selection.duration_ms";
|
||||
const CATALOG_ENTRY_COUNT_METRIC: &str = "codex.skills.shadow_selection.catalog_entries";
|
||||
const SELECTED_ENTRY_COUNT_METRIC: &str = "codex.skills.shadow_selection.selected_entries";
|
||||
const QUERY_TERM_COUNT_METRIC: &str = "codex.skills.shadow_selection.query_terms";
|
||||
const REDUCTION_BPS_METRIC: &str = "codex.skills.shadow_selection.reduction_bps";
|
||||
const INVOCATION_METRIC: &str = "codex.skills.shadow_selection.invocation";
|
||||
|
||||
pub(crate) struct ShadowSelectionExperiment {
|
||||
selectors: Vec<Box<dyn CheapSkillSelector>>,
|
||||
metrics_client: Option<MetricsClient>,
|
||||
}
|
||||
|
||||
impl ShadowSelectionExperiment {
|
||||
pub(crate) fn new(metrics_client: Option<MetricsClient>) -> Self {
|
||||
Self {
|
||||
selectors: vec![
|
||||
Box::new(WeightedLexicalSkillSelector),
|
||||
Box::new(FieldedBm25SkillSelector),
|
||||
Box::new(CharacterNgramSkillSelector),
|
||||
Box::new(MultiQueryLexicalSkillSelector),
|
||||
Box::new(RrfLexicalCharSkillSelector),
|
||||
Box::new(RoutingCardLexicalSkillSelector),
|
||||
],
|
||||
metrics_client,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run(
|
||||
&self,
|
||||
input: &TurnInputContext,
|
||||
catalog: &SkillCatalog,
|
||||
explicitly_selected: &[SkillCatalogEntry],
|
||||
host_snapshot: Option<&HostSkillsSnapshot>,
|
||||
recent_skill_invocations: Arc<RecentSkillInvocations>,
|
||||
task_context: Arc<ShadowTaskContext>,
|
||||
) -> ShadowSelectionTurnState {
|
||||
let query = build_shadow_query(&input.user_input);
|
||||
let query_script = query_script_tag(&query.text);
|
||||
let task_snapshot = task_context.begin_turn(&input.turn_id, &query, &input.user_input);
|
||||
let explicitly_selected_skill_resources = explicitly_selected
|
||||
.iter()
|
||||
.map(|entry| normalize_skill_resource(entry.main_prompt.as_str()))
|
||||
.collect::<HashSet<_>>();
|
||||
let documents = catalog
|
||||
.entries
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, entry)| {
|
||||
entry.is_model_visible()
|
||||
// Invocation observation currently exists only for host shell use and
|
||||
// orchestrator reads. Keep the candidate set aligned with that universe.
|
||||
&& matches!(
|
||||
&entry.authority.kind,
|
||||
SkillSourceKind::Host | SkillSourceKind::Orchestrator
|
||||
)
|
||||
&& !explicitly_selected_skill_resources
|
||||
.contains(&normalize_skill_resource(entry.main_prompt.as_str()))
|
||||
})
|
||||
.map(|(id, entry)| SkillSelectionDocument {
|
||||
id,
|
||||
name: entry.name.as_str(),
|
||||
short_description: entry.short_description.as_deref(),
|
||||
description: entry.description.as_str(),
|
||||
dependencies: entry.dependencies.as_ref(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let eligible_ids = documents
|
||||
.iter()
|
||||
.map(|document| document.id)
|
||||
.collect::<HashSet<_>>();
|
||||
let eligible_skill_ids_by_resource = documents
|
||||
.iter()
|
||||
.map(|document| {
|
||||
(
|
||||
normalize_skill_resource(catalog.entries[document.id].main_prompt.as_str()),
|
||||
document.id,
|
||||
)
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
let eligible_skill_resources = eligible_skill_ids_by_resource
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<HashSet<_>>();
|
||||
let recent_skill_ids = recent_skill_invocations
|
||||
.snapshot()
|
||||
.iter()
|
||||
.filter_map(|resource| eligible_skill_ids_by_resource.get(resource).copied())
|
||||
.collect();
|
||||
let routing_selector = CharacterRoutingCardSkillSelector::new(catalog, host_snapshot);
|
||||
let lru_selector = LruSkillSelector::new(recent_skill_ids);
|
||||
let lru_plus_lexical_selector = LruPlusLexicalSkillSelector::new(lru_selector.clone());
|
||||
let lru_plus_character_selector = LruPlusCharacterRoutingSkillSelector::new(
|
||||
lru_selector.clone(),
|
||||
routing_selector.clone(),
|
||||
);
|
||||
let lru_plus_lexical_character_selector = LruPlusLexicalCharacterRoutingSkillSelector::new(
|
||||
lru_selector.clone(),
|
||||
routing_selector.clone(),
|
||||
);
|
||||
let task_selector = LruPlusLexicalCharacterRoutingSkillSelector::new(
|
||||
LruSkillSelector::new(
|
||||
task_snapshot
|
||||
.recent_skills
|
||||
.iter()
|
||||
.filter_map(|resource| eligible_skill_ids_by_resource.get(resource).copied())
|
||||
.collect(),
|
||||
),
|
||||
routing_selector.clone(),
|
||||
);
|
||||
let mut ranked_selections = Vec::with_capacity(self.selectors.len() + 6);
|
||||
|
||||
for (method, selector, query) in self
|
||||
.selectors
|
||||
.iter()
|
||||
.map(std::convert::AsRef::as_ref)
|
||||
.chain([
|
||||
&routing_selector as &dyn CheapSkillSelector,
|
||||
&lru_selector as &dyn CheapSkillSelector,
|
||||
&lru_plus_lexical_selector as &dyn CheapSkillSelector,
|
||||
&lru_plus_character_selector as &dyn CheapSkillSelector,
|
||||
&lru_plus_lexical_character_selector as &dyn CheapSkillSelector,
|
||||
])
|
||||
.map(|selector| (selector.method(), selector, &query))
|
||||
.chain([(
|
||||
"task_context_fusion_v1",
|
||||
&task_selector as &dyn CheapSkillSelector,
|
||||
&task_snapshot.query,
|
||||
)])
|
||||
{
|
||||
let query_script = query_script_tag(&query.text);
|
||||
let start = Instant::now();
|
||||
let selection =
|
||||
selector.select(&query.text, &documents, /*limit*/ MAX_SHADOW_RESULTS);
|
||||
let duration = start.elapsed();
|
||||
let selected_ids = sanitize_selected_ids(&selection, &eligible_ids);
|
||||
self.record_metrics(ShadowSelectionObservation {
|
||||
method,
|
||||
selection: &selection,
|
||||
query_truncated_before_selection: query.truncated,
|
||||
query_script,
|
||||
catalog_entry_count: documents.len(),
|
||||
selected_entry_count: selected_ids.len(),
|
||||
duration,
|
||||
});
|
||||
ranked_selections.push(RankedSelection {
|
||||
method,
|
||||
skill_resources: selected_ids
|
||||
.iter()
|
||||
.map(|id| normalize_skill_resource(catalog.entries[*id].main_prompt.as_str()))
|
||||
.collect(),
|
||||
});
|
||||
tracing::debug!(
|
||||
method,
|
||||
catalog_entries = documents.len(),
|
||||
selected_entries = selected_ids.len(),
|
||||
query_terms = selection.query_term_count,
|
||||
query_script,
|
||||
query_truncated = query.truncated || selection.query_truncated,
|
||||
candidate_set_truncated = selection.candidate_set_truncated,
|
||||
"ran shadow skill selection"
|
||||
);
|
||||
}
|
||||
|
||||
// Explicit intent is a relevance signal even if the subsequent prompt read fails.
|
||||
// Keep it out of the implicit-only controls and freeze predictions before recording it.
|
||||
for entry in explicitly_selected.iter().filter(|entry| {
|
||||
entry.is_model_visible()
|
||||
&& matches!(
|
||||
&entry.authority.kind,
|
||||
SkillSourceKind::Host | SkillSourceKind::Orchestrator
|
||||
)
|
||||
}) {
|
||||
task_context.record(
|
||||
&input.turn_id,
|
||||
normalize_skill_resource(entry.main_prompt.as_str()),
|
||||
);
|
||||
}
|
||||
|
||||
ShadowSelectionTurnState {
|
||||
ranked_selections,
|
||||
turn_id: input.turn_id.clone(),
|
||||
query_script,
|
||||
eligible_skill_resources,
|
||||
seen_skill_resources: Mutex::new(HashSet::new()),
|
||||
recent_skill_invocations,
|
||||
task_context,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_invocation(&self, state: &ShadowSelectionTurnState, skill_resource: &str) {
|
||||
let skill_resource = normalize_skill_resource(skill_resource);
|
||||
if !state.eligible_skill_resources.contains(&skill_resource) {
|
||||
return;
|
||||
}
|
||||
if !state
|
||||
.seen_skill_resources
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.insert(skill_resource.clone())
|
||||
{
|
||||
return;
|
||||
}
|
||||
state
|
||||
.recent_skill_invocations
|
||||
.record(skill_resource.clone());
|
||||
state
|
||||
.task_context
|
||||
.record(&state.turn_id, skill_resource.clone());
|
||||
let Some(metrics_client) = self.metrics_client.as_ref() else {
|
||||
return;
|
||||
};
|
||||
for selection in &state.ranked_selections {
|
||||
let rank = selection
|
||||
.skill_resources
|
||||
.iter()
|
||||
.position(|candidate| candidate == &skill_resource)
|
||||
.map(|index| index + 1);
|
||||
let tags = [
|
||||
("method", selection.method),
|
||||
("hit", bool_tag(rank.is_some())),
|
||||
("rank", rank_bucket(rank)),
|
||||
("query_script", state.query_script),
|
||||
];
|
||||
let _ = metrics_client.counter(INVOCATION_METRIC, /*inc*/ 1, &tags);
|
||||
}
|
||||
}
|
||||
|
||||
fn record_metrics(&self, observation: ShadowSelectionObservation<'_>) {
|
||||
let Some(metrics_client) = self.metrics_client.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let ShadowSelectionObservation {
|
||||
method,
|
||||
selection,
|
||||
query_truncated_before_selection,
|
||||
query_script,
|
||||
catalog_entry_count,
|
||||
selected_entry_count,
|
||||
duration,
|
||||
} = observation;
|
||||
let status = selection_status(selection, selected_entry_count);
|
||||
let query_truncated =
|
||||
bool_tag(query_truncated_before_selection || selection.query_truncated);
|
||||
let candidate_set_truncated = bool_tag(selection.candidate_set_truncated);
|
||||
let tags = [
|
||||
("method", method),
|
||||
("status", status),
|
||||
("query_script", query_script),
|
||||
("query_truncated", query_truncated),
|
||||
("candidate_set_truncated", candidate_set_truncated),
|
||||
];
|
||||
let _ = metrics_client.counter(RUN_METRIC, /*inc*/ 1, &tags);
|
||||
let _ = metrics_client.record_duration(DURATION_METRIC, duration, &tags);
|
||||
let _ = metrics_client.histogram(
|
||||
CATALOG_ENTRY_COUNT_METRIC,
|
||||
metric_value(catalog_entry_count),
|
||||
&tags,
|
||||
);
|
||||
let _ = metrics_client.histogram(
|
||||
SELECTED_ENTRY_COUNT_METRIC,
|
||||
metric_value(selected_entry_count),
|
||||
&tags,
|
||||
);
|
||||
let _ = metrics_client.histogram(
|
||||
QUERY_TERM_COUNT_METRIC,
|
||||
metric_value(selection.query_term_count),
|
||||
&tags,
|
||||
);
|
||||
let _ = metrics_client.histogram(
|
||||
REDUCTION_BPS_METRIC,
|
||||
reduction_bps(catalog_entry_count, selected_entry_count),
|
||||
&tags,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ShadowSelectionTurnState {
|
||||
ranked_selections: Vec<RankedSelection>,
|
||||
turn_id: String,
|
||||
query_script: &'static str,
|
||||
eligible_skill_resources: HashSet<String>,
|
||||
seen_skill_resources: Mutex<HashSet<String>>,
|
||||
recent_skill_invocations: Arc<RecentSkillInvocations>,
|
||||
task_context: Arc<ShadowTaskContext>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RecentSkillInvocations {
|
||||
skill_resources: Mutex<VecDeque<String>>,
|
||||
}
|
||||
|
||||
impl RecentSkillInvocations {
|
||||
fn snapshot(&self) -> Vec<String> {
|
||||
self.skill_resources
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn record(&self, skill_resource: String) {
|
||||
let mut skill_resources = self
|
||||
.skill_resources
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(index) = skill_resources
|
||||
.iter()
|
||||
.position(|resource| resource == &skill_resource)
|
||||
{
|
||||
skill_resources.remove(index);
|
||||
}
|
||||
skill_resources.push_front(skill_resource);
|
||||
skill_resources.truncate(MAX_SHADOW_RESULTS);
|
||||
}
|
||||
}
|
||||
|
||||
struct RankedSelection {
|
||||
method: &'static str,
|
||||
skill_resources: Vec<String>,
|
||||
}
|
||||
|
||||
struct ShadowSelectionObservation<'a> {
|
||||
method: &'static str,
|
||||
selection: &'a CheapSkillSelection,
|
||||
query_truncated_before_selection: bool,
|
||||
query_script: &'static str,
|
||||
catalog_entry_count: usize,
|
||||
selected_entry_count: usize,
|
||||
duration: Duration,
|
||||
}
|
||||
|
||||
fn sanitize_selected_ids(
|
||||
selection: &CheapSkillSelection,
|
||||
eligible_ids: &HashSet<usize>,
|
||||
) -> Vec<usize> {
|
||||
let mut seen = HashSet::new();
|
||||
selection
|
||||
.candidate_ids
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| eligible_ids.contains(id) && seen.insert(*id))
|
||||
.take(MAX_SHADOW_RESULTS)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn selection_status(selection: &CheapSkillSelection, selected_entry_count: usize) -> &'static str {
|
||||
if selected_entry_count > 0 {
|
||||
"selected"
|
||||
} else if selection.query_term_count == 0 {
|
||||
"no_query_terms"
|
||||
} else {
|
||||
"no_matches"
|
||||
}
|
||||
}
|
||||
|
||||
fn reduction_bps(catalog_entry_count: usize, selected_entry_count: usize) -> i64 {
|
||||
if catalog_entry_count == 0 {
|
||||
return 0;
|
||||
}
|
||||
10_000i64.saturating_sub(ratio_bps(selected_entry_count, catalog_entry_count))
|
||||
}
|
||||
|
||||
fn ratio_bps(numerator: usize, denominator: usize) -> i64 {
|
||||
if denominator == 0 {
|
||||
return 0;
|
||||
}
|
||||
let numerator = u128::try_from(numerator).unwrap_or(u128::MAX);
|
||||
let denominator = u128::try_from(denominator).unwrap_or(u128::MAX);
|
||||
let basis_points = numerator.saturating_mul(10_000) / denominator;
|
||||
i64::try_from(basis_points).unwrap_or(i64::MAX)
|
||||
}
|
||||
|
||||
fn metric_value(value: usize) -> i64 {
|
||||
i64::try_from(value).unwrap_or(i64::MAX)
|
||||
}
|
||||
|
||||
fn bool_tag(value: bool) -> &'static str {
|
||||
if value { "true" } else { "false" }
|
||||
}
|
||||
|
||||
fn rank_bucket(rank: Option<usize>) -> &'static str {
|
||||
match rank {
|
||||
Some(1) => "1",
|
||||
Some(2..=5) => "2_5",
|
||||
Some(6..=10) => "6_10",
|
||||
Some(11..=20) => "11_20",
|
||||
Some(21..=MAX_SHADOW_RESULTS) => "21_50",
|
||||
Some(_) | None => "miss",
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_skill_resource(skill_resource: &str) -> String {
|
||||
skill_resource.replace('\\', "/")
|
||||
}
|
||||
|
||||
fn query_script_tag(query: &str) -> &'static str {
|
||||
let mut has_ascii_latin = false;
|
||||
let mut has_cjk = false;
|
||||
let mut has_other = false;
|
||||
|
||||
for character in query.chars().filter(|character| character.is_alphabetic()) {
|
||||
if character.is_ascii_alphabetic() {
|
||||
has_ascii_latin = true;
|
||||
} else if is_cjk(character) {
|
||||
has_cjk = true;
|
||||
} else {
|
||||
has_other = true;
|
||||
}
|
||||
}
|
||||
|
||||
match (has_ascii_latin, has_cjk, has_other) {
|
||||
(false, false, false) => "none",
|
||||
(true, false, false) => "ascii_latin",
|
||||
(false, true, false) => "cjk",
|
||||
(false, false, true) => "other",
|
||||
(true, true, false) | (true, false, true) | (false, true, true) | (true, true, true) => {
|
||||
"mixed"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_cjk(character: char) -> bool {
|
||||
matches!(
|
||||
character,
|
||||
'\u{1100}'..='\u{11ff}'
|
||||
| '\u{3040}'..='\u{30ff}'
|
||||
| '\u{3100}'..='\u{312f}'
|
||||
| '\u{3130}'..='\u{318f}'
|
||||
| '\u{31a0}'..='\u{31bf}'
|
||||
| '\u{31f0}'..='\u{31ff}'
|
||||
| '\u{3400}'..='\u{4dbf}'
|
||||
| '\u{4e00}'..='\u{9fff}'
|
||||
| '\u{a960}'..='\u{a97f}'
|
||||
| '\u{ac00}'..='\u{d7af}'
|
||||
| '\u{d7b0}'..='\u{d7ff}'
|
||||
| '\u{f900}'..='\u{faff}'
|
||||
| '\u{20000}'..='\u{2fa1f}'
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct ShadowQuery {
|
||||
text: String,
|
||||
truncated: bool,
|
||||
}
|
||||
|
||||
fn build_shadow_query(inputs: &[UserInput]) -> ShadowQuery {
|
||||
let mut text = String::new();
|
||||
let mut truncated = false;
|
||||
for input in inputs {
|
||||
let part = match input {
|
||||
UserInput::Text { text, .. } => text.as_str(),
|
||||
UserInput::Skill { name, .. } | UserInput::Mention { name, .. } => name.as_str(),
|
||||
_ => continue,
|
||||
};
|
||||
if part.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if !text.is_empty() && !push_bounded(&mut text, " ") {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
if !push_bounded(&mut text, part) {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
ShadowQuery { text, truncated }
|
||||
}
|
||||
|
||||
fn push_bounded(destination: &mut String, value: &str) -> bool {
|
||||
let remaining = MAX_SHADOW_QUERY_BYTES.saturating_sub(destination.len());
|
||||
if value.len() <= remaining {
|
||||
destination.push_str(value);
|
||||
return true;
|
||||
}
|
||||
let mut end = remaining;
|
||||
while !value.is_char_boundary(end) {
|
||||
end = end.saturating_sub(1);
|
||||
}
|
||||
destination.push_str(&value[..end]);
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "experiment_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,155 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use codex_utils_string::take_bytes_at_char_boundary;
|
||||
|
||||
use super::ShadowQuery;
|
||||
|
||||
const MAX_PRIOR_REQUESTS: usize = 2;
|
||||
const MAX_REQUEST_BYTES: usize = 2 * 1024;
|
||||
const MAX_QUERY_BYTES: usize = 4 * 1024;
|
||||
const MAX_RECENT_SKILLS: usize = 50;
|
||||
|
||||
/// Shadow-only relevance history. New and reconstructed thread runtimes start cold.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ShadowTaskContext(Mutex<TaskContextState>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct TaskContextState {
|
||||
prior_requests: VecDeque<ShadowQuery>,
|
||||
recent_skills: VecDeque<String>,
|
||||
pending: Option<PendingTurn>,
|
||||
}
|
||||
|
||||
struct PendingTurn {
|
||||
id: String,
|
||||
request: Option<ShadowQuery>,
|
||||
recent_skills: VecDeque<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) struct TaskContextSnapshot {
|
||||
pub(super) query: ShadowQuery,
|
||||
pub(super) recent_skills: Vec<String>,
|
||||
}
|
||||
|
||||
impl ShadowTaskContext {
|
||||
pub(super) fn begin_turn(
|
||||
&self,
|
||||
turn_id: &str,
|
||||
current: &ShadowQuery,
|
||||
inputs: &[UserInput],
|
||||
) -> TaskContextSnapshot {
|
||||
let mut state = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if state.pending.as_ref().is_none_or(|turn| turn.id != turn_id) {
|
||||
if let Some(previous) = state.pending.take() {
|
||||
if let Some(request) = previous.request {
|
||||
state
|
||||
.prior_requests
|
||||
.retain(|prior| prior.text != request.text);
|
||||
state.prior_requests.push_front(request);
|
||||
state.prior_requests.truncate(MAX_PRIOR_REQUESTS);
|
||||
}
|
||||
for resource in previous.recent_skills.into_iter().rev() {
|
||||
remember_skill(&mut state.recent_skills, resource);
|
||||
}
|
||||
}
|
||||
state.pending = Some(PendingTurn {
|
||||
id: turn_id.to_string(),
|
||||
request: None,
|
||||
recent_skills: VecDeque::new(),
|
||||
});
|
||||
}
|
||||
|
||||
let retained = take_bytes_at_char_boundary(¤t.text, MAX_REQUEST_BYTES);
|
||||
let text = take_bytes_at_char_boundary(¤t.text, MAX_QUERY_BYTES);
|
||||
let mut query = ShadowQuery {
|
||||
text: text.to_string(),
|
||||
truncated: current.truncated || text.len() < current.text.len(),
|
||||
};
|
||||
for prior in &state.prior_requests {
|
||||
if prior.text == retained {
|
||||
continue;
|
||||
}
|
||||
if !query.text.is_empty() && query.text.len() < MAX_QUERY_BYTES {
|
||||
query.text.push('\n');
|
||||
}
|
||||
let part = take_bytes_at_char_boundary(
|
||||
&prior.text,
|
||||
MAX_QUERY_BYTES.saturating_sub(query.text.len()),
|
||||
);
|
||||
query.text.push_str(part);
|
||||
query.truncated |= prior.truncated || part.len() < prior.text.len();
|
||||
if part.len() < prior.text.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let recent_skills = state.recent_skills.iter().cloned().collect();
|
||||
if is_substantive(¤t.text, inputs)
|
||||
&& let Some(pending) = state.pending.as_mut()
|
||||
{
|
||||
pending.request = Some(ShadowQuery {
|
||||
text: retained.to_string(),
|
||||
truncated: current.truncated || retained.len() < current.text.len(),
|
||||
});
|
||||
}
|
||||
TaskContextSnapshot {
|
||||
query,
|
||||
recent_skills,
|
||||
}
|
||||
}
|
||||
|
||||
/// Records relevance evidence for future turns, never the active turn's predictions.
|
||||
pub(super) fn record(&self, turn_id: &str, resource: String) {
|
||||
let mut state = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(pending) = state.pending.as_mut().filter(|turn| turn.id == turn_id) {
|
||||
remember_skill(&mut pending.recent_skills, resource);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remember_skill(skills: &mut VecDeque<String>, resource: String) {
|
||||
skills.retain(|previous| previous != &resource);
|
||||
skills.push_front(resource);
|
||||
skills.truncate(MAX_RECENT_SKILLS);
|
||||
}
|
||||
|
||||
fn is_substantive(text: &str, inputs: &[UserInput]) -> bool {
|
||||
if inputs.iter().any(|input| {
|
||||
matches!(input, UserInput::Skill { name, .. } | UserInput::Mention { name, .. } if !name.trim().is_empty())
|
||||
}) {
|
||||
return true;
|
||||
}
|
||||
let normalized = text
|
||||
.split(|character: char| !character.is_alphanumeric())
|
||||
.filter(|part| !part.is_empty())
|
||||
.map(str::to_lowercase)
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
!matches!(
|
||||
normalized.as_str(),
|
||||
"" | "yes"
|
||||
| "yep"
|
||||
| "yeah"
|
||||
| "ok"
|
||||
| "okay"
|
||||
| "sure"
|
||||
| "go"
|
||||
| "go ahead"
|
||||
| "continue"
|
||||
| "please continue"
|
||||
| "proceed"
|
||||
| "do it"
|
||||
| "do that"
|
||||
| "try again"
|
||||
| "retry"
|
||||
| "thanks"
|
||||
| "thank you"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "task_context_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,112 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn query(text: &str) -> ShadowQuery {
|
||||
ShadowQuery {
|
||||
text: text.to_string(),
|
||||
truncated: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn begin(context: &ShadowTaskContext, turn_id: &str, text: &str) -> TaskContextSnapshot {
|
||||
context.begin_turn(turn_id, &query(text), &[])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prior_requests_survive_continuations_and_keep_short_substantive_input() {
|
||||
let context = ShadowTaskContext::default();
|
||||
begin(&context, "1", "Fix lint errors.");
|
||||
assert_eq!(
|
||||
query("continue\nFix lint errors."),
|
||||
begin(&context, "2", "continue").query
|
||||
);
|
||||
begin(&context, "3", "OK!!!");
|
||||
begin(&context, "4", "deploy");
|
||||
begin(&context, "5", "修复测试");
|
||||
assert_eq!(
|
||||
query("continue\n修复测试\ndeploy"),
|
||||
begin(&context, "6", "continue").query
|
||||
);
|
||||
assert_eq!(
|
||||
query("deploy\n修复测试"),
|
||||
begin(&context, "7", "deploy").query
|
||||
);
|
||||
assert!(is_substantive(
|
||||
"go",
|
||||
&[UserInput::Mention {
|
||||
name: "go".to_string(),
|
||||
path: "skill://go".to_string(),
|
||||
}]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_turn_observations_are_pending_and_late_observations_are_ignored() {
|
||||
let context = ShadowTaskContext::default();
|
||||
begin(&context, "1", "continue");
|
||||
context.record("1", "a".to_string());
|
||||
assert_eq!(
|
||||
Vec::<String>::new(),
|
||||
begin(&context, "1", "continue").recent_skills
|
||||
);
|
||||
assert_eq!(vec!["a"], begin(&context, "2", "continue").recent_skills);
|
||||
context.record("1", "late".to_string());
|
||||
context.record("2", "a".to_string());
|
||||
context.record("2", "b".to_string());
|
||||
assert_eq!(vec!["a"], begin(&context, "2", "continue").recent_skills);
|
||||
assert_eq!(
|
||||
TaskContextSnapshot {
|
||||
query: query("continue"),
|
||||
recent_skills: vec!["b".to_string(), "a".to_string()],
|
||||
},
|
||||
begin(&context, "3", "continue")
|
||||
);
|
||||
assert_eq!(
|
||||
TaskContextSnapshot {
|
||||
query: query("continue"),
|
||||
recent_skills: Vec::new(),
|
||||
},
|
||||
begin(&ShadowTaskContext::default(), "3", "continue")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_and_augmented_query_are_bounded_at_utf8_boundaries() {
|
||||
let context = ShadowTaskContext::default();
|
||||
let first = "界".repeat(MAX_REQUEST_BYTES);
|
||||
let initial = begin(&context, "1", &first);
|
||||
assert_eq!(
|
||||
ShadowQuery {
|
||||
text: take_bytes_at_char_boundary(&first, MAX_QUERY_BYTES).to_string(),
|
||||
truncated: true,
|
||||
},
|
||||
initial.query
|
||||
);
|
||||
for index in 0..=MAX_RECENT_SKILLS {
|
||||
context.record("1", format!("skill-{index}"));
|
||||
}
|
||||
begin(&context, "2", &"é".repeat(MAX_REQUEST_BYTES));
|
||||
context.record("2", "skill-1".to_string());
|
||||
let expected = format!(
|
||||
"continue\n{}\n{}",
|
||||
"é".repeat(MAX_REQUEST_BYTES / 2),
|
||||
take_bytes_at_char_boundary(&first, MAX_REQUEST_BYTES)
|
||||
);
|
||||
assert_eq!(
|
||||
TaskContextSnapshot {
|
||||
query: ShadowQuery {
|
||||
text: take_bytes_at_char_boundary(&expected, MAX_QUERY_BYTES).to_string(),
|
||||
truncated: true,
|
||||
},
|
||||
recent_skills: std::iter::once("skill-1".to_string())
|
||||
.chain(
|
||||
(2..=MAX_RECENT_SKILLS)
|
||||
.rev()
|
||||
.map(|index| format!("skill-{index}"))
|
||||
)
|
||||
.collect(),
|
||||
},
|
||||
begin(&context, "3", "continue")
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user