mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
perf(mobile): search borrowed document views without cloning
Add SearchDocumentRef and WeightedSearchEngine::search_refs so callers search live records by reference. Keep WeightedSearchEngine::search as a wrapper with identical scores, tie-breaking, and UTF-16 highlight spans. Route MobileAppState::search_hits through search_refs to remove per-query title, tag, and preview clones.
This commit is contained in:
1 parent
9a158a3086
commit
afdc4c0f54
2 files changed
+147
-19
No files matched your search
@@ -31,6 +31,29 @@ pub struct SearchDocument {
|
||||
pub updated_at_ms: i64,
|
||||
}
|
||||
|
||||
/// Borrowed view of a [`SearchDocument`], so callers can search their own records without
|
||||
/// cloning them.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct SearchDocumentRef<'a> {
|
||||
pub id: &'a str,
|
||||
pub title: &'a str,
|
||||
pub tags: &'a [String],
|
||||
pub body_preview: &'a str,
|
||||
pub updated_at_ms: i64,
|
||||
}
|
||||
|
||||
impl<'a> From<&'a SearchDocument> for SearchDocumentRef<'a> {
|
||||
fn from(doc: &'a SearchDocument) -> Self {
|
||||
Self {
|
||||
id: &doc.id,
|
||||
title: &doc.title,
|
||||
tags: &doc.tags,
|
||||
body_preview: &doc.body_preview,
|
||||
updated_at_ms: doc.updated_at_ms,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ranked search result from [`WeightedSearchEngine::search`].
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SearchHit {
|
||||
@@ -62,14 +85,24 @@ impl WeightedSearchEngine {
|
||||
}
|
||||
|
||||
pub fn search(&self, docs: &[SearchDocument], query: &str, limit: usize) -> Vec<SearchHit> {
|
||||
self.search_refs(docs.iter().map(SearchDocumentRef::from), query, limit)
|
||||
}
|
||||
|
||||
/// Ranks borrowed documents by the same rules as [`Self::search`].
|
||||
pub fn search_refs<'a>(
|
||||
&self,
|
||||
docs: impl IntoIterator<Item = SearchDocumentRef<'a>>,
|
||||
query: &str,
|
||||
limit: usize,
|
||||
) -> Vec<SearchHit> {
|
||||
let mut hits = Vec::new();
|
||||
let prepared = PreparedQuery::new(query);
|
||||
|
||||
for doc in docs {
|
||||
if query.is_empty() {
|
||||
hits.push(SearchHit {
|
||||
doc_id: doc.id.clone(),
|
||||
title: doc.title.clone(),
|
||||
doc_id: doc.id.to_owned(),
|
||||
title: doc.title.to_owned(),
|
||||
score: 0.0,
|
||||
title_highlights: Vec::new(),
|
||||
matched_tags: Vec::new(),
|
||||
@@ -82,7 +115,7 @@ impl WeightedSearchEngine {
|
||||
let mut total_score = 0.0;
|
||||
let mut matched = false;
|
||||
|
||||
let title_highlights = if let Some((dist, spans)) = prepared.match_utf16(&doc.title) {
|
||||
let title_highlights = if let Some((dist, spans)) = prepared.match_utf16(doc.title) {
|
||||
matched = true;
|
||||
total_score += self.weights.title * (1.0 - dist);
|
||||
spans
|
||||
@@ -91,7 +124,7 @@ impl WeightedSearchEngine {
|
||||
};
|
||||
|
||||
let mut matched_tags = Vec::new();
|
||||
for tag in &doc.tags {
|
||||
for tag in doc.tags {
|
||||
if let Some((dist, _)) = prepared.match_utf16(tag) {
|
||||
matched = true;
|
||||
total_score += self.weights.tags * (1.0 - dist);
|
||||
@@ -100,7 +133,7 @@ impl WeightedSearchEngine {
|
||||
}
|
||||
|
||||
let body_highlights =
|
||||
if let Some((dist, spans)) = prepared.match_utf16(&doc.body_preview) {
|
||||
if let Some((dist, spans)) = prepared.match_utf16(doc.body_preview) {
|
||||
matched = true;
|
||||
total_score += self.weights.body * (1.0 - dist);
|
||||
spans
|
||||
@@ -110,8 +143,8 @@ impl WeightedSearchEngine {
|
||||
|
||||
if matched {
|
||||
hits.push(SearchHit {
|
||||
doc_id: doc.id.clone(),
|
||||
title: doc.title.clone(),
|
||||
doc_id: doc.id.to_owned(),
|
||||
title: doc.title.to_owned(),
|
||||
score: total_score,
|
||||
title_highlights,
|
||||
matched_tags,
|
||||
@@ -165,6 +198,46 @@ mod tests {
|
||||
assert_eq!(hit.score, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn borrowed_search_ranks_like_owned_search_with_top_k_prefixes() {
|
||||
let doc =
|
||||
|id: &str, title: &str, tags: &[&str], body: &str, updated_at_ms| SearchDocument {
|
||||
id: id.into(),
|
||||
title: title.into(),
|
||||
tags: tags.iter().map(|t| (*t).into()).collect(),
|
||||
body_preview: body.into(),
|
||||
updated_at_ms,
|
||||
};
|
||||
let docs = [
|
||||
doc("a", "Spec", &["spec"], "spec spec", 10),
|
||||
doc("b", "Spec Document", &[], "aa", 20),
|
||||
doc("c", "Notes", &["SPEC"], "Spec body", 20),
|
||||
doc("d", "İstanbul", &["ıi"], "Straße file", 5),
|
||||
doc("e", "\u{212A}elvin ΟΣ", &["ΟΣΑ"], "猫 spec", 5),
|
||||
doc("f", "😀a", &["🚀"], "前🚀猫后", 30),
|
||||
doc("g", "abab", &[], "", 30),
|
||||
];
|
||||
let engine = WeightedSearchEngine::default();
|
||||
let queries = [
|
||||
"", "spec", "Spe", "a", "ab", "i", "İ", "ss", "ß", "fi", "k", "ος", "σ", "猫", "😀",
|
||||
"🚀猫",
|
||||
];
|
||||
for query in queries {
|
||||
let owned = engine.search(&docs, query, 0);
|
||||
let borrowed = engine.search_refs(docs.iter().map(SearchDocumentRef::from), query, 0);
|
||||
assert_eq!(borrowed, owned, "query={query:?}");
|
||||
for limit in 1..=docs.len() {
|
||||
let top =
|
||||
engine.search_refs(docs.iter().map(SearchDocumentRef::from), query, limit);
|
||||
assert_eq!(
|
||||
top,
|
||||
owned[..limit.min(owned.len())],
|
||||
"query={query:?} limit={limit}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_substring_weighted_search_rejects_typos_and_ranks_title_above_body() {
|
||||
let engine = WeightedSearchEngine::default();
|
||||
|
||||
@@ -12,7 +12,7 @@ use std::{
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use affine_client::{SearchDocument, SearchHit, WorkspaceBreadcrumbSnapshot};
|
||||
use affine_client::{SearchHit, WorkspaceBreadcrumbSnapshot, search::SearchDocumentRef};
|
||||
|
||||
use super::MobileAppState;
|
||||
use crate::{explorer_model::ExplorerModel, home_model::HomeModel, strings::MobileLocale};
|
||||
@@ -189,21 +189,20 @@ impl MobileAppState {
|
||||
&ws.derived.search_builds,
|
||||
|key| key.docs_rev == docs_rev && key.query == self.search_query,
|
||||
|| {
|
||||
let docs: Vec<SearchDocument> = ws
|
||||
let docs = ws
|
||||
.docs()
|
||||
.iter()
|
||||
.filter(|d| !d.trashed)
|
||||
.map(|d| SearchDocument {
|
||||
id: d.id.clone(),
|
||||
title: d.title.clone(),
|
||||
tags: d.tags.clone(),
|
||||
body_preview: d.body_preview.clone(),
|
||||
.map(|d| SearchDocumentRef {
|
||||
id: &d.id,
|
||||
title: &d.title,
|
||||
tags: &d.tags,
|
||||
body_preview: &d.body_preview,
|
||||
updated_at_ms: d.updated_at_ms,
|
||||
})
|
||||
.collect();
|
||||
let hits = self
|
||||
.search_engine
|
||||
.search(&docs, &self.search_query, SEARCH_HIT_LIMIT);
|
||||
});
|
||||
let hits =
|
||||
self.search_engine
|
||||
.search_refs(docs, &self.search_query, SEARCH_HIT_LIMIT);
|
||||
let key = SearchKey {
|
||||
query: self.search_query.clone(),
|
||||
docs_rev,
|
||||
@@ -328,3 +327,59 @@ fn build_drawer_sections(state: &MobileAppState) -> DrawerSections {
|
||||
sections.recent = recent.into_iter().map(|(_, _, d)| row(d)).collect();
|
||||
sections
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use affine_client::SearchDocument;
|
||||
use ui_tokens::ThemeMode;
|
||||
|
||||
use crate::{MobileDocRecord, MobileLocale, seed_showcase_state};
|
||||
|
||||
#[test]
|
||||
fn search_hits_borrow_live_docs_and_rebuild_once_per_query_change() {
|
||||
let mut state = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-25");
|
||||
let ws = state.active_workspace_mut();
|
||||
ws.docs_mut().extend((0..64).map(|i| MobileDocRecord {
|
||||
id: format!("doc-spec-{i:02}"),
|
||||
title: format!("Spec Document #{i:02}"),
|
||||
body_preview: format!("Body for spec {i}"),
|
||||
tags: vec!["SPEC".into()],
|
||||
updated_at_ms: 1_000 + i,
|
||||
is_favorite: false,
|
||||
trashed: i % 7 == 0,
|
||||
journal_date: None,
|
||||
clock: 1,
|
||||
outgoing_edges: Vec::new(),
|
||||
blocks: Vec::new(),
|
||||
}));
|
||||
let owned: Vec<SearchDocument> = state
|
||||
.active_workspace()
|
||||
.docs()
|
||||
.iter()
|
||||
.filter(|d| !d.trashed)
|
||||
.map(|d| SearchDocument {
|
||||
id: d.id.clone(),
|
||||
title: d.title.clone(),
|
||||
tags: d.tags.clone(),
|
||||
body_preview: d.body_preview.clone(),
|
||||
updated_at_ms: d.updated_at_ms,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let builds = |s: &crate::MobileAppState| s.work_stats().search_builds;
|
||||
let start = builds(&state);
|
||||
for (step, query) in ["Spe", "Spec", "Spe", "Spec", "spec 6", "", "猫"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
state.search_query = query.into();
|
||||
let hits = state.search_hits();
|
||||
let expected = state
|
||||
.search_engine
|
||||
.search(&owned, query, super::SEARCH_HIT_LIMIT);
|
||||
assert_eq!(*hits, expected, "query={query:?}");
|
||||
assert!(std::sync::Arc::ptr_eq(&hits, &state.search_hits()));
|
||||
assert_eq!(builds(&state) - start, step as u64 + 1, "query={query:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user