diff: Highlight rows against whole-file context

f44235e955c741b997900f752319f9f2edc9561b
A syntax tokenizer state depends on every preceding line. Highlight each
changed row against its full old-side or new-side source so enclosing
blocks, comments, strings, and heredocs keep the correct scope.

Store a compact line index with each retained source. Validate hunk rows
through direct indexed lookup before rendering source text.

Load worktree sources only from normalized paths inside the repository.
Bound regular-file reads and use symbolic-link target text as the
source.

Key committed sources by object id so hunk filtering and context changes
keep valid data. Keep whole-file sources in the background worker, and
cap retained source data per file and per viewer.

Assisted-by: Codex:gpt-5.5
Alexis Sellier committed ago 1 parent b9abe0c9
AGENTS.md +1 -0
26 26
And follow these rules:
27 27
28 28
* NEVER add a new dependency to Cargo.toml without first asking me.
29 29
* ALWAYS document top-level symbols, even the private ones.
30 30
* ALWAYS document struct fields and enum variants, even the private ones.
31 +
* ALWAYS use the existing repository command helper to invoke Git when one is available.
31 32
* ALWAYS structure human-facing terminal output with the existing UI primitives
32 33
  (`Table`, `VStack`, `HStack`, `Line`, labels, and related renderable types)
33 34
  instead of hand-aligning text with ad hoc spacing.
34 35
* Always do things the proper, idiomatic, robust way. NO HACKS.
35 36
* After the tests pass, run the benchmarks for the crate to ensure no regressions.
crates/brain/src/session.rs +1 -1
540 540
        }) else {
541 541
            return Ok(());
542 542
        };
543 543
        let document = DiffDocument::for_hunks(file, [focused.clone()]);
544 544
        let mut viewer = DiffViewer::new(document, options);
545 -
        viewer.load_file_locs(|oid| self.brain.read_blob(oid))?;
545 +
        viewer.load_file_sources(|oid| self.brain.read_blob(oid))?;
546 546
547 547
        let mut view = HunkView::new(hunk, viewer, self.comments.author().to_owned());
548 548
        view.start_new();
549 549
        self.mode = Mode::Hunk(Box::new(view));
550 550
        self.restart_highlighter()?;
crates/brain/src/session/commit.rs +1 -1
87 87
        brain: &Brain,
88 88
        store: &ReviewComments,
