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
8 changes: 4 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions docs/file-history.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ is limited to 50 events and does not establish complete coverage.

Structured target mode includes all event kinds by default, with command
candidates excluded unless `include_command_candidates` is true. An explicit
`kind` filters the event kind. The default page holds 20 events, at most 50.
`kind` filters the event kind. The default page holds up to 20 events within an
8,800-byte UTF-8 response budget, and an explicit `limit` accepts 1 to 50.
Repeat the same target, path, source, kind, and candidate selection with
`next_cursor` until `has_more` is false. Target-relevant index changes invalidate
the cursor; restart the query rather than joining incompatible pages. Known
Expand Down Expand Up @@ -63,13 +64,13 @@ Copy `events[].evidence.event_ref` and the hit's `session_id` into MCP
`get_session`:

```json
{"session_id":"<session-id>","event_ref":"<opaque-event-ref>","evidence_part":"payload","max_bytes":16384}
{"session_id":"<session-id>","event_ref":"<opaque-event-ref>","evidence_part":"payload","max_bytes":8800}
```

Concatenate each page's UTF-8 `data` in byte-offset order before parsing the
payload JSON. Continue with the same `session_id`, `event_ref`, `evidence_part`,
and the returned `next_cursor` as `cursor`. `max_bytes` bounds each evidence
response, defaults to 16,384, and accepts 1,024–65,536. Each read has a 64 MiB
response, defaults to 8,800, and accepts 1,024 to 65,536. Each read has a 64 MiB
budget; oversized evidence fails explicitly instead of returning a complete
prefix. References identify an immutable event within one index. Any rebuild
of that event invalidates its reference, even if its content is identical;
Expand Down
10 changes: 6 additions & 4 deletions docs/session.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,10 +266,12 @@ full-content output. Bounds and role filtering are applied in SQLite.

MCP exposes the same message search as `search_messages`. Pass `around_seq`,
`before`, and `after` to `get_session`, or use `from_seq` / `to_seq`. Selected
MCP reads default to at most 50 messages and 6,000 content characters;
`max_chars` may lower this budget. `next_cursor` continues the selected window.
Selectors and cursor cannot be combined with `tail`. Legacy `get_session`
head/tail calls retain their existing text format and limits.
MCP reads return at most 50 messages and 6,000 content characters within an
8,800-byte UTF-8 response budget. Set `max_chars` to lower the character
budget. `next_cursor` continues the selected window. Default discovery and
message-search calls also fit within 8,800 UTF-8 bytes. Selectors and cursor
cannot be combined with `tail`. Legacy `get_session` head/tail calls retain
their existing text format and limits.

### `recall session export`

Expand Down
197 changes: 64 additions & 133 deletions src/db/message_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,35 @@ pub(crate) struct MessageRead<'a> {
pub(crate) role: Option<&'a str>,
pub(crate) max_messages: usize,
pub(crate) max_chars: usize,
pub(crate) max_rendered_bytes: Option<usize>,
pub(crate) cursor: Option<&'a str>,
}

pub(crate) fn json_escaped_char_bytes(ch: char) -> usize {
match ch {
'"' | '\\' | '\x08' | '\x0c' | '\n' | '\r' | '\t' => 2,
c if (c as u32) < 0x20 => 6,
c => c.len_utf8(),
}
}

pub(crate) fn json_escaped_str_bytes(text: &str) -> usize {
text.chars().map(json_escaped_char_bytes).sum()
}

fn decimal_digits(mut value: usize) -> usize {
let mut digits = 1;
while value >= 10 {
value /= 10;
digits += 1;
}
digits
}

fn rendered_prefix_bytes(seq: u32, role: &Role) -> usize {
decimal_digits(seq as usize) + role.as_str().len() + 5
}

