Skip to content
Open
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
53 changes: 53 additions & 0 deletions crates/vector-core/src/community/v2/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32985,6 +32985,59 @@ mod tests {
assert!(none_left.is_empty());
}

/// `Channel::history` (vector-sdk) is `VectorCore::get_messages_before`, and its doc says it
/// answers from the bot's own store. A restart opens the same account's database in a fresh
/// session, so STATE starts empty and the pages have to come from the store.
#[tokio::test]
async fn history_reads_the_store_after_a_restart() {
/// The whole history, read back page by page with `history_before`'s cursor.
async fn walk(chan: &str, limit: usize) -> Vec<String> {
let (mut seen, mut cursor) = (Vec::new(), None::<(u64, String)>);
for _ in 0..20 {
let page = crate::VectorCore.get_messages_before(chan, cursor.as_ref().map(|(at, id)| (*at, id.as_str())), limit).await;
let Some(oldest) = page.first() else { break };
cursor = Some((oldest.at, oldest.id.clone()));
seen.splice(0..0, page.into_iter().map(|m| m.content));
}
seen
}
let (bed, owner, _member) = TestBed::new();
bed.swap_to(&owner);
let community = create_community(&bed.relay, "Restart", bed.relays.clone(), None).await.unwrap();
let general = community.channels[0].id;
let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = channel_group_key(&community.community_root, &general, community.root_epoch);
let peer = Keys::generate();
let at = now_ms() - 60_000;
// Two in one millisecond (the id breaks the tie), one later in that second, one seconds before.
let wraps: Vec<Event> = [("old", at - 5_000), ("wall-1", at), ("wall-2", at), ("next", at + 1)]
.into_iter()
.map(|(text, at)| {
let rumor = chat::build_message_rumor(peer.public_key(), &general, community.root_epoch, text, None, &[], vec![], at);
chat::seal_chat_rumor(&rumor, &group, &peer, Timestamp::from_secs(at / 1000), false).unwrap().0
})
.collect();
let page = || wraps.iter().map(|w| FetchedEvent { event: chat::open_chat_event(w, &group, &general, community.root_epoch).unwrap(), epoch: community.root_epoch, wrap: Some(w.clone()) }).collect::<Vec<_>>();
let mut order: Vec<(u64, String, String)> = page().iter().map(|f| (f.event.opened().at_ms, f.event.opened().rumor_id.to_hex(), f.event.opened().rumor.content.clone())).collect();
order.sort();
let expected: Vec<String> = order.iter().map(|(_, _, text)| text.clone()).collect();
let me = owner.keys.public_key();

crate::VectorCore::v2_ingest_chat_page(&chan_hex, me, crate::db::current_session(), page()).await;
assert_eq!(walk(&chan_hex, 1).await, expected, "read back in the same process");

// The restart: the same account's database, a fresh session.
bed.swap_to(&owner);
assert!(crate::VectorCore.get_message(&order[0].1).await.is_some(), "the rows are still in the store");
let whole: Vec<String> = crate::VectorCore.get_messages_before(&chan_hex, None, 10).await.into_iter().map(|m| m.content).collect();
let one_by_one = walk(&chan_hex, 1).await;
// The same page again, as a Channel::sync back-page brings it: the store already holds it.
let new = crate::VectorCore::v2_ingest_chat_page(&chan_hex, me, crate::db::current_session(), page()).await;
let after_sync = walk(&chan_hex, 2).await;
eprintln!("after restart: {whole:?} / {one_by_one:?} | page again: new={new} | after it: {after_sync:?}");
assert_eq!((whole, one_by_one, after_sync), (expected.clone(), expected.clone(), expected), "history answers from the store after a restart");
}