89 89
    ) -> Result<Self, Error> {
90 90
        let document = document.split_hunks();
91 91
        let mut viewer = DiffViewer::new(document, options);
92 -
        viewer.load_file_locs(|oid| brain.read_blob(oid))?;
92 +
        viewer.load_file_sources(|oid| brain.read_blob(oid))?;
93 93
        let files = viewer.document().files.clone();
94 94
        let identities = brain.hunk_identities(viewer.document(), commit.id)?;
95 95
        let heading = format!("{} {}", commit.id.short(), commit.summary);
96 96
        let mut hunk_patches = BTreeMap::new();
97 97
        let review = Review::new();
a.rs +0 -0
crates/diff/benches/highlight.rs +53 -83
1 1
//! Highlight pipeline benchmarks for `rustik-diff`.
2 2
//!
3 3
//! The benchmark mirrors the interactive pager's slow path more closely than
4 -
//! the render benchmark: it times built-in grammar/theme setup, bounded context
5 -
//! patch decode, source extraction, visible request collection, and the final
6 -
//! highlight/apply/render pass.
4 +
//! the render benchmark. It times built-in grammar and theme setup, whole-file
5 +
//! source indexing, request collection, and the final highlight, apply, and
6 +
//! render pass.
7 7
//!
8 8
//! Run with `cargo bench -p rustik-diff --bench highlight`.
9 9
10 -
use std::collections::BTreeMap;
10 +
use std::convert::Infallible;
11 11
use std::hint::black_box;
12 12
use std::io::{self, Write as _};
13 -
use std::path::PathBuf;
14 13
use std::time::{Duration, Instant};
15 14
16 -
use rustik_diff::{
17 -
    BuiltinHighlighter, Decode, DiffAction, DiffDocument, DiffOptions, DiffSide, DiffViewer,
18 -
    HighlightRequest, HighlightSource,
19 -
};
15 +
use rustik_diff::{BuiltinHighlighter, Decode, DiffAction, DiffDocument, DiffOptions, DiffViewer};
20 16
use rustik_highlight as syntax;
21 17
use rustik_tui::{Buffer, Color, Constraint, Label, Rect, Scroll, Style, Table, TableOptions};
22 18
23 19
/// Fixed terminal-sized render area.
24 20
const AREA: Rect = Rect::new(0, 0, 120, 40);
25 21
/// Default source line number targeted by the generated patch.
26 22
const DEFAULT_LINES: usize = 100_000;
27 -
/// Default source context rows generated around the changed line.
28 -
const DEFAULT_CONTEXT_LINES: usize = 256;
29 23
/// Default number of independent timed runs.
30 24
const DEFAULT_RUNS: usize = 3;
31 25
/// Context rows in the sparse viewport document.
32 26
const SPARSE_CONTEXT_LINES: usize = 32;
33 27
/// Theme name used by the interactive pager.
41 35
42 36
/// Runs the benchmark.
43 37
fn main() {
44 38
    let args = Args::parse();
45 39
    let sparse_patch = synthetic_context_diff("src/slow.rs", args.lines, SPARSE_CONTEXT_LINES);
46 -
    let context_patch = synthetic_context_diff("src/slow.rs", args.lines, args.context_lines);
47 40
    let sparse_document = decode_patch(&sparse_patch);
41 +
    let old_source = synthetic_source(args.lines, SPARSE_CONTEXT_LINES, "old");
42 +
    let new_source = synthetic_source(args.lines, SPARSE_CONTEXT_LINES, "new");
48 43
    let widths = ReportWidths::new();
49 44
    let mut totals = StageDurations::default();
50 45
    let mut checksum = 0usize;
51 46
52 47
    for _ in 0..args.runs {
53 -
        let report = run_once(&sparse_document, &context_patch);
48 +
        let report = run_once(&sparse_document, &old_source, &new_source);
54 49
        totals += report.stages;
55 50
        checksum ^= report.checksum;
56 51
    }
57 52
    let stats = totals.div(args.runs);
58 53
59 54
    report_stage("assets", stats.assets, widths);
60 -
    report_stage("context-decode", stats.context_decode, widths);
61 -
    report_stage("source-build", stats.source_build, widths);
55 +
    report_stage("whole-source", stats.whole_source, widths);
62 56
    report_stage("requests", stats.requests, widths);
63 57
    report_stage("land", stats.land, widths);
64 58
    io::stdout().flush().ok();
65 59
66 60
    black_box(checksum);
69 63
/// Benchmark command-line arguments.
70 64
#[derive(Clone, Copy, Debug)]
71 65
struct Args {
72 66
    /// Source line number targeted by the generated patch.
73 67
    lines: usize,
74 -
    /// Source context rows generated around the changed line.
75 -
    context_lines: usize,
76 68
    /// Number of independent timed runs.
77 69
    runs: usize,
78 70
}
79 71
80 72
impl Args {
81 73
    /// Parses benchmark arguments from the process environment.
82 74
    fn parse() -> Self {
83 75
        let mut parsed = Self {
84 76
            lines: DEFAULT_LINES,
85 -
            context_lines: DEFAULT_CONTEXT_LINES,
86 77
            runs: DEFAULT_RUNS,
87 78
        };
88 79
        let mut args = std::env::args().skip(1);
89 80
90 81
        while let Some(arg) = args.next() {
91 82
            match arg.as_str() {
92 83
                "--lines" => parsed.lines = next_usize(&mut args, parsed.lines),
93 -
                "--context" => parsed.context_lines = next_usize(&mut args, parsed.context_lines),
94 84
                "--runs" => parsed.runs = next_usize(&mut args, parsed.runs).max(1),
95 85
                "--help" | "-h" => {
96 86
                    println!(
97 -
                        "usage: cargo bench -p rustik-diff --bench highlight -- [--lines N] [--context N] [--runs N]"
87 +
                        "usage: cargo bench -p rustik-diff --bench highlight -- [--lines N] [--runs N]"
98 88
                    );
99 89
                    std::process::exit(0);
100 90
                }
101 91
                _ => {}
102 92
            }
108 98
/// Stage timings from one benchmark run.
109 99
#[derive(Clone, Copy, Debug, Default)]
110 100
struct StageDurations {
111 101
    /// Built-in theme and grammar setup.
112 102
    assets: Duration,
113 -
    /// Bounded-context unified-diff decode.
114 -
    context_decode: Duration,
115 -
    /// Context source extraction from decoded diff data.
116 -
    source_build: Duration,
103 +
    /// Whole-file source indexing and loading.
104 +
    whole_source: Duration,
117 105
    /// Visible highlight request collection.
118 106
    requests: Duration,
119 107
    /// Syntax highlight, cache apply, and highlighted render.
120 108
    land: Duration,
121 109
}
125 113
    fn div(self, count: usize) -> Self {
126 114
        let count = count.max(1) as u32;
127 115
128 116
        Self {
129 117
            assets: self.assets / count,
130 -
            context_decode: self.context_decode / count,
131 -
            source_build: self.source_build / count,
118 +
            whole_source: self.whole_source / count,
132 119
            requests: self.requests / count,
133 120
            land: self.land / count,
134 121
        }
135 122
    }
136 123
}
137 124
138 125
impl std::ops::AddAssign for StageDurations {
139 126
    fn add_assign(&mut self, rhs: Self) {
140 127
        self.assets += rhs.assets;
141 -
        self.context_decode += rhs.context_decode;
142 -
        self.source_build += rhs.source_build;
128 +
        self.whole_source += rhs.whole_source;
143 129
        self.requests += rhs.requests;
144 130
        self.land += rhs.land;
145 131
    }
146 132
}
147 133
165 151
166 152
impl ReportWidths {
167 153
    /// Computes report column widths.
168 154
    fn new() -> Self {
169 155
        Self {
170 -
            stage: "context-decode".len(),
156 +
            stage: "whole-source".len(),
171 157
            duration: DURATION_FORMAT.len(),
172 158
        }
173 159
    }
174 160
}
175 161
179 165
        .and_then(|value| value.parse().ok())
180 166
        .unwrap_or(fallback)
181 167
}
182 168
183 169
/// Runs one timed highlight pipeline pass.
184 -
fn run_once(sparse_document: &DiffDocument, context_patch: &str) -> BenchReport {
170 +
fn run_once(sparse_document: &DiffDocument, old_source: &str, new_source: &str) -> BenchReport {
185 171
    let mut stages = StageDurations::default();
186 172
    let mut checksum = 0usize;
187 173
188 174
    let start = Instant::now();
189 175
    let mut highlighter = build_highlighter();
190 176
    stages.assets = start.elapsed();
191 177
178 +
    let old_oid = sparse_document.files[0].header.old_oid.unwrap();
179 +
    let mut viewer = DiffViewer::new(sparse_document.clone(), DiffOptions::default());
192 180
    let start = Instant::now();
193 -
    let context_document = decode_patch(context_patch);
194 -
    stages.context_decode = start.elapsed();
195 -
196 -
    let start = Instant::now();
197 -
    let context_sources = context_sources(&context_document);
198 -
    stages.source_build = start.elapsed();
181 +
    viewer
182 +
        .load_file_sources(|oid| {
183 +
            let source = if oid == old_oid {
184 +
                old_source
185 +
            } else {
186 +
                new_source
187 +
            };
188 +
            Ok::<_, Infallible>(source.as_bytes().to_vec())
189 +
        })
190 +
        .unwrap();
191 +
    stages.whole_source = start.elapsed();
199 192
200 -
    let mut viewer = DiffViewer::new(sparse_document.clone(), DiffOptions::default());
201 193
    let rows = rustik_tui::Widget::size(&viewer, Constraint::UNBOUNDED).rows;
202 194
    viewer.apply(DiffAction::Scroll(Scroll::Lines((rows / 2) as isize)), AREA);
203 195
204 196
    let start = Instant::now();
205 197
    let requests = viewer.highlight_requests(AREA);
206 198
    stages.requests = start.elapsed();
207 199
208 200
    let start = Instant::now();
209 -
    let requests = context_source_requests(requests, &context_sources);
210 201
    let results = highlighter.highlight_requests(requests);
211 202
212 203
    checksum ^= results.len();
213 204
    viewer.apply_highlights(results);
214 205
218 209
    stages.land = start.elapsed();
219 210
220 211
    BenchReport { stages, checksum }
221 212
}
222 213
214 +
/// Creates a full source whose visible hunk matches the generated sparse diff.
215 +
fn synthetic_source(lines: usize, context_lines: usize, changed_value: &str) -> String {
216 +
    let changed = lines.max(1).div_ceil(2);
217 +
    let before = context_lines.min(changed.saturating_sub(1));
218 +
    let after = context_lines.min(lines.saturating_sub(changed));
219 +
    let start = changed - before;
220 +
    let end = changed + after;
221 +
    let mut source = String::new();
222 +
223 +
    for line in 1..=lines {
224 +
        if (start..=end).contains(&line) {
225 +
            let value = if line == changed {
226 +
                changed_value
227 +
            } else {
228 +
                "same"
229 +
            };
230 +
            push_source_line(&mut source, line, value);
231 +
        } else {
232 +
            source.push_str("x\n");
233 +
        }
234 +
    }
235 +
    source
236 +
}
237 +
223 238
/// Builds a highlighter for the generated Rust source file.
224 239
fn build_highlighter() -> BuiltinHighlighter {
225 240
    let raw_theme = match THEME.parse::<syntax::RawTheme>() {
226 241
        Ok(theme) => theme,
227 242
        Err(error) => {
266 281
            std::process::exit(1);
267 282
        }
268 283
    }
269 284
}
270 285
271 -
/// Extracts bounded context sources from a context diff document.
272 -
fn context_sources(document: &DiffDocument) -> BTreeMap<(PathBuf, DiffSide), Vec<HighlightSource>> {
273 -
    let mut sources = BTreeMap::new();
274 -
275 -
    for file in &document.files {
276 -
        for side in [DiffSide::Old, DiffSide::New] {
277 -
            let Some(path) = file.source_path(side) else {
278 -
                continue;
279 -
            };
280 -
            let side_sources = file
281 -
                .hunks
282 -
                .iter()
283 -
                .map(|hunk| hunk.highlight_source(side))
284 -
                .collect::<Vec<_>>();
285 -
            sources.insert((path, side), side_sources);
286 -
        }
287 -
    }
288 -
    sources
289 -
}
290 -
291 -
/// Replaces sparse hunk sources with context sources where line text matches.
292 -
fn context_source_requests(
293 -
    requests: Vec<HighlightRequest>,
294 -
    sources: &BTreeMap<(PathBuf, DiffSide), Vec<HighlightSource>>,
295 -
) -> Vec<HighlightRequest> {
296 -
    requests
297 -
        .into_iter()
298 -
        .map(|mut request| {
299 -
            let Some(path) = request.path.as_ref() else {
300 -
                return request;
301 -
            };
302 -
            let key = (path.clone(), request.key.side);
303 -
            if let Some(source) = sources.get(&key).and_then(|sources| {
304 -
                sources.iter().find(|source| {
305 -
                    source.line(request.key.source_line)
306 -
                        == request.source.line(request.key.source_line)
307 -
                })
308 -
            }) {
309 -
                request.source = source.clone();
310 -
            }
311 -
            request
312 -
        })
313 -
        .collect()
314 -
}
315 -
316 286
/// Creates a deterministic Git-style unified diff for one centered file hunk.
317 287
fn synthetic_context_diff(path: &str, lines: usize, context_lines: usize) -> String {
318 288
    let mut diff = String::new();
319 289
320 290
    diff.push_str(&format!("
{path}\n")); +0 -0
crates/diff/src/bin/rustik-diff.rs +11 -2
78 78
        buf
79 79
    };
80 80
    run_or_forward(&input, &cwd, repo, debug)
81 81
}
82 82
83 +
/// Loads highlight context for files whose new side only exists in the worktree.
84 +
fn load_worktree_sources(viewer: &mut DiffViewer, repository: &git::Repository) {
85 +
    if let Ok(root) = repository.workdir() {
86 +
        viewer.load_worktree_sources(&root);
87 +
    }
88 +
}
89 +
83 90
/// Renders diff input or passes non-diff data through unchanged.
84 91
fn run_or_forward(input: &[u8], cwd: &Path, repo: RenderRepo, debug: bool) -> Result<(), Error> {
85 92
    let document = match DiffDocument::decode_bytes(input) {
86 93
        Ok(document) if !document.is_empty() => document,
87 94
        Ok(_) => {
109 116
        options.file_tree_root = root;
110 117
    }
111 118
    let mut viewer = DiffViewer::new(document, options);
112 119
    match &repo {
113 120
        RenderRepo::Git(repository) => {
114 -
            let _ = viewer.load_file_locs(|oid| repository.cat_blob(oid));
121 +
            let _ = viewer.load_file_sources(|oid| repository.cat_blob(oid));
122 +
            load_worktree_sources(&mut viewer, repository);
115 123
        }
116 124
        RenderRepo::Stdin => {
117 125
            if let Ok(repository) = git::Repository::discover(cwd.to_path_buf()) {
118 -
                let _ = viewer.load_file_locs(|oid| repository.cat_blob(oid));
126 +
                let _ = viewer.load_file_sources(|oid| repository.cat_blob(oid));
127 +
                load_worktree_sources(&mut viewer, &repository);
119 128
            }
120 129
        }
121 130
    }
122 131
123 132
    if !interactive {
crates/diff/src/highlight.rs +72 -3
70 70
pub struct HighlightSource {
71 71
    /// Source-side text assembled from the diff.
72 72
    pub text: Arc<str>,
73 73
    /// Source line represented by the head of [`HighlightSource::text`].
74 74
    pub head: u32,
75 +
    /// Byte offset of each source line.
76 +
    line_starts: Arc<[u32]>,
75 77
}
76 78
77 79
/// Pure built-in highlighter for visible diff rows.
78 80
#[derive(Debug)]
79 81
pub struct BuiltinHighlighter {
157 159
}
158 160
159 161
impl HighlightSource {
160 162
    /// Creates source text beginning at a source line.
161 163
    pub fn new(text: impl Into<Arc<str>>, head: u32) -> Self {
164 +
        let text = text.into();
165 +
        let mut line_starts = Vec::new();
166 +
        if !text.is_empty() {
167 +
            line_starts.push(0);
168 +
            line_starts.extend(
169 +
                text.bytes()
170 +
                    .enumerate()
171 +
                    .filter(|(index, byte)| *byte == b'\n' && index + 1 < text.len())
172 +
                    .map(|(index, _)| (index + 1) as u32),
173 +
            );
174 +
        }
162 175
        Self {
163 -
            text: text.into(),
176 +
            text,
164 177
            head,
178 +
            line_starts: line_starts.into(),
165 179
        }
166 180
    }
167 181
168 182
    /// Returns the zero-based source-text line index for a source line.
169 183
    pub fn line_index(&self, source_line: u32) -> Option<usize> {
170 184
        source_line.checked_sub(self.head).map(|line| line as usize)
171 185
    }
172 186
173 187
    /// Returns one source line without its trailing line terminator.
174 188
    pub fn line(&self, source_line: u32) -> Option<&str> {
175 -
        self.line_index(source_line)
176 -
            .and_then(|index| self.text.lines().nth(index))
189 +
        let index = self.line_index(source_line)?;
190 +
        self.indexed_line(index)
191 +
    }
192 +
193 +
    /// Returns one source line by its zero-based index.
194 +
    fn indexed_line(&self, index: usize) -> Option<&str> {
195 +
        let start = *self.line_starts.get(index)? as usize;
196 +
        let mut end = self
197 +
            .line_starts
198 +
            .get(index + 1)
199 +
            .map_or(self.text.len(), |next| *next as usize);
200 +
        if end > start && self.text.as_bytes()[end - 1] == b'\n' {
201 +
            end -= 1;
202 +
        }
203 +
        if end > start && self.text.as_bytes()[end - 1] == b'\r' {
204 +
            end -= 1;
205 +
        }
206 +
        Some(&self.text[start..end])
207 +
    }
208 +
209 +
    /// Returns the bytes retained by this source and its line index.
210 +
    pub(crate) fn retained_bytes(&self) -> usize {
211 +
        self.text
212 +
            .len()
213 +
            .saturating_add(self.line_starts.len() * size_of::<u32>())
214 +
    }
215 +
216 +
    /// Returns whether this source reproduces every row `hunk` shows on `side`.
217 +
    ///
218 +
    /// Highlighted rows are rendered from the source text, not the diff, so a
219 +
    /// source that has drifted from the patch would display lines the patch
220 +
    /// never contained. Worktree files drift whenever they are edited after the
221 +
    /// diff was produced.
222 +
    pub fn matches_hunk(&self, hunk: &Hunk, side: DiffSide) -> bool {
223 +
        let Some(mut line) = self.line_index(hunk_head(hunk, side)) else {
224 +
            return false;
225 +
        };
226 +
227 +
        hunk.lines
228 +
            .iter()
229 +
            .filter(|line| source_len(line, side) != 0)
230 +
            .all(|expected| {
231 +
                let matches = self.indexed_line(line) == Some(expected.text.as_str());
232 +
                line += 1;
233 +
                matches
234 +
            })
177 235
    }
178 236
179 237
    /// Returns a compact identity for grouping requests that share this source.
180 238
    fn id(&self) -> HighlightSourceId {
181 239
        HighlightSourceId {
525 583
        assert_eq!(source.line(1), None);
526 584
        assert_eq!(source.line_index(2), Some(0));
527 585
        assert_eq!(source.line(2), Some("two"));
528 586
    }
529 587
588 +
    #[test]
589 +
    fn indexed_source_lines_match_rust_line_boundaries() {
590 +
        let source = HighlightSource::new("one\r\ntwo\n\nthree", 1);
591 +
592 +
        assert_eq!(source.line(1), Some("one"));
593 +
        assert_eq!(source.line(2), Some("two"));
594 +
        assert_eq!(source.line(3), Some(""));
595 +
        assert_eq!(source.line(4), Some("three"));
596 +
        assert_eq!(source.line(5), None);
597 +
    }
598 +
530 599
    #[test]
531 600
    fn file_highlight_source_spans_the_new_side() {
532 601
        let document = crate::DiffDocument::decode_str(
533 602
            "\
534 603
a.css +0 -0
a.rs\n", +0 -0
crates/diff/src/highlighter.rs +57 -1
221 221
            return;
222 222
        };
223 223
        let mut targets = BTreeMap::new();
224 224
        for request in requests {
225 225
            let key = (request.key.file, request.key.side);
226 -
            if self.context_sources.contains_key(&key) {
226 +
            // Skip sides the viewer already supplied whole-file context for;
227 +
            // refetching them would cost a `git diff` whose result is unused.
228 +
            if self.context_sources.contains_key(&key) || request.source.head == 1 {
227 229
                continue;
228 230
            }
229 231
            if let Some(path) = request.path.as_deref() {
230 232
                targets.insert((path.to_path_buf(), request.key.side), request.key.file);
231 233
            }
265 267
        }
266 268
    }
267 269
268 270
    /// Returns cached context that contains the requested source row.
269 271
    fn context_source_for(&self, request: &HighlightRequest) -> Option<&HighlightSource> {
272 +
        // A source starting at line 1 already carries every line the tokenizer
273 +
        // state depends on. The bounded refetch would only narrow it, dropping
274 +
        // context for rows further than HIGHLIGHT_CONTEXT_LINES into a file.
275 +
        if request.source.head == 1 {
276 +
            return None;
277 +
        }
270 278
        let key = (request.key.file, request.key.side);
271 279
        let expected = request.source.line(request.key.source_line)?;
272 280
        self.context_sources
273 281
            .get(&key)?
274 282
            .iter()
283 291
284 292
        drop(paths);
285 293
        request.decode(&patch).ok().flatten()
286 294
    }
287 295
}
296 +
297 +
#[cfg(test)]
298 +
mod tests {
299 +
    use super::*;
300 +
    use crate::{HighlightKey, HighlightKeyInput, HunkId, RowId};
301 +
302 +
    /// Returns a request for row 5, carrying `source`.
303 +
    fn request(source: HighlightSource) -> HighlightRequest {
304 +
        HighlightRequest {
305 +
            key: HighlightKey::new(HighlightKeyInput {
306 +
                file: FileId::new(0),
307 +
                side: DiffSide::New,
308 +
                source_line: 5,
309 +
                text: "row",
310 +
                syntax: None,
311 +
                theme: "auto",
312 +
            }),
313 +
            hunk: HunkId::new(0),
314 +
            row: RowId::new(0),
315 +
            path: None,
316 +
            source,
317 +
        }
318 +
    }
319 +
320 +
    #[test]
321 +
    fn whole_file_sources_are_not_narrowed_to_bounded_context() {
322 +
        let mut worker = HighlightWorker::new(
323 +
            Seed {
324 +
                paths: Vec::new(),
325 +
                head_oids: BTreeMap::new(),
326 +
            },
327 +
            None,
328 +
        );
329 +
        worker.context_sources.insert(
330 +
            (FileId::new(0), DiffSide::New),
331 +
            vec![HighlightSource::new("row\n", 5)],
332 +
        );
333 +
334 +
        // A hunk-only source is still upgraded to the refetched context.
335 +
        let hunk_only = request(HighlightSource::new("row\n", 5));
336 +
        assert!(worker.context_source_for(&hunk_only).is_some());
337 +
338 +
        // A whole-file source is left alone: the refetch spans only
339 +
        // HIGHLIGHT_CONTEXT_LINES and would drop context before that.
340 +
        let whole_file = request(HighlightSource::new("a\nb\nc\nd\nrow\n", 1));
341 +
        assert!(worker.context_source_for(&whole_file).is_none());
342 +
    }
343 +
}
crates/diff/src/viewer.rs +218 -17
3 3
mod tree;
4 4
5 5
use std::collections::btree_map::Entry;
6 6
use std::collections::{BTreeMap, BTreeSet};
7 7
use std::convert::Infallible;
8 +
use std::io::Read as _;
8 9
use std::ops::Range;
9 -
use std::path::{Path, PathBuf};
10 +
use std::path::{Component, Path, PathBuf};
10 11
use std::sync::Arc;
11 12
12 13
use rustik_highlight as syntax;
13 14
use rustik_tui as tui;
14 15
use tui::{
21 22
use crate::decorate::{DiffDecorator, FileDecoration, HunkDecoration, ReviewProgress};
22 23
use crate::highlight::{DiffHighlighter, HighlightKeyInput, HighlightResult};
23 24
use crate::word;
24 25
use crate::{
25 26
    Commit, Decode, DecodeError, DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId,
26 -
    FileKind, FileStats, HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId, Oid, RowId,
27 +
    FileKind, FileMode, FileStats, HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId,
28 +
    Oid, RowId,
27 29
};
28 30
29 31
pub use tree::{FileTree, FileTreeMode, FileTreeTarget};
30 32
31 33
/// Visible and lookahead row ranges that should be highlighted.
243 245
    highlights: BTreeMap<HighlightKey, Line>,
244 246
    /// Requests already handed to a worker.
245 247
    pending_highlights: BTreeSet<HighlightKey>,
246 248
    /// Per-hunk source context reused across highlight-request batches.
247 249
    hunk_highlight_sources: BTreeMap<(FileId, HunkId, DiffSide), HighlightSource>,
250 +
    /// Whole-file source text used as highlighting context, keyed by blob.
251 +
    ///
252 +
    /// A syntax tokenizer's state at a line is the fold of every line before it,
253 +
    /// so a hunk highlighted in isolation starts from a default state and loses
254 +
    /// any enclosing block, comment, or string. Highlighting against the whole
255 +
    /// blob restores that context; sides with no blob (added or deleted files)
256 +
    /// are absent and fall back to the hunk-only source.
257 +
    ///
258 +
    /// Keying by object id rather than by file means hiding hunks or widening
259 +
    /// context cannot invalidate an entry: those rewrite a file's hunks but
260 +
    /// leave it pointing at the same blobs.
261 +
    blob_sources: BTreeMap<Oid, HighlightSource>,
262 +
    /// Whole-file source text for worktree files, which have no new-side blob.
263 +
    worktree_sources: BTreeMap<PathBuf, HighlightSource>,
264 +
    /// Total bytes held across both source maps.
265 +
    source_bytes: usize,
248 266
    /// Cached intra-line word diffs, keyed by hunk.
249 267
    word_diffs: BTreeMap<HunkId, word::WordChanges>,
250 268
    /// Rendered commit-preamble rows for the most recent body width.
251 269
    preamble: Vec<Line>,
252 270
    /// File-tree state and model.
275 293
    files: Vec<IndexedFileRows>,
276 294
    /// Total number of rendered rows.
277 295
    rows: usize,
278 296
}
279 297
298 +
/// Largest blob kept as syntax-highlighting context, in bytes.
299 +
///
300 +
/// Tokenizing the lines before a hunk is linear in the prefix and cached per
301 +
/// file, so the cap only guards against pathological inputs such as minified
302 +
/// bundles or generated data.
303 +
const MAX_SOURCE_BYTES: usize = 2 * 1024 * 1024;
304 +
305 +
/// Total bytes of highlight context a viewer keeps across all files.
306 +
///
307 +
/// A per-blob cap alone bounds nothing in aggregate: a review touching
308 +
/// thousands of files would otherwise hold every one of their sides resident.
309 +
/// Files past the budget keep using hunk-only sources.
310 +
const MAX_TOTAL_SOURCE_BYTES: usize = 64 * 1024 * 1024;
311 +
312 +
/// One source blob read for LOC metadata and highlight context.
313 +
#[derive(Clone, Debug)]
314 +
struct LoadedBlob {
315 +
    /// Nonblank line count.
316 +
    loc: usize,
317 +
    /// Blob source, absent when the blob is binary or above [`MAX_SOURCE_BYTES`].
318 +
    source: Option<HighlightSource>,
319 +
}
320 +
321 +
impl LoadedBlob {
322 +
    /// Counts lines and keeps the text when it is usable as highlight context.
323 +
    fn read(bytes: Vec<u8>) -> Self {
324 +
        let loc = bytes
325 +
            .split(|byte| *byte == b'\n')
326 +
            .filter(|line| line.iter().any(|byte| !byte.is_ascii_whitespace()))
327 +
            .count();
328 +
        let source = (bytes.len() <= MAX_SOURCE_BYTES)
329 +
            .then(|| String::from_utf8(bytes).ok())
330 +
            .flatten()
331 +
            .map(|text| HighlightSource::new(text, 1));
332 +
333 +
        Self { loc, source }
334 +
    }
335 +
336 +
    /// Reads a bounded source from one safe worktree path.
337 +
    ///
338 +
    /// `root` must be canonical so containment checks use one path form.
339 +
    fn read_worktree(root: &Path, path: &Path, mode: FileMode) -> Option<Self> {
340 +
        if path.as_os_str().is_empty()
341 +
            || !path
342 +
                .components()
343 +
                .all(|component| matches!(component, Component::Normal(_)))
344 +
        {
345 +
            return None;
346 +
        }
347 +
        let full_path = root.join(path);
348 +
        let bytes = if mode == FileMode::Link {
349 +
            let parent = full_path.parent()?.canonicalize().ok()?;
350 +
            if !parent.starts_with(root)
351 +
                || !std::fs::symlink_metadata(&full_path)
352 +
                    .ok()?
353 +
                    .file_type()
354 +
                    .is_symlink()
355 +
            {
356 +
                return None;
357 +
            }
358 +
            std::fs::read_link(full_path)
359 +
                .ok()?
360 +
                .into_os_string()
361 +
                .into_encoded_bytes()
362 +
        } else {
363 +
            if !std::fs::symlink_metadata(&full_path)
364 +
                .ok()?
365 +
                .file_type()
366 +
                .is_file()
367 +
            {
368 +
                return None;
369 +
            }
370 +
            let path = full_path.canonicalize().ok()?;
371 +
            if !path.starts_with(root) {
372 +
                return None;
373 +
            }
374 +
            let mut file = std::fs::File::open(path).ok()?;
375 +
            if file.metadata().ok()?.len() > MAX_SOURCE_BYTES as u64 {
376 +
                return None;
377 +
            }
378 +
            let mut bytes = Vec::new();
379 +
            file.by_ref()
380 +
                .take(MAX_SOURCE_BYTES as u64 + 1)
381 +
                .read_to_end(&mut bytes)
382 +
                .ok()?;
383 +
            if bytes.len() > MAX_SOURCE_BYTES {
384 +
                return None;
385 +
            }
386 +
            bytes
387 +
        };
388 +
389 +
        Some(Self::read(bytes))
390 +
    }
391 +
}
392 +
280 393
/// Stable metadata shown in a file header.
281 394
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
282 395
struct FileSummary {
283 396
    /// Nonblank displayed-side lines, upgraded from the full blob when available.
284 397
    loc: Option<usize>,
568 681
            options,
569 682
            state,
570 683
            highlights: BTreeMap::new(),
571 684
            pending_highlights: BTreeSet::new(),
572 685
            hunk_highlight_sources: BTreeMap::new(),
686 +
            blob_sources: BTreeMap::new(),
687 +
            worktree_sources: BTreeMap::new(),
688 +
            source_bytes: 0,
573 689
            word_diffs: BTreeMap::new(),
574 690
            preamble,
575 691
            file_tree,
576 692
            file_tree_visibility: FileTreeVisibility::default(),
577 693
            index: RowIndex::default(),
614 730
    /// Returns the viewed document.
615 731
    pub const fn document(&self) -> &DiffDocument {
616 732
        &self.document
617 733
    }
618 734
619 -
    /// Loads full-file LOC metadata from the displayed-side blob of each text file.
620 -
    pub fn load_file_locs<E>(
735 +
    /// Loads full-file LOC metadata and highlight context from each text file's blobs.
736 +
    ///
737 +
    /// Both diff sides are read so deleted rows highlight against the old blob
738 +
    /// and added rows against the new one. Blobs are read once per object id and
739 +
    /// shared between files that reference them.
740 +
    pub fn load_file_sources<E>(
621 741
        &mut self,
622 742
        mut read_blob: impl FnMut(Oid) -> Result<Vec<u8>, E>,
623 743
    ) -> Result<(), E> {
624 -
        let mut locs = BTreeMap::new();
744 +
        let mut blobs: BTreeMap<Oid, usize> = BTreeMap::new();
745 +
625 746
        for file in &self.document.files {
626 747
            if file.header.kind == FileKind::Binary {
627 748
                continue;
628 749
            }
750 +
            for oid in [file.header.old_oid, file.header.new_oid]
751 +
                .into_iter()
752 +
                .flatten()
753 +
            {
754 +
                if let Entry::Vacant(entry) = blobs.entry(oid) {
755 +
                    let blob = LoadedBlob::read(read_blob(oid)?);
756 +
                    entry.insert(blob.loc);
757 +
                    if let Some(source) = blob.source.filter(|source| {
758 +
                        self.source_bytes.saturating_add(source.retained_bytes())
759 +
                            <= MAX_TOTAL_SOURCE_BYTES
760 +
                    }) {
761 +
                        self.source_bytes += source.retained_bytes();
762 +
                        self.blob_sources.insert(oid, source);
763 +
                    }
764 +
                }
765 +
            }
766 +
629 767
            let oid = if file.header.kind == FileKind::Deleted {
630 768
                file.header.old_oid
631 769
            } else {
632 770
                file.header.new_oid.or(file.header.old_oid)
633 771
            };
634 -
            let Some(oid) = oid else {
772 +
            let Some(loc) = oid.and_then(|oid| blobs.get(&oid)).copied() else {
635 773
                continue;
636 774
            };
637 -
            let loc = if let Some(loc) = locs.get(&oid) {
638 -
                *loc
639 -
            } else {
640 -
                let bytes = read_blob(oid)?;
641 -
                let loc = bytes
642 -
                    .split(|byte| *byte == b'\n')
643 -
                    .filter(|line| line.iter().any(|byte| !byte.is_ascii_whitespace()))
644 -
                    .count();
645 -
                locs.insert(oid, loc);
646 -
                loc
647 -
            };
648 775
            if let Some(summary) = self.summaries.get_mut(&file.id) {
649 776
                summary.loc = Some(loc);
650 777
            }
651 778
        }
652 779
        Ok(())
653 780
    }
654 781
782 +
    /// Loads new-side highlight context from the working tree.
783 +
    ///
784 +
    /// Working-tree diffs have no new-side object id, so the post-image only
785 +
    /// exists on disk. Unreadable files are skipped: highlighting falls back to
786 +
    /// the hunk-only source for those.
787 +
    pub fn load_worktree_sources(&mut self, root: &Path) {
788 +
        let Ok(root) = root.canonicalize() else {
789 +
            return;
790 +
        };
791 +
        for file in &self.document.files {
792 +
            if file.header.kind == FileKind::Binary
793 +
                || file.header.kind == FileKind::Deleted
794 +
                || file.header.new_oid.is_some()
795 +
            {
796 +
                continue;
797 +
            }
798 +
            let Some(path) = file.header.new_path.as_ref() else {
799 +
                continue;
800 +
            };
801 +
            let mode = file.header.new_mode.unwrap_or(FileMode::Blob);
802 +
            let Some(blob) = LoadedBlob::read_worktree(&root, path, mode) else {
803 +
                continue;
804 +
            };
805 +
            if let Some(source) = blob.source.filter(|source| {
806 +
                self.source_bytes.saturating_add(source.retained_bytes()) <= MAX_TOTAL_SOURCE_BYTES
807 +
            }) {
808 +
                self.source_bytes += source.retained_bytes();
809 +
                self.worktree_sources.insert(path.clone(), source);
810 +
            }
811 +
            if let Some(summary) = self.summaries.get_mut(&file.id) {
812 +
                summary.loc = Some(blob.loc);
813 +
            }
814 +
        }
815 +
    }
816 +
655 817
    /// Returns the viewer options.
656 818
    pub const fn options(&self) -> &DiffOptions {
657 819
        &self.options
658 820
    }
659 821
684 846
                *existing = replacement;
685 847
            }
686 848
        }
687 849
        self.pending_highlights.clear();
688 850
        self.hunk_highlight_sources.clear();
851 +
        // Loaded sources are keyed by blob, not by file, so they stay valid
852 +
        // across replacement. A file that now points at a blob never loaded
853 +
        // simply misses the lookup and falls back to its hunk source.
689 854
        self.word_diffs.clear();
690 855
        self.rebuild_index();
691 856
    }
692 857
693 858
    /// Replaces file diffs while keeping a visible focused hunk on its screen row.
1255 1420
        self.hunk_highlight_sources.insert(key, source.clone());
1256 1421
        source
1257 1422
    }
1258 1423
1259 1424
    /// Builds source text for one hunk side.
1425 +
    ///
1426 +
    /// The whole-file blob is preferred so the tokenizer reaches the hunk with
1427 +
    /// the parser state its enclosing lines produce. Requests sharing a blob
1428 +
    /// also share one tokenizer cache downstream, so the prefix is walked once
1429 +
    /// per file rather than once per hunk.
1260 1430
    fn build_highlight_source(&self, meta: &DiffLineMeta) -> HighlightSource {
1261 1431
        let Some(file) = self.document.files.iter().find(|file| file.id == meta.file) else {
1262 1432
            return meta.single_row_source();
1263 1433
        };
1264 1434
        let Some(hunk) = file.hunks.iter().find(|hunk| hunk.id == meta.hunk) else {
1265 1435
            return meta.single_row_source();
1266 1436
        };
1437 +
        if let Some(source) = self.file_source(file, meta.side) {
1438 +
            // Rendered rows come from the source, so a source that disagrees
1439 +
            // with the patch would show text the patch never contained. The
1440 +
            // whole hunk is checked because one source is cached for all of it.
1441 +
            if source.matches_hunk(hunk, meta.side) {
1442 +
                return source.clone();
1443 +
            }
1444 +
        }
1267 1445
        hunk.highlight_source(meta.side)
1268 1446
    }
1269 1447
1448 +
    /// Returns whole-file source text for one file side, when it was loaded.
1449 +
    fn file_source(&self, file: &FileDiff, side: DiffSide) -> Option<&HighlightSource> {
1450 +
        let oid = match side {
1451 +
            DiffSide::Old => file.header.old_oid,
1452 +
            DiffSide::New => file.header.new_oid,
1453 +
        };
1454 +
        if let Some(text) = oid.and_then(|oid| self.blob_sources.get(&oid)) {
1455 +
            return Some(text);
1456 +
        }
1457 +
        // Only the new side of a worktree diff lacks a blob; the old side is
1458 +
        // always a committed object.
1459 +
        if side == DiffSide::New && oid.is_none() {
1460 +
            return file
1461 +
                .header
1462 +
                .new_path
1463 +
                .as_ref()
1464 +
                .and_then(|path| self.worktree_sources.get(path));
1465 +
        }
1466 +
        None
1467 +
    }
1468 +
1270 1469
    /// Merges highlighted rows and returns whether a redraw is needed.
1271 1470
    ///
1272 1471
    /// The word-diff overlay is applied here, once, so the cached `Line` is
1273 1472
    /// ready to render with no per-frame merge work. All paths that write to the
1274 1473
    /// cached highlighted rows keep this invariant: cached lines are render-ready
2428 2627
}
2429 2628
2430 2629
#[cfg(test)]
2431 2630
#[allow(clippy::unwrap_used)]
2432 2631
mod tests {
2632 +
    use std::fs;
2433 2633
    use std::path::PathBuf;
2434 2634
    use std::str::FromStr;
2635 +
    use std::time::{SystemTime, UNIX_EPOCH};
2435 2636
2436 2637
    use super::*;
2437 2638
2438 2639
    use crate::Decode;
2439 2640
    use crate::DiffDocument;
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/tests/golden/sticky_header_before_next_file_64x5.txt +0 -0
src/a.rs +0 -0
src/b.rs +0 -0
README.md +0 -0
src/app/a.rs +0 -0
src/lib/b.rs +0 -0
README.md +0 -0
a.rs +0 -0
b.rs +0 -0
assets/css/style.css +0 -0
assets/css/style.css +0 -0
first.rs +0 -0
second.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs\n", +0 -0
a\n\ +0 -0
crates/diff/tests/golden.rs +1 -1
73 73
74 74
#[test]
75 75
fn file_summary_ignores_visible_hunks_and_context() {
76 76
    let mut viewer = two_hunk_viewer();
77 77
    viewer
78 -
        .load_file_locs(|_| Ok::<_, ()>(b"one\ntwo\nthree\nfour\nfive\nsix\n".to_vec()))
78 +
        .load_file_sources(|_| Ok::<_, ()>(b"one\ntwo\nthree\nfour\nfive\nsix\n".to_vec()))
79 79
        .unwrap();
80 80
    let mut replacement = DiffDocument::decode_str(
81 81
        "\
82 82
a.rs +0 -0
a.rs +0 -0
crates/repo/src/git.rs +16 -0
84 84
            git_dir,
85 85
            selector_args: Vec::new(),
86 86
        })
87 87
    }
88 88
89 +
    /// Returns the absolute working-tree root, which diff paths are relative to.
90 +
    pub fn workdir(&self) -> Result<PathBuf, RepoError> {
91 +
        let output = self.command("rev-parse").arg("--show-toplevel").output()?;
92 +
        if !output.status.success() {
93 +
            return Err(RepoError::git(&output));
94 +
        }
95 +
        let text = utf8(output.stdout)?;
96 +
        let root = PathBuf::from(text.trim());
97 +
        if root.as_os_str().is_empty() {
98 +
            return Err(RepoError::Git(
99 +
                "git rev-parse --show-toplevel returned an empty path".to_owned(),
100 +
            ));
101 +
        }
102 +
        Ok(root)
103 +
    }
104 +
89 105
    /// Returns a copy with `selector_args` used for diff context refetches.
90 106
    pub fn with_selector_args(&self, selector_args: impl Into<Vec<OsString>>) -> Self {
91 107
        Self {
92 108
            cwd: self.cwd.clone(),
93 109
            git_dir: self.git_dir.clone(),