From 3bbac69479c4ea3e8ca7fa25fb454e6bfb186a86 Mon Sep 17 00:00:00 2001 From: DarkSky Date: Thu, 26 Nov 2026 06:34:59 +0900 Subject: [PATCH] fix(search): extract inline doc references like the v0.27.5 reader The search extractor did not read inline `reference` attributes in rich text, so a doc that links to another doc only through an inline mention did not show as a backlink. It also dropped `prop:params` of linked and synced doc embeds, and it did not index database columns, table cells or LaTeX. - Read the `reference` attribute of the visible runs in `prop:text` of paragraph, list and code blocks. Parse each `reference` format once, so a long run of text under one reference costs linear time. - Keep `ref` unique by its full string and push the `pageId` of each kept `ref` to `ref_doc_id`, so the two lists stay in step. Check database cells one at a time, as the reader does. - Serialize `ref` as `JSON.stringify({ docId, ...params })`. Spread strings and arrays by index, put index keys first, and format numbers as ECMAScript does. - Keep only the `docId` when the params are larger than 256 KiB, nest too deeply, have too many entries, or pass the 16 MiB budget of the block. Check duplicates by the hash of the full reference, so such a reference does not merge with a different reference to the same doc. - Merge `prop:params` into the `ref` of `affine:embed-linked-doc` and `affine:embed-synced-doc`, and keep an empty `pageId`. - Index the database title, column names and select options from `Y.Map` columns. Read cell references from `Y.Text` or from boxed text with a truthy marker. Add `databaseName` to database blocks and row paragraphs. - Read the text of each flavour as the old server does. Read rich text only from `Y.Text`. Index the table cells in key order and the LaTeX source. - A note, frame or edgeless text with no text of its own joins the text of its direct children, up to 1 MiB. Each child gives its text to one container only. - Index no text for doc embeds and bookmarks. Skip blocks with only white space, and keep bookmark blocks. - Raise `SCHEMA_FINGERPRINT` to 2, so that startup builds a new generation and reprojects docs that did not change. Retire drained generations of any schema version. - Move the `TestDoc` builder to `tests/support`. Test each flavour, the params spread, malformed input, the time for many runs and references, backlinks through `search` and `aggregate`, and the schema upgrade. --- .../backend/server-search/src/doc_extract.rs | 1393 +++++++++++++++-- .../src/doc_extract/reference.rs | 740 +++++++++ .../backend/server-search/src/generation.rs | 12 +- packages/backend/server-search/src/lib.rs | 4 +- .../server-search/tests/pg_integration.rs | 378 ++++- .../server-search/tests/support/test_doc.rs | 208 +++ 6 files changed, 2603 insertions(+), 132 deletions(-) create mode 100644 packages/backend/server-search/src/doc_extract/reference.rs create mode 100644 packages/backend/server-search/tests/support/test_doc.rs diff --git a/packages/backend/server-search/src/doc_extract.rs b/packages/backend/server-search/src/doc_extract.rs index 39f163e350..6bc2bd02cd 100644 --- a/packages/backend/server-search/src/doc_extract.rs +++ b/packages/backend/server-search/src/doc_extract.rs @@ -1,7 +1,10 @@ +mod reference; + use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque}; +use reference::{References, collect_cell_references, collect_text_references}; use serde::Serialize; -use serde_json::{Value as JsonValue, json}; +use serde_json::{Map as JsonMap, Value as JsonValue}; use sha2::{Digest, Sha256}; use y_octo::{Any, Doc, ReadDoc, ReadMap, ReadValue, Value}; @@ -10,6 +13,17 @@ use crate::error::{SearchError, SearchResult}; const MAX_SOURCE_BINARY_BYTES: usize = 32 * 1024 * 1024; const MAX_SOURCE_BLOCKS: usize = 100_000; const MAX_CHILDREN_PER_BLOCK: u64 = 10_000; +/// The most text bytes that one container takes from its children. +const MAX_DESCENDANT_TEXT_BYTES: usize = 1024 * 1024; +/// Flavours that the `v0.27.5` server indexes with no text. +const BOOKMARK_FLAVOURS: [&str; 6] = [ + "affine:bookmark", + "affine:embed-youtube", + "affine:embed-iframe", + "affine:embed-figma", + "affine:embed-github", + "affine:embed-loom", +]; #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] @@ -102,8 +116,8 @@ pub fn project_document_search(blob: Vec, doc_id: String) -> SearchResult, doc_id: String) -> SearchResult, Option)> = VecDeque::new(); let mut visited: HashSet = HashSet::new(); + let mut claimed_children: HashSet = HashSet::new(); for root_id in root_ids { if visited.insert(root_id.clone()) { queue.push_back((root_id, None, None)); @@ -122,7 +137,7 @@ pub fn project_document_search(blob: Vec, doc_id: String) -> SearchResult, doc_id: String) -> SearchResult, doc_id: String) -> SearchResult, block_id: &str, units: &mut Vec< let Some(elem) = elements.get(&key).and_then(|v| v.as_map()) else { continue; }; - let elem_id = read_string(elem, "id").unwrap_or_else(|| key.clone()); - let elem_type = read_string(elem, "type").unwrap_or_else(|| "surface-element".to_owned()); + let elem_id = read_text_field(elem, "id").unwrap_or_else(|| key.clone()); + let elem_type = read_text_field(elem, "type").unwrap_or_else(|| "surface-element".to_owned()); let mut parts = Vec::new(); for field in ["title", "text", "label"] { if let Some(t) = read_text_field(elem, field) @@ -250,65 +284,142 @@ fn extract_surface_elements(block: ReadMap<'_>, block_id: &str, units: &mut Vec< } } -fn extract_block_text_and_refs(block: ReadMap<'_>, flavour: &str) -> (String, Vec, Vec) { - let mut text_parts = Vec::new(); - let mut ref_doc_ids = BTreeSet::new(); - let mut refs = Vec::new(); - - for field in [ - "prop:title", - "prop:text", - "prop:caption", - "prop:name", - "prop:description", - "prop:url", - ] { - if let Some(val) = block.get(field) { - match val { - ReadValue::Text(text) => { - let s = text.to_string(); - if !s.is_empty() { - text_parts.push(s); - } - } - ReadValue::Any(any) => { - if let Some(s) = any.as_str() - && !s.is_empty() - { - text_parts.push(s.to_owned()); - } - } - _ => {} - } - } - } - - if let Some(page_id) = read_string(block, "prop:pageId").filter(|s| !s.is_empty()) { - ref_doc_ids.insert(page_id.clone()); - refs.push(json!({"docId": page_id}).to_string()); - } - - if flavour == "affine:code" - && let Some(lang) = read_string(block, "prop:language") - && !lang.is_empty() - && text_parts.is_empty() - { - text_parts.push(lang); - } - - (text_parts.join("\n"), ref_doc_ids.into_iter().collect(), refs) +struct BlockContent { + text: String, + references: References, + database_name: Option, } -fn extract_block_additional(block: ReadMap<'_>, flavour: &str) -> Option { - let mut obj = serde_json::Map::new(); - if let Some(url) = read_string(block, "prop:url") { +/// Extracts the indexed text and doc references of one block with the same +/// per-flavour rules as the `v0.27.5` reader. +fn extract_block_content( + blocks: ReadMap<'_>, + claimed_children: &mut HashSet, + block: ReadMap<'_>, + flavour: &str, + parent: Option>, + parent_flavour: Option<&str>, +) -> BlockContent { + let mut text_parts = Vec::new(); + let mut references = References::default(); + let mut database_name = None; + + match flavour { + "affine:database" => { + let title = block.get("prop:title"); + text_parts.extend(title.and_then(ReadValue::as_text).map(|title| title.to_string())); + database_name = title.and_then(value_string); + collect_database_column_texts(block, &mut text_parts); + if let Some(rows) = block.get("prop:cells").and_then(ReadValue::as_map) { + let cells = sorted_values(rows) + .into_iter() + .filter_map(ReadValue::as_map) + .flat_map(sorted_values) + .filter_map(ReadValue::as_map) + .filter_map(|cell| cell.get("value")); + collect_cell_references(cells, &mut references); + } + } + "affine:latex" => text_parts.extend(read_text_field(block, "prop:latex")), + "affine:table" => { + let mut cells: Vec<(&str, ReadValue<'_>)> = block + .iter() + .filter(|(key, _)| key.starts_with("prop:cells.") && key.ends_with(".text")) + .collect(); + cells.sort_by_key(|(key, _)| *key); + text_parts.extend(cells.into_iter().filter_map(|(_, value)| value_string(value))); + } + "affine:paragraph" | "affine:list" | "affine:code" => { + let text = block.get("prop:text").and_then(ReadValue::as_text); + text_parts.extend(text.map(|text| text.to_string())); + } + "affine:attachment" => text_parts.extend(read_text_field(block, "prop:name")), + "affine:image" => text_parts.extend(read_text_field(block, "prop:caption")), + "affine:note" | "affine:frame" | "affine:edgeless-text" => { + let text = block_text(block) + .or_else(|| read_text_field(block, "prop:title")) + .or_else(|| descendant_text(blocks, claimed_children, block)); + text_parts.extend(text); + } + "affine:embed-linked-doc" | "affine:embed-synced-doc" => {} + flavour if BOOKMARK_FLAVOURS.contains(&flavour) => {} + _ => text_parts.extend(block_text(block)), + } + + match flavour { + "affine:paragraph" | "affine:list" | "affine:code" => { + if let Some(text) = block.get("prop:text").and_then(ReadValue::as_text) { + collect_text_references(text, &mut references); + } + if flavour == "affine:paragraph" && parent_flavour == Some("affine:database") { + database_name = parent.and_then(|parent| read_text_field(parent, "prop:title")); + } + } + "affine:embed-linked-doc" | "affine:embed-synced-doc" => { + // The reader keeps any string `pageId`, the empty one included. + if let Some(page_id) = block + .get("prop:pageId") + .and_then(ReadValue::as_any) + .and_then(|any| any.as_str()) + { + references.push(page_id, block.get("prop:params")); + } + } + _ => {} + } + + text_parts.retain(|part| !part.is_empty()); + BlockContent { + text: text_parts.join("\n"), + references, + database_name, + } +} + +/// Reads column names and select option values from `Y.Map` columns, as the +/// reader does. It skips plain-object columns. +fn collect_database_column_texts(block: ReadMap<'_>, texts: &mut Vec) { + let Some(columns) = block.get("prop:columns").and_then(ReadValue::as_array) else { + return; + }; + for column in columns.iter().filter_map(ReadValue::as_map) { + texts.extend(read_plain_string(column, "name")); + let options = column + .get("data") + .and_then(ReadValue::as_map) + .and_then(|data| data.get("options")) + .and_then(ReadValue::as_array); + for option in options + .iter() + .flat_map(|options| options.iter()) + .filter_map(ReadValue::as_map) + { + texts.extend(read_plain_string(option, "value")); + } + } +} + +/// Map values in key order. The decoded key order depends on the update +/// encoding, so sort to keep the extracted order stable. +fn sorted_values(map: ReadMap<'_>) -> Vec> { + let mut entries: Vec<_> = map.iter().collect(); + entries.sort_by_key(|(key, _)| *key); + entries.into_iter().map(|(_, value)| value).collect() +} + +fn extract_block_additional(block: ReadMap<'_>, flavour: &str, database_name: Option) -> Option { + let mut obj = JsonMap::new(); + if let Some(url) = read_text_field(block, "prop:url") { obj.insert("url".to_owned(), JsonValue::String(url)); } if flavour == "affine:code" - && let Some(lang) = read_string(block, "prop:language") + && let Some(lang) = read_text_field(block, "prop:language") { obj.insert("language".to_owned(), JsonValue::String(lang)); } + if let Some(database_name) = database_name { + obj.insert("databaseName".to_owned(), JsonValue::String(database_name)); + } if obj.is_empty() { None } else { @@ -316,20 +427,78 @@ fn extract_block_additional(block: ReadMap<'_>, flavour: &str) -> Option } } -fn read_text_field(map: ReadMap<'_>, key: &str) -> Option { - match map.get(key)? { - ReadValue::Text(t) => Some(t.to_string()), - ReadValue::Any(a) => a.as_str().map(str::to_owned), +fn value_string(value: ReadValue<'_>) -> Option { + match value { + ReadValue::Text(text) => Some(text.to_string()), + ReadValue::Any(any) => any.as_str().map(str::to_owned), _ => None, } } -fn read_string(map: ReadMap<'_>, key: &str) -> Option { - match map.get(key)? { - ReadValue::Any(a) => a.as_str().map(str::to_owned), - ReadValue::Text(t) => Some(t.to_string()), - _ => None, +/// The first non-blank of the common text properties. +fn block_text(block: ReadMap<'_>) -> Option { + ["prop:text", "prop:caption", "prop:latex", "prop:name"] + .into_iter() + .find_map(|key| read_text_field(block, key)) + .filter(|text| !text.trim().is_empty()) +} + +/// Joins the `block_text` of the direct children, as the `v0.27.5` server +/// does for a container with no text of its own. +/// +/// Each child gives its text to the first container that takes at least one +/// character of it, so a child listed many times or under many containers +/// is read once for the whole doc. The joined text stops at +/// `MAX_DESCENDANT_TEXT_BYTES`. +fn descendant_text(blocks: ReadMap<'_>, claimed: &mut HashSet, block: ReadMap<'_>) -> Option { + let children = block.get("sys:children").and_then(ReadValue::as_array)?; + let mut joined = String::new(); + for child in children.iter().take(MAX_CHILDREN_PER_BLOCK as usize) { + if joined.len() >= MAX_DESCENDANT_TEXT_BYTES { + break; + } + let Some(child_id) = child.as_any().and_then(|child| child.as_str()) else { + continue; + }; + if claimed.contains(child_id) { + continue; + } + let Some(text) = blocks.get(child_id).and_then(ReadValue::as_map).and_then(block_text) else { + // A child with no text never gives text, so no container reads it again. + claimed.insert(child_id.to_owned()); + continue; + }; + let separator = usize::from(!joined.is_empty()); + if joined.len() + separator >= MAX_DESCENDANT_TEXT_BYTES { + break; + } + let room = MAX_DESCENDANT_TEXT_BYTES - joined.len() - separator; + let end = (0..=room.min(text.len())) + .rev() + .find(|end| text.is_char_boundary(*end)) + .unwrap_or(0); + // A child that gives no character stays free for the next container. + if end == 0 { + break; + } + claimed.insert(child_id.to_owned()); + if separator == 1 { + joined.push('\n'); + } + joined.push_str(&text[..end]); + if end < text.len() { + break; + } } + (!joined.is_empty()).then_some(joined) +} + +fn read_plain_string(map: ReadMap<'_>, key: &str) -> Option { + map.get(key)?.as_any()?.as_str().map(str::to_owned) +} + +fn read_text_field(map: ReadMap<'_>, key: &str) -> Option { + map.get(key).and_then(value_string) } fn hex_sha256(bytes: &[u8]) -> String { @@ -394,57 +563,1045 @@ pub fn extract_legacy_workspace( }) } -/// Builds a minimal BlockSuite Yjs page binary with title and paragraph body (for tests). -pub fn build_test_doc(title: &str, body: &str, page_id: &str) -> Vec { - let doc = Doc::new(); - let mut blocks = doc.get_or_create_map("blocks").expect("blocks map"); - - let mut page = doc.create_map().expect("page map"); - page - .insert("sys:id".to_owned(), Any::String(page_id.to_owned())) - .unwrap(); - page - .insert("sys:flavour".to_owned(), Any::String("affine:page".to_owned())) - .unwrap(); - let mut title_text = doc.create_text().expect("title text"); - title_text.insert(0, title).unwrap(); - page.insert("prop:title".to_owned(), title_text).unwrap(); - - let note_id = format!("note-{page_id}"); - let para_id = format!("para-{page_id}"); - - let mut page_children = doc.create_array().expect("page children"); - page_children.insert(0, Any::String(note_id.clone())).unwrap(); - page.insert("sys:children".to_owned(), page_children).unwrap(); - blocks.insert(page_id.to_owned(), page).unwrap(); - - let mut note = doc.create_map().expect("note map"); - note.insert("sys:id".to_owned(), Any::String(note_id.clone())).unwrap(); - note - .insert("sys:flavour".to_owned(), Any::String("affine:note".to_owned())) - .unwrap(); - let mut note_children = doc.create_array().expect("note children"); - note_children.insert(0, Any::String(para_id.clone())).unwrap(); - note.insert("sys:children".to_owned(), note_children).unwrap(); - blocks.insert(note_id, note).unwrap(); - - let mut para = doc.create_map().expect("para map"); - para.insert("sys:id".to_owned(), Any::String(para_id.clone())).unwrap(); - para - .insert("sys:flavour".to_owned(), Any::String("affine:paragraph".to_owned())) - .unwrap(); - let mut para_text = doc.create_text().expect("para text"); - para_text.insert(0, body).unwrap(); - para.insert("prop:text".to_owned(), para_text).unwrap(); - blocks.insert(para_id, para).unwrap(); - - doc.encode_update_v1().expect("encode yjs update") -} +#[cfg(test)] +#[path = "../tests/support/test_doc.rs"] +mod test_doc; #[cfg(test)] mod tests { + use std::time::{Duration, Instant}; + + use y_octo::{TextAttributes, TextDeltaOp, TextInsert}; + + use super::test_doc::{TestDoc, TestValue, build_test_doc, object}; use super::*; + const MARKER: &str = "$blocksuite:internal:text$"; + + fn project(doc: TestDoc) -> DocumentProjection { + project_document_search(doc.encode(), "doc-src".to_owned()).expect("project test doc") + } + + fn unit<'a>(projection: &'a DocumentProjection, block_id: &str) -> Option<&'a SearchUnit> { + projection + .units + .iter() + .find(|unit| unit.block_id.as_deref() == Some(block_id)) + } + + fn strings(values: &[&str]) -> Any { + Any::Array(values.iter().map(|value| Any::String((*value).to_owned())).collect()) + } + + fn target(id: &str) -> Option { + Some(TestValue::reference(id, vec![])) + } + + fn boxed(marker: Any, references: &[&str]) -> Any { + let ops = references + .iter() + .map(|id| { + object(vec![ + ("insert", Any::String("x".to_owned())), + ( + "attributes", + object(vec![("reference", TestValue::reference(id, vec![]))]), + ), + ]) + }) + .collect(); + object(vec![(MARKER, marker), ("delta", Any::Array(ops))]) + } + + fn cell(value: TestValue) -> TestValue { + TestValue::map(vec![("value", value)]) + } + + struct Case { + block_id: &'static str, + unit_type: &'static str, + text: &'static str, + ref_doc_ids: &'static [&'static str], + refs: &'static [&'static str], + additional: Option<&'static str>, + } + + #[test] + fn projection_extracts_reader_text_and_references_per_flavour() { + let mut doc = TestDoc::new("doc-src", "Source"); + doc + .block( + "p-inline", + "affine:paragraph", + None, + vec![( + "prop:text", + TestValue::rich(&[ + ("See ", None), + ("Target", target("target-a")), + (" and ", None), + ( + "Anchor", + Some(TestValue::reference( + "target-b", + vec![ + ("mode", Any::String("page".to_owned())), + ("blockIds", strings(&["blk-1"])), + ], + )), + ), + (" again", target("target-a")), + ]), + )], + ) + .block( + "p-params", + "affine:paragraph", + None, + vec![( + "prop:text", + TestValue::rich(&[ + ("one", target("target-a")), + ( + "two", + Some(TestValue::reference( + "target-a", + vec![("mode", Any::String("edgeless".to_owned()))], + )), + ), + ]), + )], + ) + .block( + "l-item", + "affine:list", + None, + vec![( + "prop:text", + TestValue::rich(&[("item ", None), ("C", target("target-c"))]), + )], + ) + .block( + "c-code", + "affine:code", + None, + vec![ + ("prop:text", TestValue::rich(&[("let x", target("target-c"))])), + ("prop:language", TestValue::string("rust")), + ], + ) + .block( + "c-empty", + "affine:code", + None, + vec![ + ("prop:text", TestValue::text("")), + ("prop:language", TestValue::string("rust")), + ], + ) + .block( + "p-numbers", + "affine:paragraph", + None, + vec![( + "prop:text", + TestValue::rich(&[ + ( + "a", + Some(TestValue::reference("target-a", vec![("x", Any::Float64(1e20.into()))])), + ), + ( + "b", + Some(TestValue::reference("target-a", vec![("x", Any::Float64(2e20.into()))])), + ), + ]), + )], + ) + .block( + "callout-text", + "affine:callout", + None, + vec![("prop:text", TestValue::rich(&[("tip", target("target-x"))]))], + ) + .block( + "e-linked", + "affine:embed-linked-doc", + None, + vec![ + ("prop:pageId", TestValue::string("target-d")), + ( + "prop:params", + TestValue::map(vec![ + ("mode", TestValue::string("page")), + ("blockIds", TestValue::Array(vec![TestValue::string("b1")])), + ("elementIds", TestValue::Array(vec![])), + ]), + ), + ("prop:text", TestValue::rich(&[("extra", target("target-x"))])), + ], + ) + .block( + "e-synced", + "affine:embed-synced-doc", + None, + vec![ + ("prop:pageId", TestValue::string("target-e")), + ( + "prop:params", + TestValue::Any(object(vec![("mode", Any::String("edgeless".to_owned()))])), + ), + ], + ) + .block( + "e-empty", + "affine:embed-linked-doc", + None, + vec![("prop:pageId", TestValue::string(""))], + ) + .block( + "db", + "affine:database", + None, + vec![ + ("prop:title", TestValue::text("Tasks")), + ( + "prop:columns", + TestValue::Array(vec![ + TestValue::map(vec![ + ("name", TestValue::string("Status")), + ( + "data", + TestValue::map(vec![( + "options", + TestValue::Array(vec![ + TestValue::map(vec![("value", TestValue::string("Done"))]), + TestValue::map(vec![("value", TestValue::string("Todo"))]), + ]), + )]), + ), + ]), + TestValue::Any(object(vec![("name", Any::String("Plain".to_owned()))])), + ]), + ), + ( + "prop:cells", + TestValue::map(vec![ + ( + "row-b", + TestValue::map(vec![( + "col-1", + cell(TestValue::rich(&[ + ("F", target("target-f")), + ("G", target("target-g")), + ("F", target("target-f")), + ])), + )]), + ), + ( + "row-a", + TestValue::map(vec![ + ( + "col-1", + cell(TestValue::Any(boxed(Any::True, &["target-h", "target-h"]))), + ), + ("col-2", cell(TestValue::rich(&[("F", target("target-f"))]))), + ( + "col-3", + cell(TestValue::map(vec![ + (MARKER, TestValue::Any(Any::False)), + ( + "delta", + TestValue::Any(Any::Array(vec![object(vec![( + "attributes", + object(vec![("reference", TestValue::reference("target-skip", vec![]))]), + )])])), + ), + ])), + ), + ( + "col-4", + cell(TestValue::map(vec![ + (MARKER, TestValue::Any(Any::Integer(1))), + ( + "delta", + TestValue::Array(vec![TestValue::map(vec![( + "attributes", + TestValue::Any(object(vec![("reference", TestValue::reference("target-i", vec![]))])), + )])]), + ), + ])), + ), + ]), + ), + ]), + ), + ], + ) + .block( + "db-row", + "affine:paragraph", + Some("db"), + vec![("prop:text", TestValue::text("Row one"))], + ) + .block( + "table", + "affine:table", + None, + vec![ + ("prop:cells.c2.text", TestValue::text("Cell B")), + ("prop:cells.c1.text", TestValue::text("Cell A")), + ("prop:cells.c3.text", TestValue::text("")), + ("prop:columns.c1.width", TestValue::Any(Any::Integer(100))), + ], + ) + .block( + "latex", + "affine:latex", + None, + vec![("prop:latex", TestValue::string("E=mc^2"))], + ) + .block( + "blank", + "affine:paragraph", + None, + vec![("prop:text", TestValue::text(" \n "))], + ) + .block("bookmark", "affine:bookmark", None, vec![]); + let projection = project(doc); + + let cases = [ + Case { + block_id: "p-inline", + unit_type: "paragraph", + text: "See Target and Anchor again", + ref_doc_ids: &["target-a", "target-b"], + refs: &[ + r#"{"docId":"target-a"}"#, + r#"{"docId":"target-b","blockIds":["blk-1"],"mode":"page"}"#, + ], + additional: None, + }, + Case { + block_id: "p-params", + unit_type: "paragraph", + text: "onetwo", + ref_doc_ids: &["target-a", "target-a"], + refs: &[r#"{"docId":"target-a"}"#, r#"{"docId":"target-a","mode":"edgeless"}"#], + additional: None, + }, + Case { + block_id: "l-item", + unit_type: "list", + text: "item C", + ref_doc_ids: &["target-c"], + refs: &[r#"{"docId":"target-c"}"#], + additional: None, + }, + Case { + block_id: "c-code", + unit_type: "code", + text: "let x", + ref_doc_ids: &["target-c"], + refs: &[r#"{"docId":"target-c"}"#], + additional: Some(r#"{"language":"rust"}"#), + }, + Case { + block_id: "callout-text", + unit_type: "callout", + text: "tip", + ref_doc_ids: &[], + refs: &[], + additional: None, + }, + Case { + block_id: "e-linked", + unit_type: "embed-linked-doc", + text: "", + ref_doc_ids: &["target-d"], + refs: &[r#"{"docId":"target-d","blockIds":["b1"],"elementIds":[],"mode":"page"}"#], + additional: None, + }, + Case { + block_id: "p-numbers", + unit_type: "paragraph", + text: "ab", + ref_doc_ids: &["target-a", "target-a"], + refs: &[ + r#"{"docId":"target-a","x":100000000000000000000}"#, + r#"{"docId":"target-a","x":200000000000000000000}"#, + ], + additional: None, + }, + Case { + block_id: "e-synced", + unit_type: "embed-synced-doc", + text: "", + ref_doc_ids: &["target-e"], + refs: &[r#"{"docId":"target-e","mode":"edgeless"}"#], + additional: None, + }, + Case { + block_id: "e-empty", + unit_type: "embed-linked-doc", + text: "", + ref_doc_ids: &[""], + refs: &[r#"{"docId":""}"#], + additional: None, + }, + Case { + block_id: "db", + unit_type: "database", + text: "Tasks\nStatus\nDone\nTodo", + ref_doc_ids: &["target-h", "target-f", "target-i", "target-f", "target-g"], + refs: &[ + r#"{"docId":"target-h"}"#, + r#"{"docId":"target-f"}"#, + r#"{"docId":"target-i"}"#, + r#"{"docId":"target-f"}"#, + r#"{"docId":"target-g"}"#, + ], + additional: Some(r#"{"databaseName":"Tasks"}"#), + }, + Case { + block_id: "db-row", + unit_type: "paragraph", + text: "Row one", + ref_doc_ids: &[], + refs: &[], + additional: Some(r#"{"databaseName":"Tasks"}"#), + }, + Case { + block_id: "table", + unit_type: "table", + text: "Cell A\nCell B", + ref_doc_ids: &[], + refs: &[], + additional: None, + }, + Case { + block_id: "latex", + unit_type: "latex", + text: "E=mc^2", + ref_doc_ids: &[], + refs: &[], + additional: None, + }, + Case { + block_id: "bookmark", + unit_type: "bookmark", + text: "", + ref_doc_ids: &[], + refs: &[], + additional: None, + }, + ]; + for case in cases { + let block_id = case.block_id; + let unit = unit(&projection, block_id).unwrap_or_else(|| panic!("{block_id} unit is missing")); + assert_eq!(unit.unit_type, case.unit_type, "{block_id} flavour"); + assert_eq!(unit.text, case.text, "{block_id} text"); + assert_eq!(unit.ref_doc_ids, case.ref_doc_ids, "{block_id} ref doc ids"); + assert_eq!(unit.refs, case.refs, "{block_id} refs"); + assert_eq!(unit.additional.as_deref(), case.additional, "{block_id} additional"); + } + assert!( + unit(&projection, "blank").is_none(), + "whitespace-only block is not indexed" + ); + assert!( + unit(&projection, "c-empty").is_none(), + "empty code block is not indexed" + ); + assert_eq!( + unit(&projection, "db-row").and_then(|unit| unit.parent_flavour.as_deref()), + Some("affine:database") + ); + } + + #[test] + fn reference_params_spread_like_json_stringify() { + let nested = (0..20).fold(TestValue::string("leaf"), |value, _| TestValue::map(vec![("a", value)])); + let cases: Vec<(&str, TestValue, String)> = vec![ + ("none", TestValue::Any(Any::Null), r#"{"docId":"t"}"#.to_owned()), + ( + "number", + TestValue::Any(Any::Integer(42)), + r#"{"docId":"t"}"#.to_owned(), + ), + ("bool", TestValue::Any(Any::True), r#"{"docId":"t"}"#.to_owned()), + ( + "string", + TestValue::string("ab😀"), + r#"{"0":"a","1":"b","2":"\ud83d","3":"\ude00","docId":"t"}"#.to_owned(), + ), + ( + "array", + TestValue::Any(strings(&["p", "q"])), + r#"{"0":"p","1":"q","docId":"t"}"#.to_owned(), + ), + ( + "object", + TestValue::Any(object(vec![ + ("mode", Any::String("page".to_owned())), + ("10", Any::String("x".to_owned())), + ("2", Any::String("y".to_owned())), + ("docId", Any::String("other".to_owned())), + ("gone", Any::Undefined), + ("ratio", Any::Float64(1.5.into())), + ("whole", Any::Float64(3.0.into())), + ("list", Any::Array(vec![Any::Undefined, Any::Null])), + ("negZero", Any::Float64((-0.0).into())), + ("big", Any::Float64(1e21.into())), + ("small", Any::Float64(1e-6.into())), + ("tiny", Any::Float64((-1.5e-7).into())), + ])), + concat!( + r#"{"2":"y","10":"x","docId":"other","big":1e+21,"list":[null,null],"mode":"page","#, + r#""negZero":0,"ratio":1.5,"small":0.000001,"tiny":-1.5e-7,"whole":3}"# + ) + .to_owned(), + ), + ( + "y-map", + TestValue::map(vec![ + ("mode", TestValue::string("page")), + ("databaseId", TestValue::string("db")), + ("title", TestValue::text("T")), + ]), + r#"{"docId":"t","databaseId":"db","mode":"page","title":"T"}"#.to_owned(), + ), + ( + "oversized", + TestValue::string(&"x".repeat(20 * 1024)), + r#"{"docId":"t"}"#.to_owned(), + ), + ("too-deep", nested, r#"{"docId":"t"}"#.to_owned()), + ]; + let mut doc = TestDoc::new("doc-src", "Source"); + let mut expected = Vec::new(); + for (id, params, serialized) in cases { + doc.block( + id, + "affine:embed-linked-doc", + None, + vec![("prop:pageId", TestValue::string("t")), ("prop:params", params)], + ); + expected.push((id, serialized)); + } + let projection = project(doc); + for (id, serialized) in expected { + let unit = unit(&projection, id).unwrap_or_else(|| panic!("{id} unit is missing")); + assert_eq!(unit.ref_doc_ids, ["t"], "{id} ref doc ids"); + assert_eq!(unit.refs, [serialized], "{id} refs"); + } + } + + #[test] + fn projection_skips_malformed_properties_without_losing_other_blocks() { + let mut doc = TestDoc::new("doc-src", "Source"); + doc + .block( + "bad-reference", + "affine:paragraph", + None, + vec![( + "prop:text", + TestValue::rich(&[ + ("string ", Some(Any::String("oops".to_owned()))), + ("no page ", Some(object(vec![("params", Any::Integer(1))]))), + ("number page ", Some(object(vec![("pageId", Any::Integer(7))]))), + ("empty", Some(TestValue::reference("", vec![]))), + ]), + )], + ) + .block( + "bad-database", + "affine:database", + None, + vec![ + ("prop:title", TestValue::text("Broken")), + ("prop:columns", TestValue::string("junk")), + ( + "prop:cells", + TestValue::map(vec![ + ("row-1", TestValue::Any(Any::Integer(1))), + ( + "row-2", + TestValue::map(vec![ + ("col-1", TestValue::string("junk")), + ("col-2", cell(TestValue::Any(Any::Integer(2)))), + ("col-3", cell(TestValue::Any(object(vec![(MARKER, Any::True)])))), + ]), + ), + ]), + ), + ], + ) + .block( + "good", + "affine:paragraph", + None, + vec![("prop:text", TestValue::rich(&[("ok", target("target-z"))]))], + ); + let projection = project(doc); + + let bad_reference = unit(&projection, "bad-reference").expect("bad-reference unit"); + assert_eq!(bad_reference.text, "string no page number page empty"); + assert!(bad_reference.ref_doc_ids.is_empty() && bad_reference.refs.is_empty()); + + let bad_database = unit(&projection, "bad-database").expect("bad-database unit"); + assert_eq!(bad_database.text, "Broken"); + assert!(bad_database.refs.is_empty()); + + let good = unit(&projection, "good").expect("good unit"); + assert_eq!(good.ref_doc_ids, ["target-z"]); + } + + /// Times `project_document_search` and returns its paragraph unit. + fn timed_projection(doc: TestDoc) -> (Duration, SearchUnit) { + let blob = doc.encode(); + let started = Instant::now(); + let projection = project_document_search(blob, "doc-src".to_owned()).expect("project test doc"); + let elapsed = started.elapsed(); + (elapsed, unit(&projection, "para").expect("para unit").clone()) + } + + /// The bound for one projection in these tests. It includes decoding the + /// doc in a debug build next to the other tests. The quadratic versions + /// took minutes for the same input. + const PROJECTION_BUDGET: Duration = Duration::from_secs(2); + + #[test] + fn inline_reference_projection_stays_linear_in_runs_and_references() { + // One 10 KiB reference over 8,000 characters, then bold on every other + // character, so the reference spans 8,000 runs. + let block_ids = strings(&["block-id-0123456789"; 500]); + let large = TestValue::reference("target-large", vec![("blockIds", block_ids)]); + let insert = vec![TextDeltaOp::Insert { + insert: TextInsert::Text("r".repeat(8_000)), + format: Some(TextAttributes::from([("reference".to_owned(), large)])), + }]; + let bold = (0..8_000) + .map(|index| TextDeltaOp::Retain { + retain: 1, + format: (index % 2 == 1).then(|| TextAttributes::from([("bold".to_owned(), Any::True)])), + }) + .collect(); + let mut doc = TestDoc::new("doc-src", "Source"); + doc.block( + "para", + "affine:paragraph", + None, + vec![("prop:text", TestValue::Deltas(vec![insert, bold]))], + ); + let (elapsed, unit) = timed_projection(doc); + assert_eq!(unit.ref_doc_ids, ["target-large"]); + assert_eq!(unit.refs.len(), 1); + assert!(elapsed < PROJECTION_BUDGET, "8,000 runs took {elapsed:?}"); + + // 25,000 different references in one paragraph. + let segments = (0..25_000) + .map(|index| { + let reference = TestValue::reference(&format!("target-{index}"), vec![]); + ( + "r".to_owned(), + TextAttributes::from([("reference".to_owned(), reference)]), + ) + }) + .collect(); + let mut doc = TestDoc::new("doc-src", "Source"); + doc.block( + "para", + "affine:paragraph", + None, + vec![("prop:text", TestValue::RichText(segments))], + ); + let (elapsed, unit) = timed_projection(doc); + assert_eq!(unit.refs.len(), 25_000); + assert_eq!(unit.ref_doc_ids.len(), 25_000); + assert_eq!(unit.ref_doc_ids[24_999], "target-24999"); + assert!(elapsed < PROJECTION_BUDGET, "25,000 references took {elapsed:?}"); + } + + #[test] + fn oversized_reference_params_fall_back_to_doc_id() { + let cases: Vec<(&str, Any)> = vec![ + ("long-string", Any::String("x".repeat(2 * 1024 * 1024))), + ("long-array", Any::Array(vec![Any::Integer(1); 200_000])), + ( + "wide-object", + (0..200_000) + .map(|index| (format!("k{index}"), Any::Integer(1))) + .collect(), + ), + ]; + let mut doc = TestDoc::new("doc-src", "Source"); + for (id, params) in &cases { + doc.block( + id, + "affine:embed-linked-doc", + None, + vec![ + ("prop:pageId", TestValue::string("t")), + ("prop:params", TestValue::Any(params.clone())), + ], + ); + } + let projection = project(doc); + for (id, _) in &cases { + let unit = unit(&projection, id).unwrap_or_else(|| panic!("{id} unit is missing")); + assert_eq!(unit.ref_doc_ids, ["t"], "{id}"); + assert_eq!(unit.refs, [r#"{"docId":"t"}"#], "{id}"); + } + } + + #[test] + fn large_params_keep_distinct_references_to_one_doc() { + let with_note = |note: String| Some(TestValue::reference("D", vec![("note", Any::String(note))])); + let mut doc = TestDoc::new("doc-src", "Source"); + doc.block( + "para", + "affine:paragraph", + None, + vec![( + "prop:text", + TestValue::rich(&[ + ("a", with_note("a".repeat(17 * 1024))), + ("b", with_note("b".repeat(17 * 1024))), + ("x", with_note("x".repeat(300 * 1024))), + ("y", with_note("y".repeat(300 * 1024))), + ]), + )], + ); + let projection = project(doc); + let unit = unit(&projection, "para").expect("para unit"); + let full = |fill: &str| format!(r#"{{"docId":"D","note":"{}"}}"#, fill.repeat(17 * 1024)); + assert_eq!(unit.ref_doc_ids, ["D", "D", "D", "D"]); + assert_eq!( + unit.refs, + [ + full("a"), + full("b"), + r#"{"docId":"D"}"#.to_owned(), + r#"{"docId":"D"}"#.to_owned() + ] + ); + } + + #[test] + fn text_comes_from_y_text_and_containers_join_direct_children() { + let mut doc = TestDoc::new("doc-src", "Source"); + doc + .block( + "p-quasar", + "affine:paragraph", + None, + vec![("prop:text", TestValue::text("quasar"))], + ) + .block("frame", "affine:frame", None, vec![]) + .block( + "frame-child", + "affine:paragraph", + Some("frame"), + vec![("prop:text", TestValue::text("inside frame"))], + ) + .block("edgeless", "affine:edgeless-text", None, vec![]) + .block( + "edgeless-child", + "affine:paragraph", + Some("edgeless"), + vec![("prop:text", TestValue::text("inside edgeless"))], + ) + .block( + "p-plain", + "affine:paragraph", + None, + vec![("prop:text", TestValue::string("plain"))], + ) + .block( + "l-plain", + "affine:list", + None, + vec![("prop:text", TestValue::string("plain list"))], + ) + .block( + "c-real", + "affine:code", + None, + vec![("prop:text", TestValue::text("real"))], + ); + let projection = project(doc); + let text = |block_id: &str| unit(&projection, block_id).map(|unit| unit.text.as_str()); + let cases = [ + ("note-doc-src", Some("quasar\nplain\nplain list\nreal")), + ("frame", Some("inside frame")), + ("edgeless", Some("inside edgeless")), + ("p-quasar", Some("quasar")), + ("frame-child", Some("inside frame")), + ("p-plain", None), + ("l-plain", None), + ("c-real", Some("real")), + ]; + for (block_id, expected) in cases { + assert_eq!(text(block_id), expected, "{block_id}"); + } + } + + fn children(ids: impl Iterator) -> TestValue { + TestValue::Array(ids.map(|id| TestValue::string(&id)).collect()) + } + + #[test] + fn containers_claim_each_child_text_once() { + let big = "p".repeat(120 * 1024); + let mut doc = TestDoc::new("doc-src", "Source"); + doc + .block( + "big-note", + "affine:note", + None, + vec![( + "sys:children", + children(std::iter::repeat_n("para-big".to_owned(), 10_000)), + )], + ) + .detached( + "para-big", + "affine:paragraph", + vec![("prop:text", TestValue::text(&big))], + ) + .detached( + "shared", + "affine:paragraph", + vec![("prop:text", TestValue::text("shared text"))], + ); + for index in 0..1_000 { + doc.block( + &format!("frame-{index:04}"), + "affine:frame", + None, + vec![("sys:children", children(std::iter::once("shared".to_owned())))], + ); + } + let projection = project(doc); + + assert_eq!( + unit(&projection, "big-note").map(|unit| unit.text.len()), + Some(120 * 1024) + ); + assert_eq!( + unit(&projection, "para-big").map(|unit| unit.text.len()), + Some(120 * 1024) + ); + let frames: Vec<(&str, &str)> = projection + .units + .iter() + .filter(|unit| unit.unit_type == "frame") + .map(|unit| (unit.block_id.as_deref().unwrap_or_default(), unit.text.as_str())) + .collect(); + assert_eq!(frames, [("frame-0000", "shared text")]); + assert_eq!( + unit(&projection, "shared").map(|unit| unit.text.as_str()), + Some("shared text") + ); + } + + #[test] + fn oversized_references_keep_their_identity_and_the_block_budget() { + let with_note = + |fill: &str, len: usize| Some(TestValue::reference("D", vec![("note", Any::String(fill.repeat(len)))])); + let large = 300 * 1024; + let mut doc = TestDoc::new("doc-src", "Source"); + doc.block( + "p-repeat", + "affine:paragraph", + None, + vec![( + "prop:text", + TestValue::rich(&[ + ("a", with_note("a", large)), + ("b", with_note("b", large)), + ("a", with_note("a", large)), + ]), + )], + ); + let cell = |fill: &str| { + TestValue::map(vec![( + "value", + TestValue::rich(&[("x", with_note(fill, large)), ("y", with_note(fill, large))]), + )]) + }; + doc.block( + "db", + "affine:database", + None, + vec![ + ("prop:title", TestValue::text("Tasks")), + ( + "prop:cells", + TestValue::map(vec![( + "row", + TestValue::map(vec![("col-1", cell("a")), ("col-2", cell("a"))]), + )]), + ), + ], + ); + // 70 different references of 250 KiB each pass the block budget. + let budget: Vec<(String, Option)> = (0..70) + .map(|index| (format!("{index:02}"), with_note(&format!("{index:02}"), 125 * 1024))) + .collect(); + let segments: Vec<(&str, Option)> = budget + .iter() + .map(|(text, reference)| (text.as_str(), reference.clone())) + .collect(); + doc.block( + "p-budget", + "affine:paragraph", + None, + vec![("prop:text", TestValue::rich(&segments))], + ); + let projection = project(doc); + + let fallback = r#"{"docId":"D"}"#; + let repeat = unit(&projection, "p-repeat").expect("p-repeat unit"); + assert_eq!(repeat.ref_doc_ids, ["D", "D"]); + assert_eq!(repeat.refs, [fallback, fallback]); + let database = unit(&projection, "db").expect("db unit"); + assert_eq!(database.refs, [fallback, fallback], "each cell checks duplicates alone"); + + let budget = unit(&projection, "p-budget").expect("p-budget unit"); + let total: usize = budget.refs.iter().map(String::len).sum(); + let full = budget + .refs + .iter() + .filter(|serialized| serialized.len() > fallback.len()) + .count(); + assert!(total <= reference::MAX_BLOCK_REFS_BYTES, "refs take {total} bytes"); + assert_eq!(budget.refs.len(), 70); + assert_eq!(budget.ref_doc_ids.len(), 70); + assert!(full > 0 && full < 70, "{full} references kept their params"); + assert!(budget.refs[full..].iter().all(|serialized| serialized == fallback)); + } + + #[test] + fn wide_oversized_params_keep_their_identity() { + // 4,097 keys pass `MAX_SPREAD_ENTRIES`, and only the last value differs. + let params = |last: Any| { + let mut entries: Vec<(String, Any)> = (0..4_096).map(|index| (format!("k{index}"), Any::Integer(1))).collect(); + entries.push(("k4096".to_owned(), last)); + let params: Any = entries.into_iter().collect(); + Some(object(vec![ + ("pageId", Any::String("D".to_owned())), + ("params", params), + ])) + }; + let mut doc = TestDoc::new("doc-src", "Source"); + doc.block( + "para", + "affine:paragraph", + None, + vec![( + "prop:text", + TestValue::rich(&[ + ("a", params(Any::String("a".to_owned()))), + ("b", params(Any::String("b".to_owned()))), + ("a", params(Any::String("a".to_owned()))), + ]), + )], + ); + // Nested arrays of the same items in another shape: `[[1], 2]` and `[[1, 2]]`. + let split = || Any::Array(vec![Any::Array(vec![Any::Integer(1)]), Any::Integer(2)]); + let joined = || Any::Array(vec![Any::Array(vec![Any::Integer(1), Any::Integer(2)])]); + doc.block( + "nested", + "affine:paragraph", + None, + vec![( + "prop:text", + TestValue::rich(&[("a", params(split())), ("b", params(joined())), ("a", params(split()))]), + )], + ); + let projection = project(doc); + for block_id in ["para", "nested"] { + let unit = unit(&projection, block_id).unwrap_or_else(|| panic!("{block_id} unit is missing")); + assert_eq!(unit.ref_doc_ids, ["D", "D"], "{block_id}"); + assert_eq!(unit.refs, [r#"{"docId":"D"}"#, r#"{"docId":"D"}"#], "{block_id}"); + } + } + + #[test] + fn full_containers_leave_unwritten_children_to_later_containers() { + let shared = |id: &str| children([format!("{id}-big"), format!("{id}-word")].into_iter()); + let mut doc = TestDoc::new("doc-src", "Source"); + doc + .block("frame-a", "affine:frame", None, vec![("sys:children", shared("a"))]) + .block( + "frame-b", + "affine:frame", + None, + vec![("sys:children", children(std::iter::once("a-word".to_owned())))], + ) + .block("frame-c", "affine:frame", None, vec![("sys:children", shared("c"))]) + .block( + "frame-d", + "affine:frame", + None, + vec![("sys:children", children(std::iter::once("c-word".to_owned())))], + ) + .detached( + "a-big", + "affine:paragraph", + vec![("prop:text", TestValue::text(&"x".repeat(1024 * 1024)))], + ) + .detached( + "a-word", + "affine:paragraph", + vec![("prop:text", TestValue::text("needle"))], + ) + .detached( + "c-big", + "affine:paragraph", + vec![("prop:text", TestValue::text(&"x".repeat(1024 * 1024 - 2)))], + ) + .detached( + "c-word", + "affine:paragraph", + vec![("prop:text", TestValue::text("中文词"))], + ); + let projection = project(doc); + let text = |block_id: &str| unit(&projection, block_id).map(|unit| unit.text.clone()); + assert_eq!(text("frame-a").map(|text| text.len()), Some(1024 * 1024)); + assert_eq!(text("frame-b").as_deref(), Some("needle")); + assert_eq!(text("frame-c").map(|text| text.len()), Some(1024 * 1024 - 2)); + assert_eq!(text("frame-d").as_deref(), Some("中文词")); + } + + #[test] + fn deep_params_keep_their_identity() { + // 18 nested arrays pass the JSON writer depth limit of 16. + let params = |leaf: i32| { + let nested = (0..18).fold(Any::Integer(leaf), |value, _| Any::Array(vec![value])); + Some(object(vec![ + ("pageId", Any::String("D".to_owned())), + ("params", object(vec![("v", nested)])), + ])) + }; + let mut doc = TestDoc::new("doc-src", "Source"); + doc.block( + "para", + "affine:paragraph", + None, + vec![( + "prop:text", + TestValue::rich(&[("a", params(1)), ("b", params(2)), ("a", params(1))]), + )], + ); + let projection = project(doc); + let unit = unit(&projection, "para").expect("para unit"); + assert_eq!(unit.ref_doc_ids, ["D", "D"]); + assert_eq!(unit.refs, [r#"{"docId":"D"}"#, r#"{"docId":"D"}"#]); + } + fn push_varuint(buf: &mut Vec, mut v: u64) { while v >= 0x80 { buf.push(((v as u8) & 0x7f) | 0x80); diff --git a/packages/backend/server-search/src/doc_extract/reference.rs b/packages/backend/server-search/src/doc_extract/reference.rs new file mode 100644 index 0000000000..9121758027 --- /dev/null +++ b/packages/backend/server-search/src/doc_extract/reference.rs @@ -0,0 +1,740 @@ +//! Doc references of a block, serialized as the `v0.27.5` reader does: +//! `ref_doc_id` holds `pageId`, and `ref` holds +//! `JSON.stringify({ docId: pageId, ...params })`. + +use std::collections::HashSet; +use std::io; + +use sha2::{Digest, Sha256}; +use y_octo::{ReadAny, ReadText, ReadTextRun, ReadValue}; + +/// The largest `params` part of one serialized reference. A reference with +/// larger params keeps only its `docId`. +const MAX_REF_PARAMS_BYTES: usize = 256 * 1024; +/// The bytes of all `refs` entries of one block. A reference that does not +/// fit in the bytes left keeps only its `docId`, and a reference whose +/// `docId` entry does not fit is dropped. +pub(super) const MAX_BLOCK_REFS_BYTES: usize = 16 * 1024 * 1024; +/// The most references of one block that keep only their `docId`. +const MAX_FALLBACK_REFS: usize = 4_096; +/// The most JSON bytes hashed to identify one reference that does not fit. +const MAX_IDENTITY_BYTES: usize = 4 * 1024 * 1024; +/// The most nodes and string bytes that the structural identity reads, for +/// params that are too large to hash as JSON. +const MAX_STRUCTURE_NODES: usize = 65_536; +const MAX_STRUCTURE_BYTES: usize = 16 * 1024 * 1024; +/// The deepest nesting that the structural identity reads. It matches the +/// `y-octo` decode limit, so it reads every decoded value to its leaves. +const MAX_STRUCTURE_DEPTH: usize = 128; +const MAX_PARAMS_DEPTH: usize = 16; +/// The most entries of one params object or spread. A spread with more +/// entries stops before they are collected. +const MAX_SPREAD_ENTRIES: usize = 4_096; +/// The most items of one params array. +const MAX_ARRAY_ITEMS: usize = 8_192; +const BOXED_TEXT_MARKER: &str = "$blocksuite:internal:text$"; + +/// The SHA-256 of a serialized reference. +type Identity = [u8; 32]; + +/// References in first-seen order, and `doc_ids[i]` is the doc id of +/// `refs[i]`. +/// +/// The duplicate check uses the identity of the full serialized reference. +/// A reference that does not fit keeps only its `docId`, but it is still +/// checked by its full identity, so it does not merge with other +/// references to the same doc. The bytes of `refs` and `bytes_left` always +/// add up to `MAX_BLOCK_REFS_BYTES`. +pub(super) struct References { + pub(super) doc_ids: Vec, + pub(super) refs: Vec, + seen: HashSet, + bytes_left: usize, + fallbacks: usize, +} + +impl Default for References { + fn default() -> Self { + Self { + doc_ids: Vec::new(), + refs: Vec::new(), + seen: HashSet::new(), + bytes_left: MAX_BLOCK_REFS_BYTES, + fallbacks: 0, + } + } +} + +impl References { + pub(super) fn push(&mut self, doc_id: &str, params: Option>) { + let serialized = serialize_reference(doc_id, params, self.entry_limit(doc_id)); + self.push_serialized(doc_id.to_owned(), serialized); + } + + /// The longest serialized reference to `doc_id` that can be kept now. + fn entry_limit(&self, doc_id: &str) -> usize { + doc_id + .len() + .saturating_add(16) + .saturating_add(MAX_REF_PARAMS_BYTES) + .min(self.bytes_left) + } + + fn push_serialized(&mut self, doc_id: String, serialized: Result) { + match serialized { + Ok(serialized) => { + if self.seen.insert(Sha256::digest(serialized.as_bytes()).into()) { + self.bytes_left = self.bytes_left.saturating_sub(serialized.len()); + self.doc_ids.push(doc_id); + self.refs.push(serialized); + } + } + Err(Oversize(identity)) => { + let fallback = doc_id_only(&doc_id); + if self.fallbacks < MAX_FALLBACK_REFS && fallback.len() <= self.bytes_left && self.seen.insert(identity) { + self.bytes_left -= fallback.len(); + self.fallbacks += 1; + self.doc_ids.push(doc_id); + self.refs.push(fallback); + } + } + } + } + + /// Starts the references of one database cell. The cell has its own + /// duplicate check and shares the block budget. + fn scope(&self) -> Self { + Self { + bytes_left: self.bytes_left, + fallbacks: self.fallbacks, + ..Self::default() + } + } + + /// Appends the references of a cell without a shared duplicate check, as + /// the reader concatenates database cells. + fn append(&mut self, other: References) { + self.doc_ids.extend(other.doc_ids); + self.refs.extend(other.refs); + self.bytes_left = other.bytes_left; + self.fallbacks = other.fallbacks; + } +} + +/// Collects the `reference` attribute of each visible run, as +/// `collectInlineReferences(text.toDelta())` does. Each `reference` format +/// is parsed once, and later runs under the same format cost O(1). +pub(super) fn collect_text_references(text: ReadText<'_>, references: &mut References) { + let mut pending: Option<(String, Result)> = None; + for run in text.runs() { + match run { + ReadTextRun::Format { + key: "reference", + value, + } => pending = inline_reference(ReadValue::Any(value), references), + ReadTextRun::Format { .. } | ReadTextRun::Text("") => {} + ReadTextRun::Text(_) | ReadTextRun::Embed(_) => { + if let Some((doc_id, serialized)) = pending.take() { + references.push_serialized(doc_id, serialized); + } + } + } + } +} + +/// Collects references from each database cell. Each cell has its own +/// duplicate check, as `reader.ts` does. +pub(super) fn collect_cell_references<'a>(cells: impl Iterator>, references: &mut References) { + for value in cells { + let mut cell = references.scope(); + collect_rich_text_references(value, &mut cell); + references.append(cell); + } +} + +/// Reads a cell value as `getTextDeltasFromCellValue` does: a `Y.Text`, a +/// `Y.Map` boxed text with a truthy marker, or a plain object that has the +/// marker key. +fn collect_rich_text_references(value: ReadValue<'_>, references: &mut References) { + let delta = match value { + ReadValue::Text(text) => return collect_text_references(text, references), + ReadValue::Map(map) if map.get(BOXED_TEXT_MARKER).is_some_and(is_truthy) => map.get("delta"), + ReadValue::Any(any) if any.get(BOXED_TEXT_MARKER).is_some() => any.get("delta").map(ReadValue::Any), + _ => return, + }; + let ops: Vec> = match delta { + Some(ReadValue::Array(array)) => array.iter().collect(), + Some(ReadValue::Any(any)) => any + .array() + .map(|ops| ops.map(ReadValue::Any).collect()) + .unwrap_or_default(), + _ => return, + }; + for op in ops { + let reference = child(op, "attributes").and_then(|attributes| child(attributes, "reference")); + if let Some((doc_id, serialized)) = reference.and_then(|reference| inline_reference(reference, references)) { + references.push_serialized(doc_id, serialized); + } + } +} + +/// Parses a `{pageId, params?}` reference. The reader skips a falsy `pageId`. +fn inline_reference(reference: ReadValue<'_>, references: &References) -> Option<(String, Result)> { + let page_id = child(reference, "pageId")?.as_any()?.as_str()?; + if page_id.is_empty() { + return None; + } + Some(( + page_id.to_owned(), + serialize_reference(page_id, child(reference, "params"), references.entry_limit(page_id)), + )) +} + +fn child<'a>(value: ReadValue<'a>, key: &str) -> Option> { + match value { + ReadValue::Map(map) => map.get(key), + ReadValue::Any(any) => any.get(key).map(ReadValue::Any), + _ => None, + } +} + +/// JavaScript truthiness of a stored value. +fn is_truthy(value: ReadValue<'_>) -> bool { + let ReadValue::Any(any) = value else { + return true; + }; + if any.is_undefined() || any.is_null() { + false + } else if let Some(value) = any.as_bool() { + value + } else if let Some(value) = any.as_i64() { + value != 0 + } else if let Some(value) = any.as_f64() { + value != 0.0 && !value.is_nan() + } else if let Some(value) = any.as_str() { + !value.is_empty() + } else { + true + } +} + +/// Serializes `JSON.stringify({ docId, ...params })` in at most `limit` +/// bytes. +/// +/// The spread follows JavaScript: an object gives its own keys, a string or +/// an array gives its indices, and other values give no keys. Array index +/// keys come first in ascending order, then `docId`, then the other keys. +/// Stored objects do not keep their insertion order, so the other keys come +/// in sorted order. A reference that does not fit returns `Oversize` with +/// its identity. +fn serialize_reference(doc_id: &str, params: Option>, limit: usize) -> Result { + let Ok(entries) = reference_entries(doc_id, params) else { + return Err(Oversize(structure_identity(doc_id, params))); + }; + let mut text = JsonWriter::new(Sink::Text(Vec::new()), limit); + if text.spread(&entries).is_ok() { + return Ok(text.into_string()); + } + let mut hash = JsonWriter::new(Sink::Hash(Sha256::new()), MAX_IDENTITY_BYTES); + let identity = match hash.spread(&entries) { + Ok(()) => hash.into_identity(), + Err(Limit) => structure_identity(doc_id, params), + }; + Err(Oversize(identity)) +} + +/// The entries of `{ docId, ...params }` in output order. +fn reference_entries<'a>(doc_id: &str, params: Option>) -> Result)>, Limit> { + let mut entries = params.map_or(Ok(Vec::new()), spread_entries)?; + entries.sort_by(|(left, _), (right, _)| js_key_order(left, right)); + // A `docId` param replaces the value but keeps the first string key slot. + let doc_id_entry = match entries.iter().position(|(key, _)| key == "docId") { + Some(position) => entries.remove(position), + None => ("docId".to_owned(), Spread::String(doc_id.to_owned())), + }; + let position = entries.partition_point(|(key, _)| array_index(key).is_some()); + entries.insert(position, doc_id_entry); + Ok(entries) +} + +fn doc_id_only(doc_id: &str) -> String { + let mut writer = JsonWriter::new(Sink::Text(Vec::new()), usize::MAX); + let _ = writer.spread(&[("docId".to_owned(), Spread::String(doc_id.to_owned()))]); + writer.into_string() +} + +/// One spread value: a stored value, a string, or one UTF-16 unit of a +/// spread string. +enum Spread<'a> { + Value(ReadValue<'a>), + String(String), + Unit(u16), +} + +/// Lists the keys that `{ ...params }` gives. It stops with `Limit` once +/// there are more than `MAX_SPREAD_ENTRIES` entries. +fn spread_entries(params: ReadValue<'_>) -> Result)>, Limit> { + match params { + ReadValue::Map(map) => bounded(map.iter(), MAX_SPREAD_ENTRIES).map(|entries| { + entries + .into_iter() + .map(|(key, value)| (key.to_owned(), Spread::Value(value))) + .collect() + }), + ReadValue::Array(array) => indexed(array.iter().map(Spread::Value)), + ReadValue::Any(any) => { + if let Some(entries) = any.object() { + bounded(entries, MAX_SPREAD_ENTRIES).map(|entries| { + entries + .into_iter() + .map(|(key, value)| (key.to_owned(), Spread::Value(ReadValue::Any(value)))) + .collect() + }) + } else if let Some(values) = any.array() { + indexed(values.map(|value| Spread::Value(ReadValue::Any(value)))) + } else if let Some(value) = any.as_str() { + indexed(value.encode_utf16().map(Spread::Unit)) + } else { + Ok(Vec::new()) + } + } + _ => Ok(Vec::new()), + } +} + +fn indexed<'a>(values: impl Iterator>) -> Result)>, Limit> { + bounded(values, MAX_SPREAD_ENTRIES).map(|values| { + values + .into_iter() + .enumerate() + .map(|(index, value)| (index.to_string(), value)) + .collect() + }) +} + +/// Collects at most `limit` items, or returns `Limit` when there are more. +fn bounded(items: impl Iterator, limit: usize) -> Result, Limit> { + let items: Vec = items.take(limit + 1).collect(); + if items.len() > limit { Err(Limit) } else { Ok(items) } +} + +/// Returns the index of a canonical array index key such as `"0"` or `"12"`. +fn array_index(key: &str) -> Option { + if key.is_empty() || (key.len() > 1 && key.starts_with('0')) || !key.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + key.parse::().ok().filter(|index| *index != u32::MAX) +} + +fn js_key_order(left: &str, right: &str) -> std::cmp::Ordering { + match (array_index(left), array_index(right)) { + (Some(left), Some(right)) => left.cmp(&right), + (Some(_), None) => std::cmp::Ordering::Less, + (None, Some(_)) => std::cmp::Ordering::Greater, + (None, None) => left.cmp(right), + } +} + +/// A reference that does not fit, with its identity. +struct Oversize(Identity); + +/// A serialization that passed a size, entry or depth limit. +struct Limit; + +/// Returns `true` for a value that `JSON.stringify` leaves out of an object. +fn is_omitted(value: ReadValue<'_>) -> bool { + match value { + ReadValue::Any(any) => any.is_undefined() || any.as_binary().is_some(), + ReadValue::Xml { .. } | ReadValue::Doc { .. } => true, + ReadValue::Text(_) | ReadValue::Map(_) | ReadValue::Array(_) => false, + } +} + +/// Where `JsonWriter` sends its output: a buffer, or a hash that keeps no +/// output. +enum Sink { + Text(Vec), + Hash(Sha256), +} + +/// Writes `JSON.stringify` output and stops at `limit` bytes or at +/// `MAX_PARAMS_DEPTH` levels. +struct JsonWriter { + sink: Sink, + len: usize, + limit: usize, +} + +impl io::Write for JsonWriter { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self + .bytes(bytes) + .map_err(|Limit| io::Error::other("search reference is too large"))?; + Ok(bytes.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl JsonWriter { + fn new(sink: Sink, limit: usize) -> Self { + Self { sink, len: 0, limit } + } + + fn into_string(self) -> String { + match self.sink { + Sink::Text(bytes) => String::from_utf8(bytes).unwrap_or_default(), + Sink::Hash(_) => String::new(), + } + } + + fn into_identity(self) -> Identity { + match self.sink { + Sink::Text(bytes) => Sha256::digest(&bytes).into(), + Sink::Hash(hash) => hash.finalize().into(), + } + } + + fn bytes(&mut self, bytes: &[u8]) -> Result<(), Limit> { + if self.len.saturating_add(bytes.len()) > self.limit { + return Err(Limit); + } + self.len += bytes.len(); + match &mut self.sink { + Sink::Text(out) => out.extend_from_slice(bytes), + Sink::Hash(hash) => hash.update(bytes), + } + Ok(()) + } + + fn push(&mut self, value: &str) -> Result<(), Limit> { + self.bytes(value.as_bytes()) + } + + fn string(&mut self, value: &str) -> Result<(), Limit> { + if self.len.saturating_add(value.len()) > self.limit { + return Err(Limit); + } + serde_json::to_writer(&mut *self, value).map_err(|_| Limit) + } + + /// Writes a top-level spread object from entries in output order. + fn spread(&mut self, entries: &[(String, Spread<'_>)]) -> Result<(), Limit> { + self.push("{")?; + let mut first = true; + for (key, value) in entries { + if let Spread::Value(value) = value + && is_omitted(*value) + { + continue; + } + if !first { + self.push(",")?; + } + first = false; + self.string(key)?; + self.push(":")?; + match value { + Spread::Value(value) => self.value(*value, 1)?, + Spread::String(value) => self.string(value)?, + Spread::Unit(unit) => self.unit(*unit)?, + } + } + self.push("}") + } + + /// Writes one UTF-16 unit as a string. A lone surrogate becomes an escape, + /// as in well-formed `JSON.stringify`. + fn unit(&mut self, unit: u16) -> Result<(), Limit> { + match char::from_u32(u32::from(unit)) { + Some(character) => self.string(character.encode_utf8(&mut [0; 4])), + None => self.push(&format!("\"\\u{unit:04x}\"")), + } + } + + /// Writes a value that `is_omitted` keeps. + fn value(&mut self, value: ReadValue<'_>, depth: usize) -> Result<(), Limit> { + if depth > MAX_PARAMS_DEPTH { + return Err(Limit); + } + match value { + ReadValue::Any(any) => self.any(any, depth), + ReadValue::Text(text) => { + if usize::try_from(text.len()).unwrap_or(usize::MAX) > self.limit { + return Err(Limit); + } + self.string(&text.to_string()) + } + ReadValue::Map(map) => { + let mut entries = bounded(map.iter(), MAX_SPREAD_ENTRIES)?; + entries.sort_by(|(left, _), (right, _)| js_key_order(left, right)); + self.object(entries.into_iter(), depth) + } + ReadValue::Array(array) => { + if array.len() > MAX_ARRAY_ITEMS as u64 { + return Err(Limit); + } + self.array(array.iter(), depth) + } + ReadValue::Xml { .. } | ReadValue::Doc { .. } => self.push("null"), + } + } + + fn any(&mut self, any: ReadAny<'_>, depth: usize) -> Result<(), Limit> { + if any.is_null() || any.is_undefined() || any.as_binary().is_some() { + self.push("null") + } else if let Some(value) = any.as_bool() { + self.push(if value { "true" } else { "false" }) + } else if let Some(value) = any.as_i64() { + self.push(&value.to_string()) + } else if let Some(value) = any.as_f64() { + self.push(&js_number(value)) + } else if let Some(value) = any.as_str() { + self.string(value) + } else if let Some(values) = any.array() { + self.array(values.map(ReadValue::Any), depth) + } else if let Some(entries) = any.object() { + let mut entries = bounded(entries, MAX_SPREAD_ENTRIES)?; + entries.sort_by(|(left, _), (right, _)| js_key_order(left, right)); + self.object( + entries.into_iter().map(|(key, value)| (key, ReadValue::Any(value))), + depth, + ) + } else { + self.push("null") + } + } + + fn object<'a>(&mut self, entries: impl Iterator)>, depth: usize) -> Result<(), Limit> { + self.push("{")?; + let mut first = true; + for (key, value) in entries { + if is_omitted(value) { + continue; + } + if !first { + self.push(",")?; + } + first = false; + self.string(key)?; + self.push(":")?; + self.value(value, depth + 1)?; + } + self.push("}") + } + + /// Writes an array. `JSON.stringify` writes `null` for a value that it + /// leaves out of an object. + fn array<'a>(&mut self, values: impl Iterator>, depth: usize) -> Result<(), Limit> { + self.push("[")?; + for (index, value) in values.enumerate() { + if index > 0 { + self.push(",")?; + } + if is_omitted(value) { + self.push("null")?; + } else { + self.value(value, depth + 1)?; + } + } + self.push("]") + } +} + +/// Identifies params that are too large to hash as JSON. It hashes a type +/// tag for each node and the string bytes, up to `MAX_STRUCTURE_NODES` +/// nodes and `MAX_STRUCTURE_BYTES` string bytes, so it reads a bounded part +/// of the params and keeps no copy of them. Object entries add up into an +/// order-independent digest, because stored objects have no stable key +/// order. +fn structure_identity(doc_id: &str, params: Option>) -> Identity { + let mut hasher = StructureHasher { + hash: Sha256::new(), + nodes: 0, + bytes: 0, + }; + hasher.hash.update(b"affine-search-reference-structure\0"); + hasher.string(doc_id); + if let Some(params) = params { + hasher.value(params, 0); + } + hasher.hash.finalize().into() +} + +struct StructureHasher { + hash: Sha256, + nodes: usize, + bytes: usize, +} + +impl StructureHasher { + /// Hashes a node tag, or returns `false` once the node budget is spent. + fn node(&mut self, tag: u8) -> bool { + if self.nodes >= MAX_STRUCTURE_NODES { + return false; + } + self.nodes += 1; + self.hash.update([tag]); + true + } + + fn string(&mut self, value: &str) { + self.hash.update((value.len() as u64).to_le_bytes()); + let take = value.len().min(MAX_STRUCTURE_BYTES.saturating_sub(self.bytes)); + self.bytes += take; + self.hash.update(&value.as_bytes()[..take]); + } + + /// Hashes one value. Every container and cut ends with its own marker, + /// so no two shapes give the same bytes. + fn value(&mut self, value: ReadValue<'_>, depth: usize) { + if depth > MAX_STRUCTURE_DEPTH { + let _ = self.node(b'!'); + return; + } + match value { + ReadValue::Any(any) => self.any(any, depth), + ReadValue::Text(text) => { + if self.node(b's') { + for run in text.runs() { + if let ReadTextRun::Text(value) = run { + self.string(value); + } + } + self.hash.update(b"]"); + } + } + ReadValue::Map(map) => { + if self.node(b'{') { + self.entries(map.iter(), depth); + } + } + ReadValue::Array(array) => { + if self.node(b'[') { + self.hash.update(array.len().to_le_bytes()); + for value in array.iter() { + if self.nodes >= MAX_STRUCTURE_NODES { + break; + } + self.value(value, depth + 1); + } + self.hash.update(b"]"); + } + } + ReadValue::Xml { .. } | ReadValue::Doc { .. } => { + self.node(b'x'); + } + } + } + + fn any(&mut self, any: ReadAny<'_>, depth: usize) { + if depth > MAX_STRUCTURE_DEPTH { + let _ = self.node(b'!'); + } else if any.is_undefined() { + self.node(b'u'); + } else if any.is_null() { + self.node(b'n'); + } else if let Some(value) = any.as_bool() { + self.node(if value { b't' } else { b'f' }); + } else if let Some(value) = any.as_i64() { + if self.node(b'i') { + self.hash.update(value.to_le_bytes()); + } + } else if let Some(value) = any.as_f64() { + if self.node(b'd') { + self.hash.update(value.to_bits().to_le_bytes()); + } + } else if let Some(value) = any.as_str() { + if self.node(b's') { + self.string(value); + } + } else if let Some(binary) = any.as_binary() { + if self.node(b'b') { + self.hash.update((binary.len() as u64).to_le_bytes()); + } + } else if let Some(values) = any.array() { + if self.node(b'[') { + let mut count = 0_u64; + for value in values { + if self.nodes >= MAX_STRUCTURE_NODES { + break; + } + self.any(value, depth + 1); + count += 1; + } + self.hash.update(count.to_le_bytes()); + self.hash.update(b"]"); + } + } else if let Some(entries) = any.object() + && self.node(b'{') + { + self.entries(entries.map(|(key, value)| (key, ReadValue::Any(value))), depth); + } + } + + /// Hashes object entries in any order: each entry gets its own digest, + /// and the digests add up lane by lane, so the key order does not matter. + fn entries<'a>(&mut self, entries: impl Iterator)>, depth: usize) { + let mut sum = [0_u64; 4]; + let mut count = 0_u64; + for (key, value) in entries { + if self.nodes >= MAX_STRUCTURE_NODES { + break; + } + self.nodes += 1; + let parent = std::mem::replace(&mut self.hash, Sha256::new()); + self.string(key); + self.value(value, depth + 1); + let digest: Identity = std::mem::replace(&mut self.hash, parent).finalize().into(); + for (index, lane) in sum.iter_mut().enumerate() { + let mut word = [0_u8; 8]; + word.copy_from_slice(&digest[index * 8..index * 8 + 8]); + *lane = lane.wrapping_add(u64::from_le_bytes(word)); + } + count += 1; + } + self.hash.update(count.to_le_bytes()); + for lane in sum { + self.hash.update(lane.to_le_bytes()); + } + } +} + +/// Formats a number as ECMAScript `Number::toString` does: the shortest +/// round-trip digits, in plain notation for decimal exponents from -7 to 20 +/// and in `1e+21` form otherwise. +fn js_number(value: f64) -> String { + if !value.is_finite() { + return "null".to_owned(); + } + if value == 0.0 { + return "0".to_owned(); + } + // `{:e}` gives the shortest round-trip digits, such as `-1.5e-7`. + let scientific = format!("{:e}", value.abs()); + let (mantissa, exponent) = scientific.split_once('e').unwrap_or((&scientific, "0")); + let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect(); + let k = digits.len() as i64; + let n = exponent.parse::().unwrap_or(0) + 1; + let sign = if value < 0.0 { "-" } else { "" }; + let body = if k <= n && n <= 21 { + format!("{digits}{}", "0".repeat((n - k) as usize)) + } else if 0 < n && n <= 21 { + format!("{}.{}", &digits[..n as usize], &digits[n as usize..]) + } else if -6 < n && n <= 0 { + format!("0.{}{digits}", "0".repeat((-n) as usize)) + } else { + let exponent = n - 1; + let exponent_sign = if exponent < 0 { "-" } else { "+" }; + let (first, rest) = digits.split_at(1); + let fraction = if rest.is_empty() { + String::new() + } else { + format!(".{rest}") + }; + format!("{first}{fraction}e{exponent_sign}{}", exponent.abs()) + }; + format!("{sign}{body}") +} diff --git a/packages/backend/server-search/src/generation.rs b/packages/backend/server-search/src/generation.rs index 56ef68508c..60fa3cb4d6 100644 --- a/packages/backend/server-search/src/generation.rs +++ b/packages/backend/server-search/src/generation.rs @@ -196,6 +196,9 @@ pub async fn load_active_in( row.map(decode).transpose() } +/// Drops one retired generation of this provider. It does not filter on +/// `schema_version`, so generations of an earlier projection schema are +/// dropped too. pub async fn cleanup_retired_generation( pool: &PgPool, embedded: &EmbeddedSearchIndex, @@ -205,7 +208,7 @@ pub async fn cleanup_retired_generation( let row = sqlx::query( r#"SELECT id, manifest, generation.state = 'failed' - AND generation.last_error IS DISTINCT FROM $5 + AND generation.last_error IS DISTINCT FROM $4 AND NOT EXISTS (SELECT 1 FROM search_projection.generations active WHERE active.state = 'active' AND active.provider = generation.provider AND active.config_hash = generation.config_hash @@ -217,16 +220,15 @@ pub async fn cleanup_retired_generation( AND newer.created_at > generation.created_at) AS retain_failure_marker FROM search_projection.generations generation - WHERE provider = $1 AND schema_version = $2 - AND (manifest->>'providerIdentity' = $3 - OR (NOT manifest ? 'providerIdentity' AND config_hash = $4)) + WHERE provider = $1 + AND (manifest->>'providerIdentity' = $2 + OR (NOT manifest ? 'providerIdentity' AND config_hash = $3)) AND ((state = 'failed' AND created_at < now() - interval '1 hour' AND manifest <> '{}'::jsonb) OR (state = 'draining' AND drained_at < now() - interval '24 hours')) ORDER BY COALESCE(drained_at, created_at), id LIMIT 1"#, ) .bind(&config.provider) - .bind(SCHEMA_FINGERPRINT) .bind(provider_identity(config)) .bind(config_hash(config)) .bind(EMBEDDED_GENERATION_LOST) diff --git a/packages/backend/server-search/src/lib.rs b/packages/backend/server-search/src/lib.rs index b61512a232..e690dc332f 100644 --- a/packages/backend/server-search/src/lib.rs +++ b/packages/backend/server-search/src/lib.rs @@ -33,7 +33,9 @@ use server_domain::acl::{ReservedDocClass, classify_reserved_doc}; use sha2::{Digest, Sha256}; use sqlx::PgConnection; -pub(crate) const SCHEMA_FINGERPRINT: i32 = 1; +/// The search projection schema. Raise it when extraction changes indexed +/// fields, so that startup builds a new generation and reprojects every doc. +pub const SCHEMA_FINGERPRINT: i32 = 2; pub(crate) const WORKSPACE_RECONCILE_FAILED: &str = "search_workspace_reconcile_failed"; pub(crate) const DOCUMENT_PROJECTION_FAILED: &str = "search_document_projection_failed"; pub(crate) const EMBEDDED_GENERATION_LOST: &str = "search_embedded_generation_lost"; diff --git a/packages/backend/server-search/tests/pg_integration.rs b/packages/backend/server-search/tests/pg_integration.rs index 0a6cbed972..5c48de149e 100644 --- a/packages/backend/server-search/tests/pg_integration.rs +++ b/packages/backend/server-search/tests/pg_integration.rs @@ -20,14 +20,18 @@ fn enabled_search_config() -> SearchConfig { } } +#[path = "support/test_doc.rs"] +mod test_doc; + +use test_doc::{TestDoc, TestValue, build_test_doc}; + use server_db::{DbConfig, ServerDb}; -use server_search::doc_extract::build_test_doc; use server_search::generation::{config_hash, provider_identity}; use server_search::worker::{OrphanGcFence, capture_orphan_gc_high_water}; use server_search::{ - AggregateHitsOptions, AggregateOptions, AggregateRequest, SearchConfig, SearchError, SearchOptions, SearchPagination, - SearchQuery, SearchRequest, SearchRuntime, SearchTable, expire_lockless_v2_lease, is_lockless_v2_active, - renew_lockless_v2_lease, renew_lockless_v2_lease_for, + AggregateHitsOptions, AggregateOptions, AggregateRequest, SCHEMA_FINGERPRINT, SearchConfig, SearchError, + SearchOptions, SearchPagination, SearchQuery, SearchRequest, SearchRuntime, SearchTable, expire_lockless_v2_lease, + is_lockless_v2_active, renew_lockless_v2_lease, renew_lockless_v2_lease_for, }; use server_spi::CommunityQuotaGate; use server_types::ServerRole; @@ -728,11 +732,12 @@ fn two_beat_fence_xid_closes_gap_a_and_gap_b() { let mut tx_gen = pool.begin().await.unwrap(); sqlx::query( "INSERT INTO search_projection.generations (id, provider, state, config_hash, schema_version, manifest) - VALUES ($1, $2, 'building', $3, 1, $4)", + VALUES ($1, $2, 'building', $3, $4, $5)", ) .bind(gen_id) .bind(&cfg.provider) .bind(config_hash(&cfg)) + .bind(SCHEMA_FINGERPRINT) .bind(&manifest) .execute(&mut *tx_gen) .await @@ -860,8 +865,13 @@ fn two_beat_fence_xid_closes_gap_a_and_gap_b() { ) .await .unwrap(); - assert_eq!(res_a["nodes"].as_array().unwrap().len(), 1); - assert_eq!(res_a["nodes"][0]["fields"]["doc_id"][0], "doc-gap-a"); + let docs_a: std::collections::BTreeSet<&str> = res_a["nodes"] + .as_array() + .unwrap() + .iter() + .map(|n| n["fields"]["doc_id"][0].as_str().unwrap()) + .collect(); + assert_eq!(docs_a, std::collections::BTreeSet::from(["doc-gap-a"])); // Verify Gap B workspace has BOTH doc-1 (from T_w) and doc-2 (from T_2). let res_b = runtime @@ -1144,7 +1154,16 @@ fn admin_demotion_with_restricted_doc_excluded_from_search_and_aggregate() { .search_authorized(&actor_id, &ws_id, make_search()) .await .unwrap(); - assert_eq!(before_search["nodes"].as_array().unwrap().len(), 2); + let before_docs: std::collections::BTreeSet<&str> = before_search["nodes"] + .as_array() + .unwrap() + .iter() + .map(|n| n["fields"]["doc_id"][0].as_str().unwrap()) + .collect(); + assert_eq!( + before_docs, + std::collections::BTreeSet::from(["doc-public", "doc-secret"]) + ); // Demote actor from owner to member (transferring ownership to owner_id) and insert a new restricted doc-secret-2. let mut transfer_tx = pool.begin().await.unwrap(); @@ -1220,6 +1239,349 @@ fn admin_demotion_with_restricted_doc_excluded_from_search_and_aggregate() { }); } +const INLINE_REF: &str = r#"{"docId":"doc-target","mode":"page"}"#; + +/// Seeds a workspace where `doc-inline` mentions `doc-target` inline and +/// `doc-embed` embeds it, and returns `(owner_id, workspace_id)`. +async fn seed_backlink_workspace(pool: &sqlx::PgPool) -> (String, String) { + let owner_id = format!("owner-b-{}", Uuid::new_v4().simple()); + sqlx::query("INSERT INTO users(id, name, email, registered, disabled) VALUES ($1, 'Owner', $2, true, false)") + .bind(&owner_id) + .bind(format!("{owner_id}@affine.test")) + .execute(pool) + .await + .unwrap(); + let ws_id = format!("ws-backlinks-{}", Uuid::new_v4().simple()); + sqlx::query("INSERT INTO workspaces(id) VALUES ($1)") + .bind(&ws_id) + .execute(pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO workspace_members(id, workspace_id, user_id, role, source, state) + VALUES ($1, $2, $3, 'owner', 'legacy', 'active')", + ) + .bind(format!("m-b-{}", Uuid::new_v4().simple())) + .bind(&ws_id) + .bind(&owner_id) + .execute(pool) + .await + .unwrap(); + + let mut inline_doc = TestDoc::new("doc-inline", "Inline Doc"); + inline_doc.block( + "para-inline", + "affine:paragraph", + None, + vec![( + "prop:text", + TestValue::rich(&[ + ("quasar mention ", None), + ( + "Target Doc", + Some(TestValue::reference( + "doc-target", + vec![("mode", y_octo::Any::String("page".to_owned()))], + )), + ), + ]), + )], + ); + inline_doc.block( + "code-empty", + "affine:code", + None, + vec![ + ("prop:text", TestValue::text("")), + ("prop:language", TestValue::string("rust")), + ], + ); + let mut embed_doc = TestDoc::new("doc-embed", "Embed Doc"); + embed_doc.block( + "embed-linked", + "affine:embed-linked-doc", + None, + vec![ + ("prop:pageId", TestValue::string("doc-target")), + ("prop:text", TestValue::text("extra")), + ], + ); + sqlx::query( + "INSERT INTO snapshots(workspace_id, guid, blob, updated_at) + VALUES ($1, 'doc-target', $2, now()), ($1, 'doc-inline', $3, now()), ($1, 'doc-embed', $4, now())", + ) + .bind(&ws_id) + .bind(build_test_doc("Target Doc", "target body", "doc-target")) + .bind(inline_doc.encode()) + .bind(embed_doc.encode()) + .execute(pool) + .await + .unwrap(); + activate_workspace_lifecycle(pool, &[&ws_id]).await; + (owner_id, ws_id) +} + +fn match_query(field: &str, value: &str) -> SearchQuery { + SearchQuery { + query_type: "match".to_owned(), + field: Some(field.to_owned()), + match_value: Some(value.to_owned()), + query: None, + queries: None, + occur: None, + boost: None, + } +} + +fn first_page() -> SearchPagination { + SearchPagination { + limit: Some(10), + skip: None, + cursor: None, + } +} + +/// A bucket key, its count, and its `(doc_id, block_id, ref)` hits. +type BacklinkBucket = (String, u64, std::collections::BTreeSet<(String, String, String)>); + +/// Runs the backlink query for `doc-target`: an `aggregate` on `ref_doc_id`. +async fn backlink_buckets(runtime: &SearchRuntime, owner_id: &str, ws_id: &str) -> Vec { + let aggregate = runtime + .aggregate_authorized( + owner_id, + ws_id, + AggregateRequest { + table: SearchTable::Block, + field: "ref_doc_id".to_owned(), + query: match_query("refDocId", "doc-target"), + options: AggregateOptions { + pagination: first_page(), + hits: AggregateHitsOptions { + fields: ["docId", "blockId", "ref"].map(str::to_owned).to_vec(), + highlights: vec![], + pagination: first_page(), + }, + }, + }, + ) + .await + .unwrap(); + aggregate["buckets"] + .as_array() + .unwrap() + .iter() + .map(|bucket| { + let hits = bucket["hits"]["nodes"] + .as_array() + .unwrap() + .iter() + .map(|hit| { + let field = |name: &str| hit["fields"][name][0].as_str().unwrap().to_owned(); + (field("doc_id"), field("block_id"), field("ref")) + }) + .collect(); + ( + bucket["key"].as_str().unwrap().to_owned(), + bucket["count"].as_u64().unwrap(), + hits, + ) + }) + .collect() +} + +fn expected_backlinks() -> Vec { + vec![( + "doc-target".to_owned(), + 2, + std::collections::BTreeSet::from([ + ( + "doc-embed".to_owned(), + "embed-linked".to_owned(), + r#"{"docId":"doc-target"}"#.to_owned(), + ), + ("doc-inline".to_owned(), "para-inline".to_owned(), INLINE_REF.to_owned()), + ]), + )] +} + +#[test] +fn inline_reference_backlinks_match_embed_linked_doc_in_search_and_aggregate() { + let _xmin_guard = PRIVATE_CLUSTER_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let cluster = private_cluster(); + let empty = EmptyDbGuard::create(&cluster, "s_backlinks"); + + test_runtime().block_on(async { + let db = setup_db(&empty.url).await; + let pool = db.pool().clone(); + renew_lockless_v2_lease(&pool).await.unwrap(); + let (owner_id, ws_id) = seed_backlink_workspace(&pool).await; + + let runtime = SearchRuntime::new( + pool.clone(), + Arc::new(CommunityQuotaGate::new()), + enabled_search_config(), + ) + .expect("build search runtime"); + runtime.initialize().await.unwrap(); + for _ in 0..10 { + runtime.reconcile_pending(50).await.unwrap(); + } + + let search_content = |keyword: &'static str| { + runtime.search_authorized( + &owner_id, + &ws_id, + SearchRequest { + table: SearchTable::Block, + query: match_query("content", keyword), + options: SearchOptions { + fields: ["docId", "blockId", "refDocId", "ref"].map(str::to_owned).to_vec(), + highlights: vec![], + pagination: first_page(), + }, + }, + ) + }; + // The embed indexes no text. Its note joins the `block_text` of its + // children, which reads any `prop:text`, as the v0.27.5 server does. + let search = search_content("extra").await.unwrap(); + let extra_blocks: Vec<&str> = search["nodes"] + .as_array() + .unwrap() + .iter() + .map(|node| node["fields"]["block_id"][0].as_str().unwrap()) + .collect(); + assert_eq!(extra_blocks, ["note-doc-embed"], "search extra: {search}"); + // The empty code block is not indexed, and its language is not text. + let search = search_content("rust").await.unwrap(); + assert_eq!(search["nodes"], serde_json::json!([]), "search rust: {search}"); + let search = search_content("quasar").await.unwrap(); + // The paragraph matches, and so does its note, which indexes the text + // of its direct children. + let blocks: std::collections::BTreeMap<&str, &serde_json::Value> = search["nodes"] + .as_array() + .unwrap() + .iter() + .map(|node| (node["fields"]["block_id"][0].as_str().unwrap(), &node["fields"])) + .collect(); + assert_eq!( + blocks.keys().copied().collect::>(), + ["note-doc-inline", "para-inline"], + "search nodes: {search}" + ); + let fields = blocks["para-inline"]; + assert_eq!(fields["doc_id"], serde_json::json!(["doc-inline"])); + assert_eq!(fields["ref_doc_id"], serde_json::json!(["doc-target"])); + assert_eq!(fields["ref"], serde_json::json!([INLINE_REF])); + assert_eq!(blocks["note-doc-inline"]["doc_id"], serde_json::json!(["doc-inline"])); + + assert_eq!( + backlink_buckets(&runtime, &owner_id, &ws_id).await, + expected_backlinks() + ); + + db.pool().close().await; + }); +} + +#[test] +fn schema_upgrade_reprojects_unchanged_docs_and_retires_previous_generation() { + let _xmin_guard = PRIVATE_CLUSTER_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let cluster = private_cluster(); + let empty = EmptyDbGuard::create(&cluster, "s_schema_upgrade"); + + test_runtime().block_on(async { + let db = setup_db(&empty.url).await; + let pool = db.pool().clone(); + renew_lockless_v2_lease(&pool).await.unwrap(); + let (owner_id, ws_id) = seed_backlink_workspace(&pool).await; + + let runtime = SearchRuntime::new( + pool.clone(), + Arc::new(CommunityQuotaGate::new()), + enabled_search_config(), + ) + .expect("build search runtime"); + runtime.initialize().await.unwrap(); + for _ in 0..10 { + runtime.reconcile_pending(50).await.unwrap(); + } + let previous: Uuid = sqlx::query_scalar("SELECT id FROM search_projection.generations WHERE state = 'active'") + .fetch_one(&pool) + .await + .unwrap(); + + // Mark the active generation as written by the previous projection schema. + // No doc changes after this point. + sqlx::query("UPDATE search_projection.generations SET schema_version = $2 WHERE id = $1") + .bind(previous) + .bind(SCHEMA_FINGERPRINT - 1) + .execute(&pool) + .await + .unwrap(); + let error = runtime + .aggregate_authorized( + &owner_id, + &ws_id, + AggregateRequest { + table: SearchTable::Block, + field: "ref_doc_id".to_owned(), + query: match_query("refDocId", "doc-target"), + options: AggregateOptions::default(), + }, + ) + .await + .unwrap_err(); + assert!(matches!(error, SearchError::IndexNotReady), "got {error:?}"); + + for _ in 0..10 { + runtime.reconcile_pending(50).await.unwrap(); + } + let generations: Vec<(Uuid, String, i32)> = + sqlx::query_as("SELECT id, state, schema_version FROM search_projection.generations ORDER BY created_at") + .fetch_all(&pool) + .await + .unwrap(); + let active: Vec<_> = generations.iter().filter(|(_, state, _)| state == "active").collect(); + assert_eq!(active.len(), 1, "generations: {generations:?}"); + let (current, _, schema_version) = active[0]; + assert_ne!(*current, previous, "generations: {generations:?}"); + assert_eq!(*schema_version, SCHEMA_FINGERPRINT); + + let published: i64 = sqlx::query_scalar( + "SELECT count(*) FROM search_projection.document_states + WHERE generation_id = $1 AND doc_id IN ('doc-inline', 'doc-embed') + AND published_source_version = target_source_version", + ) + .bind(current) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(published, 2, "the new generation reprojects both unchanged docs"); + assert_eq!( + backlink_buckets(&runtime, &owner_id, &ws_id).await, + expected_backlinks() + ); + + // The drained generation of the previous schema is still retired. + sqlx::query("UPDATE search_projection.generations SET drained_at = now() - interval '25 hours' WHERE id = $1") + .bind(previous) + .execute(&pool) + .await + .unwrap(); + runtime.reconcile_pending(50).await.unwrap(); + let previous_left: bool = + sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM search_projection.generations WHERE id = $1)") + .bind(previous) + .fetch_one(&pool) + .await + .unwrap(); + assert!(!previous_left, "the previous schema generation is dropped"); + + db.pool().close().await; + }); +} + #[test] fn v0275_migration_prefix_verification_accepts_v6_database() { let _xmin_guard = PRIVATE_CLUSTER_LOCK.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/packages/backend/server-search/tests/support/test_doc.rs b/packages/backend/server-search/tests/support/test_doc.rs new file mode 100644 index 0000000000..e783b38416 --- /dev/null +++ b/packages/backend/server-search/tests/support/test_doc.rs @@ -0,0 +1,208 @@ +//! BlockSuite page binaries for search tests. The unit tests in +//! `src/doc_extract.rs` and the integration tests share this file. +#![allow(dead_code)] + +use std::collections::HashMap; + +use y_octo::{Any, Doc, TextAttributes, TextDeltaOp, TextInsert, Value}; + +/// Builds a minimal page binary with a title and one paragraph. +pub fn build_test_doc(title: &str, body: &str, page_id: &str) -> Vec { + let mut doc = TestDoc::new(page_id, title); + doc.block( + &format!("para-{page_id}"), + "affine:paragraph", + None, + vec![("prop:text", TestValue::text(body))], + ); + doc.encode() +} + +/// A block property value for [`TestDoc`]. +pub enum TestValue { + Any(Any), + /// A `Y.Text` built from `(text, attributes)` segments. + RichText(Vec<(String, TextAttributes)>), + /// A `Y.Text` built by applying each delta in turn. + Deltas(Vec>), + Map(Vec<(String, TestValue)>), + Array(Vec), +} + +impl TestValue { + pub fn text(text: &str) -> Self { + Self::RichText(vec![(text.to_owned(), TextAttributes::new())]) + } + + /// Builds a `Y.Text` from `(text, inline reference)` segments. + pub fn rich(segments: &[(&str, Option)]) -> Self { + Self::RichText( + segments + .iter() + .map(|(text, reference)| { + let attributes = reference + .iter() + .map(|reference| ("reference".to_owned(), reference.clone())) + .collect(); + ((*text).to_owned(), attributes) + }) + .collect(), + ) + } + + pub fn string(value: &str) -> Self { + Self::Any(Any::String(value.to_owned())) + } + + pub fn map(entries: Vec<(&str, TestValue)>) -> Self { + Self::Map( + entries + .into_iter() + .map(|(key, value)| (key.to_owned(), value)) + .collect(), + ) + } + + /// Builds an inline `reference` attribute value: `{pageId, params?}`. + pub fn reference(page_id: &str, params: Vec<(&str, Any)>) -> Any { + let mut reference = vec![("pageId".to_owned(), Any::String(page_id.to_owned()))]; + if !params.is_empty() { + reference.push(("params".to_owned(), object(params))); + } + reference.into_iter().collect() + } + + fn materialize(self, doc: &Doc) -> Value { + match self { + Self::Any(any) => Value::Any(any), + Self::RichText(segments) => { + let mut text = doc.create_text().expect("create test text"); + let delta = segments + .into_iter() + .map(|(insert, attributes)| TextDeltaOp::Insert { + insert: TextInsert::Text(insert), + format: (!attributes.is_empty()).then_some(attributes), + }) + .collect::>(); + text.apply_delta(&delta).expect("fill test text"); + Value::Text(text) + } + Self::Deltas(deltas) => { + let mut text = doc.create_text().expect("create test text"); + for delta in deltas { + text.apply_delta(&delta).expect("apply test delta"); + } + Value::Text(text) + } + Self::Map(entries) => { + let mut map = doc.create_map().expect("create test map"); + for (key, value) in entries { + map.insert(key, value.materialize(doc)).expect("fill test map"); + } + Value::Map(map) + } + Self::Array(values) => { + let mut array = doc.create_array().expect("create test array"); + for value in values { + array.push(value.materialize(doc)).expect("fill test array"); + } + Value::Array(array) + } + } + } +} + +/// Builds a plain `Any` object. +pub fn object(entries: Vec<(&str, Any)>) -> Any { + entries + .into_iter() + .map(|(key, value)| (key.to_owned(), value)) + .collect() +} + +struct TestBlock { + id: String, + flavour: String, + props: Vec<(String, TestValue)>, +} + +/// Builds page binaries: an `affine:page` with one `affine:note`, and blocks +/// under the note or under other blocks. +pub struct TestDoc { + blocks: Vec, + children: HashMap>, + note_id: String, +} + +impl TestDoc { + pub fn new(page_id: &str, title: &str) -> Self { + let note_id = format!("note-{page_id}"); + let mut doc = Self { + blocks: Vec::new(), + children: HashMap::new(), + note_id: note_id.clone(), + }; + doc.blocks.push(TestBlock { + id: page_id.to_owned(), + flavour: "affine:page".to_owned(), + props: vec![("prop:title".to_owned(), TestValue::text(title))], + }); + doc.children.insert(page_id.to_owned(), vec![note_id.clone()]); + doc.blocks.push(TestBlock { + id: note_id, + flavour: "affine:note".to_owned(), + props: Vec::new(), + }); + doc + } + + /// Adds a block under `parent`, or under the note when `parent` is `None`. + pub fn block(&mut self, id: &str, flavour: &str, parent: Option<&str>, props: Vec<(&str, TestValue)>) -> &mut Self { + let parent = parent.unwrap_or(&self.note_id).to_owned(); + self.children.entry(parent).or_default().push(id.to_owned()); + self.blocks.push(TestBlock { + id: id.to_owned(), + flavour: flavour.to_owned(), + props: props.into_iter().map(|(key, value)| (key.to_owned(), value)).collect(), + }); + self + } + + /// Adds a block that no block lists as a child. Other blocks can list it + /// through their own `sys:children` prop. + pub fn detached(&mut self, id: &str, flavour: &str, props: Vec<(&str, TestValue)>) -> &mut Self { + self.blocks.push(TestBlock { + id: id.to_owned(), + flavour: flavour.to_owned(), + props: props.into_iter().map(|(key, value)| (key.to_owned(), value)).collect(), + }); + self + } + + pub fn encode(mut self) -> Vec { + let doc = Doc::new(); + let mut blocks = doc.get_or_create_map("blocks").expect("blocks map"); + for TestBlock { id, flavour, props } in std::mem::take(&mut self.blocks) { + let mut entries = vec![ + ("sys:id".to_owned(), TestValue::Any(Any::String(id.clone()))), + ("sys:flavour".to_owned(), TestValue::Any(Any::String(flavour))), + ]; + if let Some(children) = self.children.remove(&id) { + entries.push(( + "sys:children".to_owned(), + TestValue::Array( + children + .into_iter() + .map(|child| TestValue::Any(Any::String(child))) + .collect(), + ), + )); + } + entries.extend(props); + blocks + .insert(id, TestValue::Map(entries).materialize(&doc)) + .expect("insert test block"); + } + doc.encode_update_v1().expect("encode yjs update") + } +}