Masking: move the boundary rarely (context > compact_at/3), record it per request #110

Merged
hermes merged 1 commits from mask-hysteresis into main 2026-10-01 22:36:24 +00:00
4 changed files with 147 additions and 20 deletions
Showing only changes of commit c74b45cbeb - Show all commits

No files matched your search

+94 -7
View File
@@ -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() }]);
+18 -9
View File
@@ -1,20 +1,26 @@
//! Observation masking: old, large tool results are replaced by a one-line stub in the request
//! (the session file keeps the original). Pure function of the message list, so the request prefix
//! is byte-stable between steps and the prompt cache only breaks once per `STEP` assistant turns.
//! (the session file keeps the original). Pure function of the message list and a boundary, so the
//! request prefix is byte-stable while the boundary stays put. Every move of the boundary rewrites the
//! prompt cache from the first changed result on, so the agent moves it rarely (see `Agent`).
use hx_ai::{ContentBlock, Message, Role};
use std::collections::HashMap;
/// Results from the last `KEEP` assistant turns are never masked.
const KEEP: usize = 8;
/// The masking boundary moves in jumps of this many assistant turns (one cache break per jump).
/// The target boundary is a multiple of this many assistant turns.
const STEP: usize = 8;
/// Results smaller than this stay (a stub would not save much).
const MIN_BYTES: usize = 4_000;
pub fn mask_old_results(msgs: Vec<Message>) -> Vec<Message> {
/// Boundary (in assistant turns) the history would be masked up to right now.
pub fn target_boundary(msgs: &[Message]) -> usize {
let total = msgs.iter().filter(|m| m.role == Role::Assistant).count();
let boundary = total.saturating_sub(KEEP) / STEP * STEP;
total.saturating_sub(KEEP) / STEP * STEP
}
/// Mask results of the first `boundary` assistant turns.
pub fn mask_old_results(msgs: Vec<Message>, boundary: usize) -> Vec<Message> {
if boundary == 0 {
return msgs;
}
@@ -94,11 +100,13 @@ mod tests {
v
};
// 15 turns: boundary = (15-8)/8*8 = 0 -> untouched
let v = mask_old_results(build(15));
let m = build(15);
let v = mask_old_results(m.clone(), target_boundary(&m));
assert!(v.iter().all(|m| m.text().is_empty() || m.text() == "go"));
assert_eq!(result(&v[2]).len(), 5000);
// 16 turns: boundary 8 -> first 8 big results masked, small one (i=1) kept, later ones kept
let v = mask_old_results(build(16));
let m = build(16);
let v = mask_old_results(m.clone(), target_boundary(&m));
assert!(
result(&v[2]).starts_with("[elided old tool result: bash"),
"{}",
@@ -108,9 +116,10 @@ mod tests {
assert_eq!(result(&v[4]).len(), 100);
assert_eq!(result(&v[2 * 8 + 2]).len(), 5000); // turn 9 untouched
// stable: same input -> same output (prefix bytes identical between calls)
assert_eq!(mask_old_results(build(16)), v);
assert_eq!(mask_old_results(m, target_boundary(&build(16))), v);
// one more turn inside the same step does not change the masked prefix
let w = mask_old_results(build(17));
let m = build(17);
let w = mask_old_results(m.clone(), target_boundary(&m));
assert_eq!(&w[..17], &v[..17]);
}
}
+31 -3
View File
@@ -17,6 +17,10 @@ pub struct Entry {
/// API usage of the request that produced this assistant message (absent in older files).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage: Option<hx_ai::Usage>,
/// Tool-result masking boundary (assistant turns) of the request that produced this assistant
/// message; absent in older files, where the stepwise rule applied.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mask: Option<usize>,
}
pub struct Session {
@@ -72,6 +76,17 @@ impl Session {
message: Message,
model: Option<String>,
usage: Option<hx_ai::Usage>,
) -> std::io::Result<u64> {
self.append_masked(message, model, usage, None)
}
/// Like `append_full`, also recording the masking boundary the request used.
pub fn append_masked(
&mut self,
message: Message,
model: Option<String>,
usage: Option<hx_ai::Usage>,
mask: Option<usize>,
) -> std::io::Result<u64> {
let id = self.entries.last().map_or(0, |e| e.id + 1);
let e = Entry {
@@ -80,6 +95,7 @@ impl Session {
message,
model,
usage,
mask,
};
let mut f = std::fs::OpenOptions::new()
.create(true)
@@ -121,20 +137,32 @@ impl Session {
.collect()
}
/// Messages on the path root..=head.
pub fn messages(&self) -> Vec<Message> {
fn branch(&self) -> Vec<&Entry> {
let mut out = vec![];
let mut cur = self.head;
while let Some(id) = cur {
let Some(e) = self.entries.iter().find(|e| e.id == id) else {
break;
};
out.push(e.message.clone());
out.push(e);
cur = e.parent;
}
out.reverse();
out
}
/// Messages on the path root..=head.
pub fn messages(&self) -> Vec<Message> {
self.branch()
.into_iter()
.map(|e| e.message.clone())
.collect()
}
/// Recorded masking boundary per message on the path (aligned with `messages()`).
pub fn masks(&self) -> Vec<Option<usize>> {
self.branch().into_iter().map(|e| e.mask).collect()
}
}
/// `<hx home>/sessions/<slug of cwd>`.
+4 -1
View File
@@ -90,6 +90,7 @@ pub fn report(s: &Session) -> String {
ContentBlock::ToolResult { content, .. } => content.len(),
_ => 0,
};
let masks = s.masks();
let mut sent = vec![0usize; msgs.len()];
let mut raw = vec![0usize; msgs.len()];
for (end, _) in msgs
@@ -97,7 +98,9 @@ pub fn report(s: &Session) -> String {
.enumerate()
.filter(|(_, m)| m.role == Role::Assistant)
{
let masked = crate::mask::mask_old_results(msgs[..end].to_vec());
// boundary the agent recorded for this request; older files used the stepwise rule
let b = masks[end].unwrap_or_else(|| crate::mask::target_boundary(&msgs[..end]));
let masked = crate::mask::mask_old_results(msgs[..end].to_vec(), b);
for (i, m) in masked.iter().enumerate() {
let text_len = |m: &hx_ai::Message| {
m.content