#[tokio::test]
async fn a_page_judged_before_a_stop_landed_is_judged_again_as_it_lands() {
use crate::community::roles::OverwriteTarget;
Expand Down
64 changes: 64 additions & 0 deletions crates/vector-core/src/db/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1897,6 +1897,70 @@ pub async fn get_messages_around(
compose_message_views(decrypted).await
}

/// Up to `limit` stored messages strictly before the `(at_ms, id)` cursor, chronological; `None`
/// reads the newest. The store's half of [`crate::VectorCore::get_messages_before`], in its order:
/// the cursor is compared by value, so it needs no row of its own.
///
/// SQL sees whole seconds, while `at` carries the milliseconds and the id breaks a tie. So the
/// query reads every row of each second it reaches, and the exact order is kept here.
pub async fn get_messages_before(
chat_id: i64,
before: Option<(u64, &str)>,
limit: usize,
) -> Result<Vec<Message>, String> {
if limit == 0 {
return Ok(Vec::new());
}
let message_kinds = [event_kind::CHAT_MESSAGE, event_kind::PRIVATE_DIRECT_MESSAGE, event_kind::FILE_ATTACHMENT];
// The cursor's own second is read whole; the `limit` newest rows below it decide how deep.
let top = before.map_or(i64::MAX, |(at, _)| (at / 1000) as i64);

let message_events: Vec<StoredEvent> = {
let conn = super::get_db_connection_guard_static()?;
let community = ban_param(&conn, chat_id);
// Kinds occupy ?2..?4; then ?5 the top second, ?6 the deepest row's offset, ?7 the bans.
let in_chat = "chat_id = ?1 AND kind IN (?2, ?3, ?4)";
let sql = format!(
"SELECT id, kind, chat_id, user_id, content, tags, reference_id, \
created_at, received_at, mine, pending, failed, wrapper_event_id, npub, preview_metadata \
FROM events WHERE {in_chat}{bans} AND created_at <= ?5 \
AND created_at >= COALESCE((SELECT created_at FROM events WHERE {in_chat}{bans} AND created_at < ?5 \
ORDER BY created_at DESC LIMIT 1 OFFSET ?6), 0)",
bans = ban_filter_sql(7)
);
let mut stmt = conn.prepare(&sql)
.map_err(|e| format!("Failed to prepare page query: {}", e))?;
let rows = stmt.query_map(
rusqlite::params![
chat_id,
message_kinds[0] as i32, message_kinds[1] as i32, message_kinds[2] as i32,
top, (limit - 1) as i64, community
],
parse_event_row,
).map_err(|e| format!("Failed to query page: {}", e))?;
rows.filter_map(|r| r.ok()).collect()
};

// Decrypt message content (mirror get_events).
let decrypted: Vec<StoredEvent> = crate::crypto::open_batch(|at_rest| message_events.into_iter().map(|mut event| {
if event.kind == event_kind::CHAT_MESSAGE || event.kind == event_kind::PRIVATE_DIRECT_MESSAGE {
event.content = at_rest.open(event.content)
.unwrap_or_else(|_| "[Decryption failed]".to_string());
}
event
}).collect());

let mut messages = compose_message_views(decrypted).await?;
if let Some((at, id)) = before {
messages.retain(|m| (m.at, m.id.as_str()) < (at, id));
}
messages.sort_by(|a, b| (a.at, a.id.as_str()).cmp(&(b.at, b.id.as_str())));
if messages.len() > limit {
messages.drain(..messages.len() - limit);
}
Ok(messages)
}

/// Where a message sits in its chat: how many messages sort after it and how many there are,
/// in the order and under the ban filter `get_messages_around` uses. None when it isn't held.
#[derive(serde::Serialize, Debug, PartialEq, Eq)]
Expand Down
25 changes: 21 additions & 4 deletions crates/vector-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1574,17 +1574,34 @@ impl VectorCore {
/// id tiebreaks inside a same-millisecond burst, giving a total order that
/// can't skip or re-serve across pages. Local only: sync older history in
/// from relays first.
///
/// STATE holds only a window (after a restart, nothing from before it), so
/// the store is read too. STATE's copy of a message wins: it holds what was
/// just applied and not yet saved.
pub async fn get_messages_before(
&self,
chat_id: &str,
before: Option<(u64, &str)>,
limit: usize,
) -> Vec<Message> {
let state = state::STATE.lock().await;
let Some(chat) = state.get_chat(chat_id) else {
return Vec::new();
let mut page = {
let state = state::STATE.lock().await;
match state.get_chat(chat_id) {
Some(chat) => page_before(chat.messages.messages(), &state.interner, before, limit),
None => Vec::new(),
}
};
let stored = match crate::db::id_cache::get_chat_id_by_identifier(chat_id) {
Ok(chat) => crate::db::events::get_messages_before(chat, before, limit).await.unwrap_or_default(),
Err(_) => Vec::new(),
};
page_before(chat.messages.messages(), &state.interner, before, limit)
let held: std::collections::HashSet<String> = page.iter().map(|m| m.id.clone()).collect();
page.extend(stored.into_iter().filter(|m| !held.contains(&m.id)));
page.sort_by(|a, b| (a.at, a.id.as_str()).cmp(&(b.at, b.id.as_str())));
if page.len() > limit {
page.drain(..page.len() - limit);
}
page
}

/// Get a profile by npub.
Expand Down
Loading