audit: tool_call_id replay, CoT dup guard, notepad/shell/sqlite/detok hardening (BUG-04/05/06/07/11/16, SEC-11)
This commit is contained in:
1 parent
b8e1a07e77
commit
09542e05a1
7 files changed
+276
-32
No files matched your search
+48
-5
@@ -79,7 +79,8 @@ pub async fn execute(store: &Arc<dyn Store>, session_id: &str, args: &Json) -> S
|
|||||||
.and_then(|v| v.as_str())
|
.and_then(|v| v.as_str())
|
||||||
.unwrap_or("")
|
.unwrap_or("")
|
||||||
.trim()
|
.trim()
|
||||||
.to_string();
|
.replace("\r\n", "\n")
|
||||||
|
.replace('\r', "\n");
|
||||||
let store = store.clone();
|
let store = store.clone();
|
||||||
let sid = session_id.to_string();
|
let sid = session_id.to_string();
|
||||||
let res = tokio::task::spawn_blocking(move || -> Result<String> {
|
let res = tokio::task::spawn_blocking(move || -> Result<String> {
|
||||||
@@ -91,8 +92,8 @@ pub async fn execute(store: &Arc<dyn Store>, session_id: &str, args: &Json) -> S
|
|||||||
if key.chars().count() > MAX_KEY_CHARS {
|
if key.chars().count() > MAX_KEY_CHARS {
|
||||||
return Ok(format!("error: key too long (max {MAX_KEY_CHARS} chars)"));
|
return Ok(format!("error: key too long (max {MAX_KEY_CHARS} chars)"));
|
||||||
}
|
}
|
||||||
if key.contains('\n') {
|
if key.chars().any(|c| c.is_control()) {
|
||||||
return Ok("error: key must be a single line".into());
|
return Ok("error: key must be a single line (no control characters)".into());
|
||||||
}
|
}
|
||||||
if text.is_empty() {
|
if text.is_empty() {
|
||||||
return Ok("error: notepad set requires non-empty 'text'".into());
|
return Ok("error: notepad set requires non-empty 'text'".into());
|
||||||
@@ -104,12 +105,14 @@ pub async fn execute(store: &Arc<dyn Store>, session_id: &str, args: &Json) -> S
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
let entries = store.notepad(&sid)?;
|
let entries = store.notepad(&sid)?;
|
||||||
|
// Budget the RENDERED header (`key: text` per line), not just the
|
||||||
|
// text: excluding keys let many long keys blow past the ceiling.
|
||||||
let others: usize = entries
|
let others: usize = entries
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|e| e.key != key)
|
.filter(|e| e.key != key)
|
||||||
.map(|e| e.text.chars().count())
|
.map(|e| e.key.chars().count() + 2 + e.text.chars().count())
|
||||||
.sum();
|
.sum();
|
||||||
let total = others + nlen;
|
let total = others + key.chars().count() + 2 + nlen;
|
||||||
if total > MAX_TOTAL_CHARS {
|
if total > MAX_TOTAL_CHARS {
|
||||||
return Ok(format!(
|
return Ok(format!(
|
||||||
"error: notepad full ({total} > {MAX_TOTAL_CHARS} chars). Remove or \
|
"error: notepad full ({total} > {MAX_TOTAL_CHARS} chars). Remove or \
|
||||||
@@ -240,4 +243,44 @@ mod tests {
|
|||||||
assert_eq!(d["function"]["name"], "notepad");
|
assert_eq!(d["function"]["name"], "notepad");
|
||||||
assert_eq!(d["function"]["parameters"]["required"][0], "action");
|
assert_eq!(d["function"]["parameters"]["required"][0], "action");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn budget_counts_keys_and_rejects_control_chars() {
|
||||||
|
let (store, sid) = setup();
|
||||||
|
// A carriage return (or any control char) in the key is rejected.
|
||||||
|
let out = execute(
|
||||||
|
&store,
|
||||||
|
&sid,
|
||||||
|
&json!({"action":"set","key":"a\rb","text":"x"}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(out.contains("single line"), "{out}");
|
||||||
|
// Keys count toward the budget: long keys + 1-char text hit the ceiling
|
||||||
|
// after ~125 entries, not the 8000 the text-only budget would allow.
|
||||||
|
let prefix = "k".repeat(60);
|
||||||
|
let mut refused = false;
|
||||||
|
for i in 0..200 {
|
||||||
|
let key = format!("{prefix}{i}");
|
||||||
|
let out = execute(&store, &sid, &json!({"action":"set","key":key,"text":"x"})).await;
|
||||||
|
if out.contains("full") {
|
||||||
|
refused = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(refused, "key length must count toward the notepad budget");
|
||||||
|
assert!(store.notepad(&sid).unwrap().len() < 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn text_carriage_returns_normalized() {
|
||||||
|
let (store, sid) = setup();
|
||||||
|
execute(
|
||||||
|
&store,
|
||||||
|
&sid,
|
||||||
|
&json!({"action":"set","key":"k","text":"a\r\nb\rc"}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let np = store.notepad(&sid).unwrap();
|
||||||
|
assert_eq!(np[0].text, "a\nb\nc");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+25
-1
@@ -147,9 +147,16 @@ impl ShellRequest {
|
|||||||
.filter(|s| !s.trim().is_empty())
|
.filter(|s| !s.trim().is_empty())
|
||||||
.ok_or_else(|| anyhow::anyhow!("shell_exec requires a non-empty 'command'"))?
|
.ok_or_else(|| anyhow::anyhow!("shell_exec requires a non-empty 'command'"))?
|
||||||
.to_string();
|
.to_string();
|
||||||
let cwd = args.get("cwd").and_then(|v| v.as_str()).map(str::to_string);
|
let cwd = args
|
||||||
|
.get("cwd")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.filter(|s| !s.trim().is_empty())
|
||||||
|
.map(str::to_string);
|
||||||
|
// Accept `timeout` as an alias of `timeout_secs`: the TOOL_USE manual
|
||||||
|
// spells `timeout?`, so a model following it must not be silently ignored.
|
||||||
let secs = args
|
let secs = args
|
||||||
.get("timeout_secs")
|
.get("timeout_secs")
|
||||||
|
.or_else(|| args.get("timeout"))
|
||||||
.and_then(|v| v.as_u64())
|
.and_then(|v| v.as_u64())
|
||||||
.unwrap_or(DEFAULT_TIMEOUT_SECS)
|
.unwrap_or(DEFAULT_TIMEOUT_SECS)
|
||||||
.clamp(1, 3600);
|
.clamp(1, 3600);
|
||||||
@@ -268,4 +275,21 @@ mod tests {
|
|||||||
assert_eq!(d["function"]["name"], "shell_exec");
|
assert_eq!(d["function"]["name"], "shell_exec");
|
||||||
assert_eq!(d["function"]["parameters"]["required"][0], "command");
|
assert_eq!(d["function"]["parameters"]["required"][0], "command");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_cwd_falls_back_and_timeout_alias_accepted() {
|
||||||
|
// cwd:"" (or whitespace) must be None so the caller falls back to the
|
||||||
|
// session folder instead of Command::current_dir("") failing with ENOENT.
|
||||||
|
for cwd in ["", " "] {
|
||||||
|
let r = ShellRequest::from_args(&json!({"command":"ls","cwd":cwd})).unwrap();
|
||||||
|
assert_eq!(r.cwd, None, "cwd {cwd:?} should fall back");
|
||||||
|
}
|
||||||
|
// The manual spells `timeout`; accept it as an alias of timeout_secs.
|
||||||
|
let r = ShellRequest::from_args(&json!({"command":"ls","timeout":300})).unwrap();
|
||||||
|
assert_eq!(r.timeout, Duration::from_secs(300));
|
||||||
|
// timeout_secs wins when both are present.
|
||||||
|
let r = ShellRequest::from_args(&json!({"command":"ls","timeout":300,"timeout_secs":5}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.timeout, Duration::from_secs(5));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+104
-16
@@ -103,25 +103,43 @@ fn prefix_messages(
|
|||||||
// Tool/system turns stay untagged. Strip any tag the model echoed into
|
// Tool/system turns stay untagged. Strip any tag the model echoed into
|
||||||
// stored content so we never stack a second one (duplication loop).
|
// stored content so we never stack a second one (duplication loop).
|
||||||
let clean = strip_speaker_tags(&m.content);
|
let clean = strip_speaker_tags(&m.content);
|
||||||
let content = match m.role.as_str() {
|
let tool_calls = m
|
||||||
"user" => format!(
|
|
||||||
"{}{}",
|
|
||||||
speaker_prefix(user_name, m.created_at, tz_offset),
|
|
||||||
clean
|
|
||||||
),
|
|
||||||
"assistant" => format!(
|
|
||||||
"{}{}",
|
|
||||||
speaker_prefix(&sess.title, m.created_at, tz_offset),
|
|
||||||
clean
|
|
||||||
),
|
|
||||||
_ => clean,
|
|
||||||
};
|
|
||||||
let mut msg = text_message(role_of(&m.role), content);
|
|
||||||
msg.tool_calls = m
|
|
||||||
.tool_calls_json
|
.tool_calls_json
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.and_then(|s| serde_json::from_str(s).ok());
|
.and_then(|s| serde_json::from_str(s).ok());
|
||||||
messages.push(msg);
|
// A tool-call-only assistant turn carries no text: keep content None to
|
||||||
|
// match `agent::run_loop` (which pushed the model's message verbatim).
|
||||||
|
// Stamping a bare [SPEAKER] here would emit a spurious <|content_text|>
|
||||||
|
// block, priming empty speaker tags and diverging from the cached prefix.
|
||||||
|
let tool_only = m.role == "assistant" && clean.is_empty() && tool_calls.is_some();
|
||||||
|
let content = if tool_only {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
let text = match m.role.as_str() {
|
||||||
|
"user" => format!(
|
||||||
|
"{}{}",
|
||||||
|
speaker_prefix(user_name, m.created_at, tz_offset),
|
||||||
|
clean
|
||||||
|
),
|
||||||
|
"assistant" => format!(
|
||||||
|
"{}{}",
|
||||||
|
speaker_prefix(&sess.title, m.created_at, tz_offset),
|
||||||
|
clean
|
||||||
|
),
|
||||||
|
_ => clean,
|
||||||
|
};
|
||||||
|
Some(serde_json::Value::String(text))
|
||||||
|
};
|
||||||
|
messages.push(ChatMessage {
|
||||||
|
role: role_of(&m.role),
|
||||||
|
content,
|
||||||
|
// Restore the tool-call id so the template resolves the tool name from
|
||||||
|
// the preceding assistant turn (and the prefix matches run_loop).
|
||||||
|
tool_call_id: m.tool_call_id.clone(),
|
||||||
|
tool_calls,
|
||||||
|
name: None,
|
||||||
|
reasoning_content: None,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
messages
|
messages
|
||||||
}
|
}
|
||||||
@@ -326,6 +344,76 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn history_restores_tool_call_id_and_skips_speaker_on_tool_only_turns() {
|
||||||
|
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 calls = serde_json::json!([{
|
||||||
|
"id": "call_1", "type": "function",
|
||||||
|
"function": {"name": "shell_exec", "arguments": "{\"command\":\"ls\"}"}
|
||||||
|
}]);
|
||||||
|
let history = vec![
|
||||||
|
StoredMessage {
|
||||||
|
id: 1,
|
||||||
|
role: "user".into(),
|
||||||
|
content: "lista i file".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: "".into(),
|
||||||
|
reasoning_content: Some("penso".into()),
|
||||||
|
tool_calls_json: Some(calls.to_string()),
|
||||||
|
tool_call_id: None,
|
||||||
|
prompt_tokens: 0,
|
||||||
|
completion_tokens: 0,
|
||||||
|
created_at: 1_700_000_001,
|
||||||
|
},
|
||||||
|
StoredMessage {
|
||||||
|
id: 3,
|
||||||
|
role: "tool".into(),
|
||||||
|
content: "file.txt".into(),
|
||||||
|
reasoning_content: None,
|
||||||
|
tool_calls_json: None,
|
||||||
|
tool_call_id: Some("call_1".into()),
|
||||||
|
prompt_tokens: 0,
|
||||||
|
completion_tokens: 0,
|
||||||
|
created_at: 1_700_000_002,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
let prefix = compose_prefix(&sess, &history, "Federico", &[], &[]);
|
||||||
|
// BUG-05: the tool-only assistant turn has no text (no bare [SPEAKER] block).
|
||||||
|
let asst = prefix
|
||||||
|
.iter()
|
||||||
|
.find(|m| matches!(m.role, Role::Assistant))
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
asst.content.is_none(),
|
||||||
|
"tool-only turn must not carry a [SPEAKER] text block"
|
||||||
|
);
|
||||||
|
assert!(asst.tool_calls.is_some());
|
||||||
|
// BUG-04: the tool result keeps its id so the template resolves the name.
|
||||||
|
let tool = prefix
|
||||||
|
.iter()
|
||||||
|
.find(|m| matches!(m.role, Role::Tool))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(tool.tool_call_id.as_deref(), Some("call_1"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn format_stamp_known_dates_and_offset() {
|
fn format_stamp_known_dates_and_offset() {
|
||||||
assert_eq!(format_stamp(0, 0), "1970-01-01 00:00");
|
assert_eq!(format_stamp(0, 0), "1970-01-01 00:00");
|
||||||
|
|||||||
+12
-2
@@ -163,6 +163,8 @@ pub struct InklingDialect {
|
|||||||
think_acc: String,
|
think_acc: String,
|
||||||
end_ws: String,
|
end_ws: String,
|
||||||
emitted_visible: bool,
|
emitted_visible: bool,
|
||||||
|
/// Thinking already streamed live by `emit` (so `finish` must not re-emit it).
|
||||||
|
emitted_reasoning: bool,
|
||||||
/// How many tool frames have been rendered (diagnostics).
|
/// How many tool frames have been rendered (diagnostics).
|
||||||
pub calls: u32,
|
pub calls: u32,
|
||||||
}
|
}
|
||||||
@@ -228,6 +230,7 @@ impl InklingDialect {
|
|||||||
State::Think => {
|
State::Think => {
|
||||||
self.append_think(chunk);
|
self.append_think(chunk);
|
||||||
out.push(Out::reasoning(chunk));
|
out.push(Out::reasoning(chunk));
|
||||||
|
self.emitted_reasoning = true;
|
||||||
}
|
}
|
||||||
State::ThinkEnd => {
|
State::ThinkEnd => {
|
||||||
if chunk.trim().is_empty() {
|
if chunk.trim().is_empty() {
|
||||||
@@ -237,6 +240,7 @@ impl InklingDialect {
|
|||||||
let combined = format!("{}{}{}", tag::END_MESSAGE, self.end_ws, chunk);
|
let combined = format!("{}{}{}", tag::END_MESSAGE, self.end_ws, chunk);
|
||||||
self.append_think(&combined);
|
self.append_think(&combined);
|
||||||
out.push(Out::reasoning(combined));
|
out.push(Out::reasoning(combined));
|
||||||
|
self.emitted_reasoning = true;
|
||||||
self.end_ws.clear();
|
self.end_ws.clear();
|
||||||
self.state = State::Think;
|
self.state = State::Think;
|
||||||
}
|
}
|
||||||
@@ -318,6 +322,10 @@ impl InklingDialect {
|
|||||||
State::ThinkEnd => {
|
State::ThinkEnd => {
|
||||||
let held = format!("{}{}", tag::END_MESSAGE, self.end_ws);
|
let held = format!("{}{}", tag::END_MESSAGE, self.end_ws);
|
||||||
self.append_think(&held);
|
self.append_think(&held);
|
||||||
|
// Stream the quoted end-message live (mirrors TextEnd below):
|
||||||
|
// it is thinking text, not a channel end, and must not be lost.
|
||||||
|
out.push(Out::reasoning(held));
|
||||||
|
self.emitted_reasoning = true;
|
||||||
self.end_ws.clear();
|
self.end_ws.clear();
|
||||||
}
|
}
|
||||||
State::Text => {
|
State::Text => {
|
||||||
@@ -424,11 +432,13 @@ impl InklingDialect {
|
|||||||
self.emitted_visible = true;
|
self.emitted_visible = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// #6682: budget expired inside thinking with no visible answer yet:
|
// #6682: budget expired inside thinking with no visible answer yet.
|
||||||
// surface the truncated thinking rather than an empty 200 OK.
|
// Thinking is streamed live by `emit`, so only surface the buffer if
|
||||||
|
// it was somehow NOT streamed — never duplicate the live CoT (BUG-06).
|
||||||
State::Think | State::ThinkEnd
|
State::Think | State::ThinkEnd
|
||||||
if reason == Some("length")
|
if reason == Some("length")
|
||||||
&& !self.emitted_visible
|
&& !self.emitted_visible
|
||||||
|
&& !self.emitted_reasoning
|
||||||
&& !think.trim().is_empty() =>
|
&& !think.trim().is_empty() =>
|
||||||
{
|
{
|
||||||
out.push(Out::reasoning(think));
|
out.push(Out::reasoning(think));
|
||||||
|
|||||||
@@ -133,8 +133,15 @@ impl Detok {
|
|||||||
/// Flush whatever is left (including any held replacement) at end of stream.
|
/// Flush whatever is left (including any held replacement) at end of stream.
|
||||||
pub fn finish(&mut self) -> String {
|
pub fn finish(&mut self) -> String {
|
||||||
let full = self.tok.decode_all(&self.ids).unwrap_or_default();
|
let full = self.tok.decode_all(&self.ids).unwrap_or_default();
|
||||||
if full.len() > self.emitted {
|
// `emitted` was a char boundary in an earlier decode; floor it to one in
|
||||||
let piece = full[self.emitted..].to_string();
|
// case the suffix re-aligned (an incomplete code point resolved at EOF),
|
||||||
|
// so the slice can never panic.
|
||||||
|
let mut start = self.emitted.min(full.len());
|
||||||
|
while start > 0 && !full.is_char_boundary(start) {
|
||||||
|
start -= 1;
|
||||||
|
}
|
||||||
|
if full.len() > start {
|
||||||
|
let piece = full[start..].to_string();
|
||||||
self.emitted = full.len();
|
self.emitted = full.len();
|
||||||
piece
|
piece
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+47
-2
@@ -346,6 +346,9 @@ impl SqliteStore {
|
|||||||
conn.pragma_update(None, "journal_mode", "WAL")?;
|
conn.pragma_update(None, "journal_mode", "WAL")?;
|
||||||
conn.pragma_update(None, "synchronous", "NORMAL")?;
|
conn.pragma_update(None, "synchronous", "NORMAL")?;
|
||||||
conn.pragma_update(None, "foreign_keys", "ON")?;
|
conn.pragma_update(None, "foreign_keys", "ON")?;
|
||||||
|
// Wait briefly for a concurrent writer (e.g. an external reader/tool in
|
||||||
|
// WAL) instead of failing immediately with SQLITE_BUSY.
|
||||||
|
conn.pragma_update(None, "busy_timeout", 5000)?;
|
||||||
conn.execute_batch(SCHEMA)?;
|
conn.execute_batch(SCHEMA)?;
|
||||||
migrate(&conn)?;
|
migrate(&conn)?;
|
||||||
seed_context_sections(&conn)?;
|
seed_context_sections(&conn)?;
|
||||||
@@ -637,13 +640,16 @@ impl Store for SqliteStore {
|
|||||||
fn stats(&self) -> Result<Stats> {
|
fn stats(&self) -> Result<Stats> {
|
||||||
let conn = self.lock();
|
let conn = self.lock();
|
||||||
let sessions: i64 = conn.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))?;
|
let sessions: i64 = conn.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))?;
|
||||||
// Totals + tool-call count in one pass. tool_calls_json is always a JSON
|
// Totals + tool-call count in one pass. tool_calls_json is a JSON array
|
||||||
// array of calls (or NULL); json_array_length counts the calls themselves.
|
// of calls (or NULL); guard with json_valid/json_type so one corrupt or
|
||||||
|
// non-array row cannot fail the whole stats query.
|
||||||
let (messages, prompt, completion, tool_calls): (i64, i64, i64, i64) = conn.query_row(
|
let (messages, prompt, completion, tool_calls): (i64, i64, i64, i64) = conn.query_row(
|
||||||
"SELECT COUNT(*),
|
"SELECT COUNT(*),
|
||||||
COALESCE(SUM(prompt_tokens),0),
|
COALESCE(SUM(prompt_tokens),0),
|
||||||
COALESCE(SUM(completion_tokens),0),
|
COALESCE(SUM(completion_tokens),0),
|
||||||
COALESCE(SUM(CASE WHEN tool_calls_json IS NOT NULL
|
COALESCE(SUM(CASE WHEN tool_calls_json IS NOT NULL
|
||||||
|
AND json_valid(tool_calls_json)
|
||||||
|
AND json_type(tool_calls_json) = 'array'
|
||||||
THEN json_array_length(tool_calls_json) ELSE 0 END),0)
|
THEN json_array_length(tool_calls_json) ELSE 0 END),0)
|
||||||
FROM messages",
|
FROM messages",
|
||||||
[],
|
[],
|
||||||
@@ -975,6 +981,45 @@ mod tests {
|
|||||||
assert_eq!(st.daily[0].completion_tokens, 5);
|
assert_eq!(st.daily[0].completion_tokens, 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stats_survives_a_corrupt_tool_calls_row() {
|
||||||
|
let s = store();
|
||||||
|
let sess = s
|
||||||
|
.create_session("Chat", "m", &SessionSettings::default())
|
||||||
|
.unwrap();
|
||||||
|
// A corrupt (non-JSON) tool_calls_json row must not fail the whole query.
|
||||||
|
s.append_message(
|
||||||
|
&sess.id,
|
||||||
|
NewMessage {
|
||||||
|
role: "assistant",
|
||||||
|
content: "x",
|
||||||
|
reasoning_content: None,
|
||||||
|
tool_calls_json: Some("not-json"),
|
||||||
|
tool_call_id: None,
|
||||||
|
prompt_tokens: 1,
|
||||||
|
completion_tokens: 1,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
// A valid array still counts.
|
||||||
|
s.append_message(
|
||||||
|
&sess.id,
|
||||||
|
NewMessage {
|
||||||
|
role: "assistant",
|
||||||
|
content: "y",
|
||||||
|
reasoning_content: None,
|
||||||
|
tool_calls_json: Some(r#"[{"id":"1"}]"#),
|
||||||
|
tool_call_id: None,
|
||||||
|
prompt_tokens: 1,
|
||||||
|
completion_tokens: 1,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let st = s.stats().unwrap();
|
||||||
|
assert_eq!(st.messages, 2);
|
||||||
|
assert_eq!(st.tool_calls, 1); // corrupt row skipped, valid array counted
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn settings_instance_and_name_lock() {
|
fn settings_instance_and_name_lock() {
|
||||||
let s = store();
|
let s = store();
|
||||||
|
|||||||
@@ -214,7 +214,9 @@ fn truncated_tool_falls_back_to_header_name() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn thinking_only_at_length_surfaces_reasoning() {
|
fn thinking_only_at_length_surfaces_reasoning() {
|
||||||
// #6682: budget expires mid-thinking with no answer.
|
// #6682: budget expires mid-thinking with no answer. Thinking is streamed
|
||||||
|
// live by emit(), so finish() must NOT re-emit it: the whole CoT appears
|
||||||
|
// exactly once (BUG-06 — duplication was amplified by the 16384 budget).
|
||||||
let outs = run(
|
let outs = run(
|
||||||
&[
|
&[
|
||||||
(tag::MESSAGE_MODEL, true),
|
(tag::MESSAGE_MODEL, true),
|
||||||
@@ -224,9 +226,34 @@ fn thinking_only_at_length_surfaces_reasoning() {
|
|||||||
Some("length"),
|
Some("length"),
|
||||||
);
|
);
|
||||||
assert!(content_of(&outs).is_empty());
|
assert!(content_of(&outs).is_empty());
|
||||||
// the live delta plus the finish-time accumulation both carry it (faithful
|
assert_eq!(
|
||||||
// to the reference: patched emit + _finish_typed #6682)
|
reasoning_of(&outs),
|
||||||
assert!(reasoning_of(&outs).contains("pondering"));
|
"pondering",
|
||||||
|
"thinking must appear exactly once, not duplicated at finish"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn quoted_end_message_in_think_end_streams_live() {
|
||||||
|
// #6675: two consecutive end-messages in thinking — the first is quoted text
|
||||||
|
// and must surface in reasoning live (mirrors TextEnd), not be lost.
|
||||||
|
let outs = run(
|
||||||
|
&[
|
||||||
|
(tag::MESSAGE_MODEL, true),
|
||||||
|
(tag::CONTENT_THINKING, true),
|
||||||
|
("x", false),
|
||||||
|
(tag::END_MESSAGE, true),
|
||||||
|
(tag::END_MESSAGE, true),
|
||||||
|
],
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
let r = reasoning_of(&outs);
|
||||||
|
assert!(r.contains('x'), "{r}");
|
||||||
|
assert!(
|
||||||
|
r.contains(tag::END_MESSAGE),
|
||||||
|
"quoted tag must stream live: {r}"
|
||||||
|
);
|
||||||
|
assert!(content_of(&outs).is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
Reference in new issue
Block a user