impl Store {
pub(crate) fn get_messages_in_window(
&self,
Expand Down Expand Up @@ -191,6 +217,7 @@ impl Store {
let mut messages = Vec::new();
let first_message_byte_offset = cursor.byte_offset;
let mut remaining = read.max_chars;
let mut remaining_bytes = read.max_rendered_bytes;
let mut stmt = tx.prepare(
"SELECT id, seq, role, timestamp, length(CAST(content AS BLOB)),
COALESCE(substr(CAST(content AS BLOB), ?7 + 1, ?8), X'')
Expand All @@ -200,6 +227,8 @@ impl Store {
ORDER BY seq, id LIMIT 1",
)?;
let has_more = loop {
let fetch_bytes = (remaining.max(1) * 4)
.min(remaining_bytes.map_or(usize::MAX, |budget| budget.saturating_add(4)));
let row = stmt
.query_row(
params![
Expand All @@ -210,7 +239,7 @@ impl Store {
cursor.next_seq,
cursor.next_id,
cursor.byte_offset as i64,
(remaining.max(1) * 4) as i64
fetch_bytes as i64
],
|row| {
Ok((
Expand Down Expand Up @@ -240,8 +269,39 @@ impl Store {
}
Err(_) => bail!("invalid message cursor offset or message encoding"),
};
let content: String = text.chars().take(remaining).collect();
remaining -= content.chars().count();
let content = if let Some(rem_bytes) = remaining_bytes {
let sep_bytes = if messages.is_empty() { 0 } else { 4 };
let header_bytes = sep_bytes + rendered_prefix_bytes(seq, &role);
if !messages.is_empty() {
let min_needed =
header_bytes + text.chars().next().map_or(0, json_escaped_char_bytes);
if min_needed > rem_bytes {
break true;
}
}
let mut msg_budget = rem_bytes.saturating_sub(header_bytes);
let mut kept_chars = 0;
let mut kept_utf8 = 0;
for ch in text.chars().take(remaining) {
let cost = json_escaped_char_bytes(ch);
if kept_chars == 0 && messages.is_empty() {
msg_budget = msg_budget.saturating_sub(cost);
} else if cost <= msg_budget {
msg_budget -= cost;
} else {
break;
}
kept_chars += 1;
kept_utf8 += ch.len_utf8();
}
remaining -= kept_chars;
remaining_bytes = Some(msg_budget);
text[..kept_utf8].to_string()
} else {
let content: String = text.chars().take(remaining).collect();
remaining -= content.chars().count();
content
};
cursor.byte_offset += content.len();
messages.push(Message {
session_id: session_id.to_string(),
Expand All @@ -266,133 +326,4 @@ impl Store {
}

#[cfg(test)]
mod tests {
use super::*;

fn store_with_messages(messages: &[(u32, &str)]) -> Store {
crate::db::schema::register_sqlite_vec();
let store = Store::open_in_memory().unwrap();
store.conn.execute("INSERT INTO sessions (id, source, source_id, title, started_at) VALUES ('s', 'test', 's', 'Test', 0)", []).unwrap();
for (seq, content) in messages {
store.conn.execute("INSERT INTO messages (session_id, seq, role, content) VALUES ('s', ?1, 'assistant', ?2)", params![seq, content]).unwrap();
}
store
}

#[test]
fn around_counts_messages_across_gaps_and_stops_at_edges() {
let store = store_with_messages(&[(0, "a"), (10, "b"), (40, "c"), (90, "d"), (100, "e")]);
let window = MessageWindow {
around_seq: Some(40),
before: Some(1),
after: Some(1),
..Default::default()
};
let messages = store.get_messages_in_window("s", &window, None, 100, false).unwrap();
assert_eq!(messages.iter().map(|m| m.seq).collect::<Vec<_>>(), vec![10, 40, 90]);
let window = MessageWindow {
around_seq: Some(0),
before: Some(3),
after: Some(0),
..Default::default()
};
assert_eq!(store.get_messages_in_window("s", &window, None, 100, false).unwrap().len(), 1);
let missing = MessageWindow { around_seq: Some(11), ..Default::default() };
assert!(store.get_messages_in_window("s", &missing, None, 100, false).is_err());
let conflict =
MessageWindow { around_seq: Some(40), from_seq: Some(0), ..Default::default() };
assert!(store.get_messages_in_window("s", &conflict, None, 100, false).is_err());
store.conn.execute("INSERT INTO messages (session_id, seq, role, content) VALUES ('s', 40, 'user', 'duplicate')", []).unwrap();
assert!(
store
.get_messages_in_window(
"s",
&MessageWindow { around_seq: Some(40), ..Default::default() },
None,
100,
false
)
.is_err()
);
}

#[test]
fn pages_preserve_unicode_nul_empty_and_duplicate_sequence_messages() {
let input = [
(2, "\u{4f60}\u{597d}🦀e\u{301}\0end"),
(2, "second"),
(9, ""),
(100, "\u{6700}\u{540e}"),
];
let store = store_with_messages(&input);
for budget in 1..=12 {
let mut cursor = None;
let mut text = String::new();
let mut pages = 0;
loop {
let page = store
.read_message_page(
"s",
&MessageRead {
window: &MessageWindow::default(),
role: None,
max_messages: 2,
max_chars: budget,
cursor: cursor.as_deref(),
},
)
.unwrap();
assert!(page.messages.len() <= 2);
assert!(
page.messages.iter().map(|m| m.content.chars().count()).sum::<usize>()
<= budget
);
for message in page.messages {
text.push_str(&message.content);
}
pages += 1;
assert!(pages < 100);
cursor = page.next_cursor;
if cursor.is_none() {
break;
}
}
assert_eq!(text, input.iter().map(|(_, s)| *s).collect::<String>());
}
}

#[test]
fn cursor_keeps_selection_and_rejects_reindexed_messages() {
let store = store_with_messages(&[(0, "outside"), (5, "abcdefghij"), (10, "outside")]);
let window = MessageWindow { from_seq: Some(5), to_seq: Some(5), ..Default::default() };
let page = store
.read_message_page(
"s",
&MessageRead {
window: &window,
role: None,
max_messages: 2,
max_chars: 3,
cursor: None,
},
)
.unwrap();
assert_eq!(page.messages[0].content, "abc");
let read = MessageRead {
window: &MessageWindow::default(),
role: None,
max_messages: 2,
max_chars: 32,
cursor: page.next_cursor.as_deref(),
};
let rest = store.read_message_page("s", &read).unwrap();
assert_eq!(rest.first_message_byte_offset, 3);
assert_eq!(rest.messages.len(), 1);
assert_eq!(rest.messages[0].content, "defghij");
assert!(rest.next_cursor.is_none());
assert!(store.read_message_page("other", &read).is_err());
store.conn.execute("DELETE FROM messages WHERE session_id = 's' AND seq = 5", []).unwrap();
store.conn.execute("INSERT INTO messages (session_id, seq, role, content) VALUES ('s', 5, 'assistant', 'abcdefghij')", []).unwrap();
assert!(store.read_message_page("s", &read).is_err());
}
}
mod tests;
Loading