Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions crates/runvil-internal/lua/src/compactors-tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,35 @@ fn plan_compaction_keeps_system_and_last_two_user_turns_and_summarizes_earlier_t
user("q3"),
]
);

let with_tools = vec![
Arc::new(user("set safe mode")),
Arc::new(MessageRecord {
tool_calls: vec![ToolCallRecord {
id: "c1".to_owned(),
name: "set_config".to_owned(),
arguments: json!({ "mode": "safe" }),
}],
..assistant("")
}),
Arc::new(tool_result("c1", "ok")),
Arc::new(assistant("configured")),
Arc::new(user("q2")),
Arc::new(user("q3")),
];
let CompactionPlan::Summarize(tool_plan) = plan_compaction(&with_tools) else {
panic!("expected a summarization plan for tool-call turn");
};
assert_eq!(
tool_plan.prompt,
concat!(
"Summarize this conversation:\n",
"user: \"set safe mode\"\n",
"assistant: {\"tool_calls\":[{\"id\":\"c1\",\"name\":\"set_config\",\"arguments\":{\"mode\":\"safe\"}}]}\n",
"tool: {\"tool_call_id\":\"c1\",\"content\":\"ok\"}\n",
"assistant: \"configured\"",
)
);
}

#[test]
Expand Down Expand Up @@ -172,6 +201,24 @@ fn plan_compaction_returns_discard_only_or_unchanged_when_nothing_is_summarizabl
plan_compaction(&discard_only),
CompactionPlan::DiscardOnly(vec![Arc::new(user("q1")), Arc::new(user("q2"))])
);

// 1,000 forty-character user records plus two kept user turns: the
// complete prompt (prefix and newline separators included) must never
// exceed `SUMMARY_ROOM_BYTES` (48,000 bytes).
let mut many: Vec<Arc<MessageRecord>> = (0..1_000)
.map(|_| Arc::new(user(&"a".repeat(40))))
.collect();
many.push(Arc::new(user("q_prev")));
many.push(Arc::new(user("q_last")));
let CompactionPlan::Summarize(plan) = plan_compaction(&many) else {
panic!("expected Summarize");
};
assert!(
plan.prompt.len() <= super::SUMMARY_ROOM_BYTES,
"summary prompt length {} exceeded {}",
plan.prompt.len(),
super::SUMMARY_ROOM_BYTES
);
}

fn window(tokens: u32) -> NonZeroU32 {
Expand Down
88 changes: 75 additions & 13 deletions crates/runvil-internal/lua/src/compactors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,12 @@ use serde_json::{Value, json};

use crate::protocol::{CompactHint, MessageContent, MessageRecord};

/// The room in bytes kept for the summarized lines in a compaction prompt.
/// The most bytes a compaction prompt may take in total, `SUMMARY_PROMPT_PREFIX`
/// and newline separators included.
const SUMMARY_ROOM_BYTES: usize = 48_000;

/// The most bytes of a single record's JSON-encoded content included in a
/// compaction prompt, cut back to a UTF-8 character boundary.
/// The most bytes of a single record's JSON-encoded summary representation
/// included in a compaction prompt, cut back to a UTF-8 character boundary.
const SUMMARY_RECORD_MAX_BYTES: usize = 1_500;

/// The prefix of the summarization prompt sent to `infer`.
Expand Down Expand Up @@ -406,27 +407,88 @@ pub(crate) fn plan_compaction(records: &[Arc<MessageRecord>]) -> CompactionPlan
})
}

/// One tool call in an assistant record's summary representation.
#[derive(serde::Serialize)]
struct SummaryToolCall<'a> {
id: &'a str,
name: &'a str,
arguments: &'a Value,
}

/// An assistant tool-call record's summary representation, placing
/// `tool_calls` first so long visible content cannot push call details past
/// [`SUMMARY_RECORD_MAX_BYTES`].
#[derive(serde::Serialize)]
struct SummaryAssistantCalls<'a> {
tool_calls: Vec<SummaryToolCall<'a>>,
#[serde(skip_serializing_if = "Option::is_none")]
content: Option<Value>,
}

