First `get_richtext_value()` after import is slow with many marks

Đang mở
#1,256 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
58/100
Loại issue
Lỗi
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
rust
Lĩnh vực
backend, performance

Hướng nghiên cứu

Start by reproducing the timings with the provided Rust program and Loro 1.17.1, then inspect RichtextStateLoader::into_state and the first LazyLoad::get_mut() path identified in the report. The reported cost is one annotate_style_range call per mark; compare approaches for processing the sorted ranges or loading styles lazily. Done when the first get_richtext_value() on the imported marked text is substantially faster without changing the returned rich text.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

Hi! Thanks for Loro, we're building a document editor on it and it's been great so far.

After importing a snapshot, the first get_richtext_value() on a big text with lots of marks is slow, while the import and the second read are fast. ~900k chars, ~2,200 paragraphs, loro 1.17.1, release, median of 5:

marks import 1st read 2nd read
7,000 char + 2,900 paragraph 0.9 ms 555 ms 20 ms
200 + 100 4.3 ms 25 ms 0.7 ms
none 4.8 ms 3 ms 0.1 ms

Calling to_string() first or leaving out config_text_style doesn't change it. In our app it's ~250 ms of the 277 ms it takes to open a 300-page document.

Looks like it's RichtextStateLoader::into_state on the first LazyLoad::get_mut(), which calls annotate_style_range once per mark (~50 µs each). Could that be built in one pass from the sorted ranges, or done lazily? Or is there something we can do on our side? Happy to test anything.

Repro (loro = "=1.17.1", no other deps, cargo run --release)
// Repro: the first rich-text read after importing a snapshot is slow when the text has many marks.
use loro::{ExpandType, ExportMode, LoroDoc, StyleConfig, StyleConfigMap};
use std::time::Instant;

// Small deterministic PRNG (xorshift64*), so no extra dependencies.
struct Rng(u64);
impl Rng {
    fn next(&mut self) -> u64 {
        self.0 ^= self.0 >> 12;
        self.0 ^= self.0 << 25;
        self.0 ^= self.0 >> 27;
        self.0.wrapping_mul(0x2545F4914F6CDD1D)
    }
    fn below(&mut self, n: usize) -> usize {
        (self.next() % n as u64) as usize
    }
}

fn style_config() -> StyleConfigMap {
    let mut c = StyleConfigMap::new();
    for k in ["bold", "italic", "underline", "size", "color"] {
        c.insert(k.into(), StyleConfig::new().expand(ExpandType::After));
    }
    for k in ["link", "align", "heading", "list"] {
        c.insert(k.into(), StyleConfig::new().expand(ExpandType::None));
    }
    c
}

const WORDS: &[&str] = &[
    "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do",
    "eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim",
];

/// Builds one LoroText of ~900k chars in ~2,200 paragraphs, with `char_marks` marks on word
/// ranges and `para_marks` marks on '\n' chars. Returns the snapshot.
fn build(char_marks: usize, para_marks: usize) -> Vec<u8> {
    let mut rng = Rng(0x9E3779B97F4A7C15);
    let doc = LoroDoc::new();
    doc.config_text_style(style_config());
    let text = doc.get_text("body");

    // Paragraphs of ~410 chars; remember word ranges (unicode offsets) and newline positions.
    let mut s = String::new();
    let mut words: Vec<(usize, usize)> = Vec::new();
    let mut newlines: Vec<usize> = Vec::new();
    let mut pos = 0;
    for _ in 0..2216 {
        let target = 300 + rng.below(220);
        let start = pos;
        while pos - start < target {
            let w = WORDS[rng.below(WORDS.len())];
            words.push((pos, pos + w.len()));
            s.push_str(w);
            s.push(' ');
            pos += w.len() + 1;
        }
        newlines.push(pos);
        s.push('\n');
        pos += 1;
    }
    text.insert(0, &s).unwrap();

    let char_keys = ["bold", "italic", "underline", "size", "color", "link"];
    for _ in 0..char_marks {
        let i = rng.below(words.len() - 4);
        let n = 1 + rng.below(4); // 1..=4 words
        let (a, _) = words[i];
        let (_, b) = words[i + n - 1];
        let key = char_keys[rng.below(char_keys.len())];
        let value: loro::LoroValue = match key {
            "bold" | "italic" | "underline" => true.into(),
            "size" => (10 + rng.below(20) as i64).into(),
            "color" => format!("#{:06x}", rng.below(0xFFFFFF)).into(),
            _ => format!("https://example.com/{}", rng.below(1000)).into(),
        };
        text.mark(a..b, key, value).unwrap();
    }
    let para_keys = ["align", "heading", "list"];
    for i in 0..para_marks {
        let nl = newlines[(i * 7919 + rng.below(13)) % newlines.len()];
        let key = para_keys[rng.below(para_keys.len())];
        text.mark(nl..nl + 1, key, rng.below(4) as i64).unwrap();
    }
    doc.commit();
    doc.export(ExportMode::Snapshot).unwrap()
}

fn ms(t: Instant) -> f64 {
    t.elapsed().as_secs_f64() * 1000.0
}

/// Imports the snapshot into a fresh doc and times import, first and second rich read.
fn measure(snapshot: &[u8], configure: bool, plain_first: bool) -> [f64; 4] {
    let doc = LoroDoc::new();
    if configure {
        doc.config_text_style(style_config());
    }
    let t = Instant::now();
    doc.import(snapshot).unwrap();
    let import = ms(t);
    let text = doc.get_text("body");
    let t = Instant::now();
    let plain = if plain_first {
        std::hint::black_box(text.to_string());
        ms(t)
    } else {
        f64::NAN
    };
    let t = Instant::now();
    std::hint::black_box(text.get_richtext_value());
    let first = ms(t);
    let t = Instant::now();
    std::hint::black_box(text.get_richtext_value());
    let second = ms(t);
    [import, plain, first, second]
}

fn main() {
    let full = build(7000, 2900);
    let few = build(200, 100);
    let none = build(0, 0);
    let cases: [(&str, &[u8], bool, bool); 5] = [
        ("7000+2900 marks", &full, true, false),
        ("7000+2900 marks, to_string() first", &full, true, true),
        ("7000+2900 marks, no config_text_style", &full, false, false),
        ("200+100 marks", &few, true, false),
        ("no marks", &none, true, false),
    ];
    for (name, snap, cfg, plain) in cases {
        let [i, p, f, s] = measure(snap, cfg, plain);
        println!("{name}\t{}\t{i:.2}\t{p:.2}\t{f:.2}\t{s:.2}", snap.len());
    }
}
Ngôn ngữ chính
Rust
Star
6.3k
Fork
205
Merge trung bình
3 ngày 20 giờ
Pull request đã merge (30 ngày)
47

Chuẩn bị môi trường

Mở trong Codespaces

Khởi chạy dev container của dự án ngay trên trình duyệt, bằng tài khoản GitHub của bạn.

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của loro-dev/loro

Tất cả issue của loro-dev/loro

Issue tương tự

Thêm issue về Rust

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.