Sliding window 30+20 + GEN 0 cache pre-warm (pre-warm-on-change)
Window: MAIN_AREA 30 + BUFFER 20 (same 50 cap) halves rotation frequency. context: shared compose_prefix (byte-exact prefix of compose) + notepad_fingerprint (rendered header body, excludes updated_at). inkling: build_prefix_ids renders without finish_prompt. service: prewarm() sends GEN 0 directly (no PerfMeter/DB). sessions: schedule_prewarm at turn end on pending rotation OR notepad-dirty (ws=0 normalized); session_chat loads only the window subset. examples/prewarm_bench.rs: joint GEN 0 -> RESUME bench, PASS on HIP (cached==L==385). Verified live all-agent: notepad write -> pre-warm 1468 -> next turn cached_tokens==1468. Tests: prefix property, opener-skip, GEN 0 primitive, notepad fingerprint. Suite 162 passed + 3 ignored.
This commit is contained in:
1 parent
0ce84581a4
commit
a52bec97d4
12 files changed
+650
-59
No files matched your search
+184
-26
@@ -24,6 +24,66 @@ pub fn compose(
|
||||
) -> Vec<ChatMessage> {
|
||||
// Server-local timezone offset, computed once for every turn in this request.
|
||||
let tz_offset = server_utc_offset_secs();
|
||||
// The shared prefix (pinned + DIALOG + history), then the new user turn.
|
||||
let mut messages = prefix_messages(sess, history, user_name, sections, notepad, tz_offset);
|
||||
// The user turn: typed text + attachment context. Images become multipart
|
||||
// image_url parts that the Vision bridge materializes; else a plain string.
|
||||
let user_text = format!(
|
||||
"{}{}",
|
||||
speaker_prefix(user_name, now_unix() as i64, tz_offset),
|
||||
user_content
|
||||
);
|
||||
if images.is_empty() {
|
||||
messages.push(text_message(Role::User, user_text));
|
||||
} else {
|
||||
let mut parts = vec![serde_json::json!({"type": "text", "text": user_text})];
|
||||
parts.extend(images.iter().cloned());
|
||||
messages.push(ChatMessage {
|
||||
role: Role::User,
|
||||
content: Some(serde_json::Value::Array(parts)),
|
||||
tool_call_id: None,
|
||||
tool_calls: None,
|
||||
name: None,
|
||||
reasoning_content: None,
|
||||
});
|
||||
}
|
||||
messages
|
||||
}
|
||||
|
||||
/// The prompt prefix WITHOUT the new user turn: pinned sections + notepad + the
|
||||
/// open DIALOG region + the retained history (with `[SPEAKER]` stamps). This is
|
||||
/// exactly what [`compose`] builds before appending the user turn, so a cache
|
||||
/// pre-warm (`GEN 0`) over `compose_prefix` is a byte-exact token prefix of the
|
||||
/// real turn's prompt and the engine's `RESUME` hits. The real turn must reuse
|
||||
/// this same prefix (it does, via [`compose`]) — never a parallel rebuild.
|
||||
pub fn compose_prefix(
|
||||
sess: &Session,
|
||||
history: &[StoredMessage],
|
||||
user_name: &str,
|
||||
sections: &[ContextSection],
|
||||
notepad: &[NotepadEntry],
|
||||
) -> Vec<ChatMessage> {
|
||||
prefix_messages(
|
||||
sess,
|
||||
history,
|
||||
user_name,
|
||||
sections,
|
||||
notepad,
|
||||
server_utc_offset_secs(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The shared prefix builder: pinned prefix + the open DIALOG region + the
|
||||
/// retained history. `tz_offset` is the server UTC offset, passed in so [`compose`]
|
||||
/// stamps the history and the new user turn with one consistent offset.
|
||||
fn prefix_messages(
|
||||
sess: &Session,
|
||||
history: &[StoredMessage],
|
||||
user_name: &str,
|
||||
sections: &[ContextSection],
|
||||
notepad: &[NotepadEntry],
|
||||
tz_offset: i64,
|
||||
) -> Vec<ChatMessage> {
|
||||
// Pinned prefix: static sections + notepad, always present above the window.
|
||||
let mut messages = pinned_messages(sess, sections, notepad);
|
||||
// The interactive region opens with <DIALOG> and is left OPEN: a trailing
|
||||
@@ -63,27 +123,6 @@ pub fn compose(
|
||||
.and_then(|s| serde_json::from_str(s).ok());
|
||||
messages.push(msg);
|
||||
}
|
||||
// The user turn: typed text + attachment context. Images become multipart
|
||||
// image_url parts that the Vision bridge materializes; else a plain string.
|
||||
let user_text = format!(
|
||||
"{}{}",
|
||||
speaker_prefix(user_name, now_unix() as i64, tz_offset),
|
||||
user_content
|
||||
);
|
||||
if images.is_empty() {
|
||||
messages.push(text_message(Role::User, user_text));
|
||||
} else {
|
||||
let mut parts = vec![serde_json::json!({"type": "text", "text": user_text})];
|
||||
parts.extend(images.iter().cloned());
|
||||
messages.push(ChatMessage {
|
||||
role: Role::User,
|
||||
content: Some(serde_json::Value::Array(parts)),
|
||||
tool_call_id: None,
|
||||
tool_calls: None,
|
||||
name: None,
|
||||
reasoning_content: None,
|
||||
});
|
||||
}
|
||||
messages
|
||||
}
|
||||
|
||||
@@ -114,11 +153,7 @@ pub fn pinned_messages(
|
||||
));
|
||||
}
|
||||
if !notepad.is_empty() {
|
||||
let body = notepad
|
||||
.iter()
|
||||
.map(|e| format!("{}: {}", e.key, e.text.replace('\n', " ")))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let body = notepad_fingerprint(notepad);
|
||||
messages.push(text_message(
|
||||
Role::System,
|
||||
format!("<NOTEPAD>\n{body}\n</NOTEPAD>\n\n"),
|
||||
@@ -127,6 +162,20 @@ pub fn pinned_messages(
|
||||
messages
|
||||
}
|
||||
|
||||
/// The rendered `<NOTEPAD>` body: one `key: text` line per entry (newlines in text
|
||||
/// normalized to spaces), in store order. This is exactly what the header injects,
|
||||
/// so it doubles as a fingerprint: if it is unchanged across a turn, the notepad
|
||||
/// header is byte-identical and the prefix cache still holds (no pre-warm needed).
|
||||
/// `updated_at` is deliberately excluded — it does not affect the rendered header,
|
||||
/// so re-setting identical text does not trigger a wasted pre-warm.
|
||||
pub fn notepad_fingerprint(notepad: &[NotepadEntry]) -> String {
|
||||
notepad
|
||||
.iter()
|
||||
.map(|e| format!("{}: {}", e.key, e.text.replace('\n', " ")))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn role_of(s: &str) -> Role {
|
||||
match s {
|
||||
"system" | "developer" => Role::System,
|
||||
@@ -385,4 +434,113 @@ mod tests {
|
||||
assert!(a[da + 1].text().unwrap().ends_with("\n\n"));
|
||||
assert_eq!(a[da + 1].text().unwrap(), b[db + 1].text().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compose_prefix_is_exact_prefix_of_compose() {
|
||||
let sess = Session {
|
||||
id: "s".into(),
|
||||
title: "Nebula".into(),
|
||||
model: "m".into(),
|
||||
settings: crate::store::SessionSettings::default(),
|
||||
name_locked: true,
|
||||
folder: None,
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
};
|
||||
let sections = vec![ContextSection {
|
||||
name: "TOOL_USE".into(),
|
||||
content: "manuale".into(),
|
||||
position: 1,
|
||||
}];
|
||||
let notepad = vec![NotepadEntry {
|
||||
key: "goal".into(),
|
||||
text: "ship it".into(),
|
||||
updated_at: 0,
|
||||
}];
|
||||
let history = vec![
|
||||
StoredMessage {
|
||||
id: 1,
|
||||
role: "user".into(),
|
||||
content: "ciao".into(),
|
||||
reasoning_content: None,
|
||||
tool_calls_json: None,
|
||||
tool_call_id: None,
|
||||
prompt_tokens: 0,
|
||||
completion_tokens: 0,
|
||||
created_at: 1_700_000_000,
|
||||
},
|
||||
StoredMessage {
|
||||
id: 2,
|
||||
role: "assistant".into(),
|
||||
content: "ciao a te".into(),
|
||||
reasoning_content: None,
|
||||
tool_calls_json: None,
|
||||
tool_call_id: None,
|
||||
prompt_tokens: 0,
|
||||
completion_tokens: 0,
|
||||
created_at: 1_700_000_001,
|
||||
},
|
||||
];
|
||||
let prefix = compose_prefix(&sess, &history, "Federico", §ions, ¬epad);
|
||||
let full = compose(
|
||||
&sess,
|
||||
&history,
|
||||
"nuovo turno",
|
||||
&[],
|
||||
"Federico",
|
||||
§ions,
|
||||
¬epad,
|
||||
);
|
||||
// compose == prefix + exactly one new user turn: the pre-warm prefix is a
|
||||
// byte-exact prefix of the real turn (ChatMessage has no PartialEq, so
|
||||
// compare the serialized form, which is what the template renders).
|
||||
assert_eq!(full.len(), prefix.len() + 1);
|
||||
let pj: Vec<serde_json::Value> = prefix
|
||||
.iter()
|
||||
.map(|m| serde_json::to_value(m).unwrap())
|
||||
.collect();
|
||||
let fj: Vec<serde_json::Value> = full[..prefix.len()]
|
||||
.iter()
|
||||
.map(|m| serde_json::to_value(m).unwrap())
|
||||
.collect();
|
||||
assert_eq!(pj, fj, "pre-warm prefix must equal the real turn's prefix");
|
||||
assert!(matches!(full.last().unwrap().role, Role::User));
|
||||
assert!(full
|
||||
.last()
|
||||
.unwrap()
|
||||
.text()
|
||||
.unwrap()
|
||||
.ends_with("nuovo turno"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notepad_fingerprint_tracks_header_not_updated_at() {
|
||||
let a = vec![NotepadEntry {
|
||||
key: "goal".into(),
|
||||
text: "ship it".into(),
|
||||
updated_at: 1,
|
||||
}];
|
||||
let b = vec![NotepadEntry {
|
||||
key: "goal".into(),
|
||||
text: "ship it".into(),
|
||||
updated_at: 999,
|
||||
}];
|
||||
// updated_at differs but the rendered header is identical -> same fingerprint
|
||||
// (re-setting identical text must not trigger a wasted pre-warm).
|
||||
assert_eq!(notepad_fingerprint(&a), notepad_fingerprint(&b));
|
||||
let c = vec![NotepadEntry {
|
||||
key: "goal".into(),
|
||||
text: "ship it now".into(),
|
||||
updated_at: 1,
|
||||
}];
|
||||
assert_ne!(notepad_fingerprint(&a), notepad_fingerprint(&c));
|
||||
// newline normalization matches the header body exactly.
|
||||
let d = vec![NotepadEntry {
|
||||
key: "state".into(),
|
||||
text: "coding\nnow".into(),
|
||||
updated_at: 0,
|
||||
}];
|
||||
assert_eq!(notepad_fingerprint(&d), "state: coding now");
|
||||
assert_eq!(notepad_fingerprint(&[]), "");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user