/// A tool-result record's summary representation, placing `tool_call_id`
/// first so a truncated result excerpt still names the call it answered.
#[derive(serde::Serialize)]
struct SummaryToolResult<'a> {
tool_call_id: &'a str,
content: Value,
}

/// JSON-encodes `record` for [`build_summary_prompt`], preserving the plain
/// content representation for text-only records and including tool-call names,
/// arguments, and matching call identifiers for tool-call and tool-result
/// records.
fn encode_summary_record(record: &MessageRecord) -> String {
if !record.tool_calls.is_empty() {
let tool_calls = record
.tool_calls
.iter()
.map(|call| SummaryToolCall {
id: &call.id,
name: &call.name,
arguments: &call.arguments,
})
.collect();
let content = match &record.content {
MessageContent::Text(text) if text.is_empty() => None,
content => Some(content.to_json()),
};
serde_json::to_string(&SummaryAssistantCalls {
tool_calls,
content,
})
.unwrap_or_else(|_| "\"\"".to_owned())
} else if let Some(tool_call_id) = record.tool_call_id.as_deref() {
serde_json::to_string(&SummaryToolResult {
tool_call_id,
content: record.content.to_json(),
})
.unwrap_or_else(|_| "\"\"".to_owned())
} else {
serde_json::to_string(&record.content.to_json()).unwrap_or_else(|_| "\"\"".to_owned())
}
}

