mask: boundary kept in Agent, advances only when context > compact_at/3; recorded per request, stats replays it
This commit is contained in:
1 parent
166d9fec87
commit
c74b45cbeb
4 files changed
+147
-20
No files matched your search
@@ -37,6 +37,9 @@ pub struct Agent {
|
||||
/// Auto-compact when the estimated context exceeds this many tokens.
|
||||
compact_at: usize,
|
||||
ctx: ContextMeter,
|
||||
/// Assistant turns whose big tool results are masked in requests. Only moves forward, and only
|
||||
/// once the context is big enough that the saving beats rewriting the prompt cache.
|
||||
mask_boundary: usize,
|
||||
abort: watch::Receiver<bool>,
|
||||
abort_tx: Arc<watch::Sender<bool>>,
|
||||
}
|
||||
@@ -76,6 +79,7 @@ impl Agent {
|
||||
session,
|
||||
compact_at: 150_000,
|
||||
ctx: ContextMeter::default(),
|
||||
mask_boundary: 0,
|
||||
abort: rx,
|
||||
abort_tx: tx.clone(),
|
||||
};
|
||||
@@ -142,14 +146,14 @@ impl Agent {
|
||||
/// Continue in another session (resume or new). Drops token usage measured on the old history.
|
||||
pub fn replace_session(&mut self, session: Session) {
|
||||
self.session = session;
|
||||
self.ctx.reset();
|
||||
self.reset_ctx();
|
||||
}
|
||||
|
||||
/// Move the session head to entry `id`. False (and no change) if there is no such entry.
|
||||
pub fn fork(&mut self, id: u64) -> bool {
|
||||
let ok = self.session.fork(id);
|
||||
if ok {
|
||||
self.ctx.reset();
|
||||
self.reset_ctx();
|
||||
}
|
||||
ok
|
||||
}
|
||||
@@ -157,7 +161,7 @@ impl Agent {
|
||||
/// Start over: empty the conversation, keeping the session file's history.
|
||||
pub fn clear(&mut self) -> Result<(), Error> {
|
||||
self.session.rebase(vec![])?;
|
||||
self.ctx.reset();
|
||||
self.reset_ctx();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -179,17 +183,30 @@ impl Agent {
|
||||
}
|
||||
let summary = summary.ok_or(Error::Truncated)?;
|
||||
self.session.rebase(plan.apply(&summary))?;
|
||||
self.ctx.reset();
|
||||
self.reset_ctx();
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The history was replaced or rewritten: readings and the masking boundary no longer apply.
|
||||
fn reset_ctx(&mut self) {
|
||||
self.ctx.reset();
|
||||
self.mask_boundary = 0;
|
||||
}
|
||||
|
||||
/// Masking starts once the context passes this share of the compaction threshold.
|
||||
fn mask_from(&self) -> usize {
|
||||
self.compact_at / 3
|
||||
}
|
||||
|
||||
fn push(&mut self, m: Message) -> Result<(), Error> {
|
||||
self.push_with(m, None)
|
||||
}
|
||||
|
||||
fn push_with(&mut self, m: Message, usage: Option<Usage>) -> Result<(), Error> {
|
||||
let by = (m.role == Role::Assistant).then(|| self.model.clone());
|
||||
self.session.append_full(m, by, usage)?;
|
||||
let assistant = m.role == Role::Assistant;
|
||||
let by = assistant.then(|| self.model.clone());
|
||||
let mask = assistant.then_some(self.mask_boundary);
|
||||
self.session.append_masked(m, by, usage, mask)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -222,10 +239,15 @@ impl Agent {
|
||||
self.emit(Event::Info("context compacted".into())).await;
|
||||
}
|
||||
self.emit(Event::TurnStart).await;
|
||||
let msgs = self.session.messages();
|
||||
let target = crate::mask::target_boundary(&msgs);
|
||||
if target > self.mask_boundary && self.ctx.tokens(&msgs) > self.mask_from() {
|
||||
self.mask_boundary = target;
|
||||
}
|
||||
let req = Request {
|
||||
model: self.model.clone(),
|
||||
system: self.system.clone(),
|
||||
messages: crate::mask::mask_old_results(self.session.messages()),
|
||||
messages: crate::mask::mask_old_results(msgs, self.mask_boundary),
|
||||
tools: self.tools.specs(),
|
||||
max_tokens: self.max_tokens,
|
||||
};
|
||||
@@ -529,6 +551,71 @@ mod tests {
|
||||
assert!(matches!(a.run("again").await, Err(Error::Aborted)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mask_boundary_waits_for_big_context_and_is_recorded() {
|
||||
let big = "z".repeat(8000);
|
||||
let mut script = vec![];
|
||||
for i in 0..20 {
|
||||
script.push(asst(vec![tu(&i.to_string(), &big)]));
|
||||
}
|
||||
script.push(asst(vec![ContentBlock::Text { text: "fin".into() }]));
|
||||
let script = Arc::new(Script(Mutex::new(script), Mutex::new(vec![])));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut tools = Registry::default();
|
||||
tools.add(Echo);
|
||||
let cx = ToolCtx {
|
||||
cwd: dir.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let (mut a, _h) = Agent::new(
|
||||
script.clone(),
|
||||
tools,
|
||||
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||
cx,
|
||||
);
|
||||
a.set_compact_at(1_000_000); // masking only from ~333k tokens: never in this run
|
||||
a.run("go").await.unwrap();
|
||||
let elided = |r: &Request| {
|
||||
r.messages.iter().any(|m| {
|
||||
m.content.iter().any(|b| matches!(b, ContentBlock::ToolResult { content, .. } if content.starts_with("[elided")))
|
||||
})
|
||||
};
|
||||
assert!(!script.1.lock().unwrap().iter().any(elided));
|
||||
assert!(a.session().masks().iter().flatten().all(|&b| b == 0));
|
||||
|
||||
// same run with a small threshold: masks, boundary only grows and is recorded
|
||||
let mut v = vec![];
|
||||
for i in 0..20 {
|
||||
v.push(asst(vec![tu(&i.to_string(), &big)]));
|
||||
}
|
||||
v.push(asst(vec![ContentBlock::Text { text: "fin".into() }]));
|
||||
let script = Arc::new(Script(Mutex::new(v), Mutex::new(vec![])));
|
||||
let mut tools = Registry::default();
|
||||
tools.add(Echo);
|
||||
let cx = ToolCtx {
|
||||
cwd: dir.path().into(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let (mut b, _h) = Agent::new(
|
||||
script.clone(),
|
||||
tools,
|
||||
Session::open(dir.path().join("s2.jsonl")).unwrap(),
|
||||
cx,
|
||||
);
|
||||
b.set_compact_at(3_000);
|
||||
b.run("go").await.unwrap();
|
||||
assert!(script.1.lock().unwrap().iter().any(elided));
|
||||
assert!(
|
||||
script.1.lock().unwrap().iter().all(|r| r.tools.len() == 1),
|
||||
"no compaction request expected"
|
||||
);
|
||||
let m: Vec<usize> = b.session().masks().into_iter().flatten().collect();
|
||||
assert!(
|
||||
m.windows(2).all(|w| w[0] <= w[1]) && *m.last().unwrap() > 0,
|
||||
"{m:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn compaction_inside_tool_loop() {
|
||||
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
|
||||
|
||||
Reference in new issue
Block a user