/// Builds the bounded summarization prompt from `records`, walking from
/// newest to oldest within [`SUMMARY_ROOM_BYTES`] and truncating each
/// JSON-encoded content at [`SUMMARY_RECORD_MAX_CHARS`] characters.
/// JSON-encoded record representation at [`SUMMARY_RECORD_MAX_BYTES`] bytes
/// on a UTF-8 character boundary.
fn build_summary_prompt(records: &[Arc<MessageRecord>]) -> String {
let mut lines = Vec::new();
let mut room = SUMMARY_ROOM_BYTES;
let mut lines: Vec<String> = Vec::new();
let mut room = SUMMARY_ROOM_BYTES.saturating_sub(SUMMARY_PROMPT_PREFIX.len());
for record in records.iter().rev() {
let encoded =
serde_json::to_string(&record.content.to_json()).unwrap_or_else(|_| "\"\"".to_owned());
let encoded = encode_summary_record(record);
let excerpt = &encoded[..encoded.floor_char_boundary(SUMMARY_RECORD_MAX_BYTES)];
let line = format!("{}: {excerpt}", record.role.as_str());
if line.len() > room {
let separator = usize::from(!lines.is_empty());
let cost = line.len() + separator;
if cost > room {
break;
}
room -= line.len();
room -= cost;
lines.push(line);
}
lines.reverse();
let mut prompt = String::with_capacity(
SUMMARY_PROMPT_PREFIX.len() + (SUMMARY_ROOM_BYTES - room) + lines.len(),
);
let mut prompt = String::with_capacity(SUMMARY_ROOM_BYTES - room);
prompt.push_str(SUMMARY_PROMPT_PREFIX);
prompt.push_str(&lines.join("\n"));
prompt
Expand Down
18 changes: 17 additions & 1 deletion crates/runvil-internal/lua/src/messages-tests-list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -376,12 +376,28 @@ fn prune_and_clear_chain_and_prune_drops_discard_records_and_batches() {
messages:assistant('drop_by_tool', \
{ { id = 'c3', name = 'echo', arguments = {} } })\n\
messages:tool('r3', 'c3', { compact = 'discard' })\n\
messages:assistant('pin_wins_over_discard', \
{ { id = 'c4', name = 'echo', arguments = {} } }, \
{ compact = 'pin' })\n\
messages:tool('r4', 'c4', { compact = 'discard' })\n\
messages:assistant('pin_tool_wins_over_discard', \
{ { id = 'c5', name = 'echo', arguments = {} } }, \
{ compact = 'discard' })\n\
messages:tool('r5', 'c5', { compact = 'pin' })\n\
return messages:prune() == messages",
);
assert!(same, "prune returns messages for chaining");
assert_eq!(
texts(vm.messages()),
expect(&[(User, "keep_u"), (Assistant, "keep_batch"), (Tool, "r2")])
expect(&[
(User, "keep_u"),
(Assistant, "keep_batch"),
(Tool, "r2"),
(Assistant, "pin_wins_over_discard"),
(Tool, "r4"),
(Assistant, "pin_tool_wins_over_discard"),
(Tool, "r5"),
])
);
let cleared: bool = vm.eval("return messages:clear() == messages and #messages == 0");
assert!(cleared, "clear empties messages and returns it");
Expand Down
14 changes: 9 additions & 5 deletions crates/runvil-internal/lua/src/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,11 +386,15 @@ pub(crate) fn prune_records(records: &[Arc<MessageRecord>]) -> Vec<Arc<MessageRe
end += 1;
}
let unit = &records[index..end];
let discard = record.compact_hint() == CompactHint::Discard
|| (end > index + 1
&& unit[1..]
.iter()
.all(|tool| tool.compact_hint() == CompactHint::Discard));
let has_pin = unit
.iter()
.any(|member| member.compact_hint() == CompactHint::Pin);
let discard = !has_pin
&& (record.compact_hint() == CompactHint::Discard
|| (end > index + 1
&& unit[1..]
.iter()
.all(|tool| tool.compact_hint() == CompactHint::Discard)));
if !discard {
kept.extend(unit.iter().map(Arc::clone));
}
Expand Down
2 changes: 1 addition & 1 deletion decisions/models-and-conversations.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ The estimate omits tool schemas and image parts. A count for both is planned wor

### The Engine compacts `messages` in Rust under a snapshot, guided by `meta.compact`

A request overflows when the precheck refuses it or when the provider rejects it as too large. The loop then takes a snapshot of the records and runs the built-in Rust compactor over `messages`. The compactor keeps the leading `system` block and the last two `user` turns intact. In the compaction window before the last two `user` turns, it groups each `assistant` tool-call record with its `tool` result records as an atomic unit, drops any record or unit marked `meta.compact = "discard"`, keeps any record or unit marked `meta.compact = "pin"` in order, and summarizes the remaining records in the window through an `infer` round into one `user` record prefixed with `Summary of the earlier conversation: ` and marked `meta = { summary = true }`. The summarization prompt walks backward through the summarizable records with a 48,000-byte budget and caps each JSON-encoded content excerpt at 1,500 bytes on a UTF-8 character boundary.
A request overflows when the precheck refuses it or when the provider rejects it as too large. The loop then takes a snapshot of the records and runs the built-in Rust compactor over `messages`. The compactor keeps the leading `system` block in place, groups each `assistant` tool-call record with its `tool` result records as an atomic unit, and drops any record or unit outside the leading `system` block marked `meta.compact = "discard"` (unless a member of the unit is marked `meta.compact = "pin"`). It then keeps the last two remaining `user` turns intact, preserves any record or unit in the earlier compaction window marked `meta.compact = "pin"` in order, and summarizes the remaining records in that window through an `infer` round into one `user` record prefixed with `Summary of the earlier conversation: ` and marked `meta = { summary = true }`. The summarization prompt walks backward through the summarizable records within a 48,000-byte total prompt budget (`Summarize this conversation:\n` and newline separators included) and caps each JSON-encoded record excerpt (including tool-call names, arguments, and call ids on tool turns) at 1,500 bytes on a UTF-8 character boundary.

### Discarding alone skips the summarization round when nothing in the window needs a summary

Expand Down
Loading