heddle-refs 0.8.0

An AI-native version control system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// SPDX-License-Identifier: Apache-2.0
//! Rebuildable sidecar summary for list-heavy local ref reads.

use std::collections::{BTreeMap, BTreeSet};

use objects::{
    error::{HeddleError, Result},
    object::{ChangeId, MarkerName, ThreadName},
};
use serde::Serialize;

use super::{RefManager, packed_refs::PackedRefs, parse_change_id_text, refs_storage::RefsLock};

const REF_SUMMARY_VERSION: &str = "heddle-ref-summary-v1";

#[derive(Debug, Clone, Serialize)]
pub struct RefSummaryIndexInspection {
    pub present: bool,
    pub valid: bool,
    pub bytes: u64,
    pub threads: usize,
    pub markers: usize,
    pub remotes: usize,
    pub remote_threads: usize,
    pub packed_threads: usize,
    pub packed_markers: usize,
    pub error: Option<String>,
}

impl RefSummaryIndexInspection {
    pub fn absent() -> Self {
        Self {
            present: false,
            valid: false,
            bytes: 0,
            threads: 0,
            markers: 0,
            remotes: 0,
            remote_threads: 0,
            packed_threads: 0,
            packed_markers: 0,
            error: None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RefSummarySource {
    Loose,
    Packed,
    LooseAndPacked,
}

impl RefSummarySource {
    fn as_str(self) -> &'static str {
        match self {
            Self::Loose => "loose",
            Self::Packed => "packed",
            Self::LooseAndPacked => "loose+packed",
        }
    }

    fn parse(value: &str) -> Result<Self> {
        match value {
            "loose" => Ok(Self::Loose),
            "packed" => Ok(Self::Packed),
            "loose+packed" => Ok(Self::LooseAndPacked),
            other => Err(HeddleError::InvalidObject(format!(
                "invalid ref summary source {other}"
            ))),
        }
    }
}

#[derive(Debug, Clone)]
struct RefSummaryEntry {
    name: String,
    change_id: ChangeId,
    source: RefSummarySource,
}

/// A single loose-ref delta carried by a publish plan, used to update the
/// summary index incrementally instead of rescanning the whole refs dir.
///
/// The plan already knows exactly which thread/marker changed and its new
/// change-id, so a publish that touches `k` refs costs `O(k)` index edits +
/// one packed-refs load — not an `O(refs)` full-dir rescan. HEAD is not part of
/// the summary index, so HEAD plans carry no target; remote threads are never
/// produced by `publish_ref_plans`, so they stay untouched in the index.
#[derive(Debug, Clone)]
pub(super) enum SummaryDelta {
    /// Loose thread set to a new change-id (the loose file now exists on disk).
    SetThread { name: String, change_id: ChangeId },
    /// Loose marker set to a new change-id.
    SetMarker { name: String, change_id: ChangeId },
    /// Thread removed from both loose and packed storage (delete plans always
    /// carry a packed removal), so the entry leaves the index entirely.
    DeleteThread { name: String },
    /// Marker removed from both loose and packed storage.
    DeleteMarker { name: String },
}

#[derive(Debug, Clone)]
struct RemoteThreadSummaryEntry {
    name: String,
    change_id: ChangeId,
}

#[derive(Debug, Clone)]
struct RemoteSummaryEntry {
    name: String,
    threads: Vec<RemoteThreadSummaryEntry>,
}

#[derive(Debug, Clone)]
pub(super) struct RefSummaryIndex {
    threads: Vec<RefSummaryEntry>,
    markers: Vec<RefSummaryEntry>,
    remotes: Vec<RemoteSummaryEntry>,
}

impl RefSummaryIndex {
    fn parse(contents: &str) -> Result<Self> {
        let mut lines = contents.lines();
        let header = lines
            .next()
            .ok_or_else(|| HeddleError::InvalidObject("empty ref summary index".to_string()))?;
        if header != REF_SUMMARY_VERSION {
            return Err(HeddleError::InvalidObject(format!(
                "unsupported ref summary version: {header}"
            )));
        }

        let mut threads = Vec::new();
        let mut markers = Vec::new();
        let mut remotes = BTreeMap::<String, Vec<RemoteThreadSummaryEntry>>::new();
        let mut remote_names = BTreeSet::<String>::new();

        for line in lines {
            if line.is_empty() {
                continue;
            }

            let fields: Vec<&str> = line.split('\t').collect();
            match fields.as_slice() {
                ["thread", name, change_id, source] => threads.push(RefSummaryEntry {
                    name: (*name).to_string(),
                    change_id: parse_summary_change_id(change_id)?,
                    source: RefSummarySource::parse(source)?,
                }),
                ["marker", name, change_id, source] => markers.push(RefSummaryEntry {
                    name: (*name).to_string(),
                    change_id: parse_summary_change_id(change_id)?,
                    source: RefSummarySource::parse(source)?,
                }),
                ["remote", remote] => {
                    remote_names.insert((*remote).to_string());
                    remotes.entry((*remote).to_string()).or_default();
                }
                ["remote_thread", remote, name, change_id] => {
                    remote_names.insert((*remote).to_string());
                    remotes.entry((*remote).to_string()).or_default().push(
                        RemoteThreadSummaryEntry {
                            name: (*name).to_string(),
                            change_id: parse_summary_change_id(change_id)?,
                        },
                    );
                }
                _ => {
                    return Err(HeddleError::InvalidObject(format!(
                        "invalid ref summary line: {line}"
                    )));
                }
            }
        }

        let remotes = remote_names
            .into_iter()
            .map(|name| RemoteSummaryEntry {
                threads: remotes.remove(&name).unwrap_or_default(),
                name,
            })
            .collect();

        Ok(Self {
            threads,
            markers,
            remotes,
        })
    }

    fn to_text(&self) -> String {
        let mut out = String::from(REF_SUMMARY_VERSION);
        out.push('\n');

        for entry in &self.threads {
            out.push_str("thread\t");
            out.push_str(&entry.name);
            out.push('\t');
            out.push_str(&entry.change_id.to_string_full());
            out.push('\t');
            out.push_str(entry.source.as_str());
            out.push('\n');
        }

        for entry in &self.markers {
            out.push_str("marker\t");
            out.push_str(&entry.name);
            out.push('\t');
            out.push_str(&entry.change_id.to_string_full());
            out.push('\t');
            out.push_str(entry.source.as_str());
            out.push('\n');
        }

        for remote in &self.remotes {
            out.push_str("remote\t");
            out.push_str(&remote.name);
            out.push('\n');
            for thread in &remote.threads {
                out.push_str("remote_thread\t");
                out.push_str(&remote.name);
                out.push('\t');
                out.push_str(&thread.name);
                out.push('\t');
                out.push_str(&thread.change_id.to_string_full());
                out.push('\n');
            }
        }

        out
    }

    fn inspection(&self, bytes: u64) -> RefSummaryIndexInspection {
        RefSummaryIndexInspection {
            present: true,
            valid: true,
            bytes,
            threads: self.threads.len(),
            markers: self.markers.len(),
            remotes: self.remotes.len(),
            remote_threads: self.remotes.iter().map(|remote| remote.threads.len()).sum(),
            packed_threads: self
                .threads
                .iter()
                .filter(|entry| entry.source != RefSummarySource::Loose)
                .count(),
            packed_markers: self
                .markers
                .iter()
                .filter(|entry| entry.source != RefSummarySource::Loose)
                .count(),
            error: None,
        }
    }

    /// Apply one loose-ref delta in place, recomputing the entry's `source`
    /// from the supplied packed-refs view so a loose set over a packed ref is
    /// recorded as `LooseAndPacked` (matching the from-storage rebuild).
    ///
    /// Entries stay sorted by name: set inserts at the sorted position (or
    /// updates in place), delete removes. Remotes are never touched here.
    fn apply_delta(&mut self, delta: &SummaryDelta, packed: &PackedRefs) {
        match delta {
            SummaryDelta::SetThread { name, change_id } => {
                let source = if packed.get_thread(name).is_some() {
                    RefSummarySource::LooseAndPacked
                } else {
                    RefSummarySource::Loose
                };
                upsert_entry(&mut self.threads, name, *change_id, source);
            }
            SummaryDelta::SetMarker { name, change_id } => {
                let source = if packed.get_marker(name).is_some() {
                    RefSummarySource::LooseAndPacked
                } else {
                    RefSummarySource::Loose
                };
                upsert_entry(&mut self.markers, name, *change_id, source);
            }
            SummaryDelta::DeleteThread { name } => {
                self.threads.retain(|entry| entry.name != *name);
            }
            SummaryDelta::DeleteMarker { name } => {
                self.markers.retain(|entry| entry.name != *name);
            }
        }
    }

    pub(super) fn thread_names(&self) -> Vec<ThreadName> {
        self.threads
            .iter()
            .map(|entry| ThreadName::new(&entry.name))
            .collect()
    }

    pub(super) fn marker_names(&self) -> Vec<MarkerName> {
        self.markers
            .iter()
            .map(|entry| MarkerName::new(&entry.name))
            .collect()
    }

    pub(super) fn remote_names(&self) -> Vec<String> {
        self.remotes
            .iter()
            .map(|remote| remote.name.clone())
            .collect()
    }

    pub(super) fn remote_thread_names(&self, remote: &str) -> Vec<ThreadName> {
        self.remotes
            .iter()
            .find(|entry| entry.name == remote)
            .map(|entry| {
                entry
                    .threads
                    .iter()
                    .map(|thread| ThreadName::new(&thread.name))
                    .collect()
            })
            .unwrap_or_default()
    }
}

impl RefManager {
    pub fn inspect_ref_summary_index(&self) -> Result<RefSummaryIndexInspection> {
        let path = self.ref_summary_index_path();
        if !path.exists() {
            return Ok(RefSummaryIndexInspection::absent());
        }

        let bytes = file_len_or_zero(&path);
        match self.read_string(&path) {
            Ok(contents) => match RefSummaryIndex::parse(&contents) {
                Ok(summary) => Ok(summary.inspection(bytes)),
                Err(error) => Ok(RefSummaryIndexInspection {
                    present: true,
                    valid: false,
                    bytes,
                    threads: 0,
                    markers: 0,
                    remotes: 0,
                    remote_threads: 0,
                    packed_threads: 0,
                    packed_markers: 0,
                    error: Some(error.to_string()),
                }),
            },
            Err(error) => Ok(RefSummaryIndexInspection {
                present: true,
                valid: false,
                bytes,
                threads: 0,
                markers: 0,
                remotes: 0,
                remote_threads: 0,
                packed_threads: 0,
                packed_markers: 0,
                error: Some(error.to_string()),
            }),
        }
    }

    pub fn rebuild_ref_summary_index(&self) -> Result<RefSummaryIndexInspection> {
        let lock = self.lock_refs()?;
        self.rebuild_ref_summary_index_with_lock(&lock)
    }

    pub(super) fn rebuild_ref_summary_index_with_lock(
        &self,
        _lock: &RefsLock,
    ) -> Result<RefSummaryIndexInspection> {
        let summary = self.build_ref_summary_index_from_storage()?;
        let path = self.ref_summary_index_path();
        self.write_string(&path, &summary.to_text())?;
        Ok(summary.inspection(file_len_or_zero(&path)))
    }

    pub(super) fn invalidate_ref_summary_index(&self) {
        let _ = std::fs::remove_file(self.ref_summary_index_path());
    }

    /// Incrementally fold a publish's loose-ref deltas into the on-disk summary
    /// index instead of rescanning the whole refs dir (the `O(refs²)` cost that
    /// made `heddle adopt` quadratic — the index was rebuilt from a full
    /// `read_dir` + per-ref `read_change_id_at` on *every* publish over a
    /// directory growing to `N` refs).
    ///
    /// When a current, valid index exists we apply each delta (`O(deltas)` edits
    /// plus one packed-refs load) and rewrite. When the index is absent or corrupt
    /// (or `deltas` is empty, a HEAD-only publish) we fall back to a full
    /// from-storage rebuild so the sidecar is never left half-built. The result
    /// is byte-identical to a full rebuild after the same sequence of writes.
    pub(super) fn update_ref_summary_index_with_deltas(
        &self,
        _lock: &RefsLock,
        deltas: &[SummaryDelta],
    ) -> Result<()> {
        let mut summary = match self.read_ref_summary_index() {
            Ok(Some(summary)) => summary,
            // Absent or unreadable/corrupt: fall back to a clean full rebuild.
            Ok(None) | Err(_) => {
                return self.rebuild_ref_summary_index_with_lock(_lock).map(|_| ());
            }
        };

        if deltas.is_empty() {
            return Ok(());
        }

        let packed = PackedRefs::load(&self.packed_refs_path())?;
        for delta in deltas {
            summary.apply_delta(delta, &packed);
        }

        let path = self.ref_summary_index_path();
        self.write_string(&path, &summary.to_text())
    }

    pub(super) fn list_threads_from_storage(&self) -> Result<Vec<ThreadName>> {
        let loose = self.scan_loose_threads()?;
        let packed = PackedRefs::load(&self.packed_refs_path())?;
        let mut all: Vec<ThreadName> = loose.keys().map(|k| ThreadName::new(k.as_str())).collect();
        for name in packed.list_threads() {
            if !loose.contains_key(&name) {
                all.push(ThreadName::new(name));
            }
        }
        all.sort();
        Ok(all)
    }

    pub(super) fn list_markers_from_storage(&self) -> Result<Vec<MarkerName>> {
        let loose = self.scan_loose_markers()?;
        let packed = PackedRefs::load(&self.packed_refs_path())?;
        let mut all: Vec<MarkerName> = loose.keys().map(|k| MarkerName::new(k.as_str())).collect();
        for name in packed.list_markers() {
            if !loose.contains_key(&name) {
                all.push(MarkerName::new(name));
            }
        }
        all.sort();
        Ok(all)
    }

    pub(super) fn list_remotes_from_storage(&self) -> Result<Vec<String>> {
        let remotes_dir = self.remotes_dir();
        if !remotes_dir.exists() {
            return Ok(Vec::new());
        }
        let mut remotes = Vec::new();
        for entry in std::fs::read_dir(remotes_dir)? {
            let entry = entry?;
            if entry.path().is_dir()
                && let Some(name) = entry.file_name().to_str()
            {
                remotes.push(name.to_string());
            }
        }
        remotes.sort();
        Ok(remotes)
    }

    pub(super) fn list_remote_threads_from_storage(&self, remote: &str) -> Result<Vec<ThreadName>> {
        self.list_refs_recursive(&self.remotes_dir().join(remote), "")
    }

    pub(super) fn try_read_ref_summary_index(&self) -> Option<RefSummaryIndex> {
        self.read_ref_summary_index().ok().flatten()
    }

    fn read_ref_summary_index(&self) -> Result<Option<RefSummaryIndex>> {
        let path = self.ref_summary_index_path();
        if !path.exists() {
            return Ok(None);
        }
        let contents = self.read_string(&path)?;
        Ok(Some(RefSummaryIndex::parse(&contents)?))
    }

    fn build_ref_summary_index_from_storage(&self) -> Result<RefSummaryIndex> {
        let loose_threads = self.scan_loose_threads()?;
        let loose_markers = self.scan_loose_markers()?;
        let packed = PackedRefs::load(&self.packed_refs_path())?;

        let mut threads: Vec<RefSummaryEntry> = loose_threads
            .iter()
            .map(|(name, change_id)| RefSummaryEntry {
                name: name.clone(),
                change_id: *change_id,
                source: if packed.get_thread(name).is_some() {
                    RefSummarySource::LooseAndPacked
                } else {
                    RefSummarySource::Loose
                },
            })
            .collect();
        for name in packed.list_threads() {
            if let Some(change_id) = packed.get_thread(&name)
                && !loose_threads.contains_key(&name)
            {
                threads.push(RefSummaryEntry {
                    name,
                    change_id,
                    source: RefSummarySource::Packed,
                });
            }
        }
        threads.sort_by(|left, right| left.name.cmp(&right.name));

        let mut markers: Vec<RefSummaryEntry> = loose_markers
            .iter()
            .map(|(name, change_id)| RefSummaryEntry {
                name: name.clone(),
                change_id: *change_id,
                source: if packed.get_marker(name).is_some() {
                    RefSummarySource::LooseAndPacked
                } else {
                    RefSummarySource::Loose
                },
            })
            .collect();
        for name in packed.list_markers() {
            if let Some(change_id) = packed.get_marker(&name)
                && !loose_markers.contains_key(&name)
            {
                markers.push(RefSummaryEntry {
                    name,
                    change_id,
                    source: RefSummarySource::Packed,
                });
            }
        }
        markers.sort_by(|left, right| left.name.cmp(&right.name));

        let remotes = self
            .list_remotes_from_storage()?
            .into_iter()
            .map(|name| {
                let threads = self
                    .scan_remote_threads(&name)?
                    .into_iter()
                    .map(|(thread, change_id)| RemoteThreadSummaryEntry {
                        name: thread,
                        change_id,
                    })
                    .collect();
                Ok(RemoteSummaryEntry { name, threads })
            })
            .collect::<Result<Vec<_>>>()?;

        Ok(RefSummaryIndex {
            threads,
            markers,
            remotes,
        })
    }

    fn scan_loose_threads(&self) -> Result<BTreeMap<String, ChangeId>> {
        let mut loose = BTreeMap::new();
        for name in self.list_refs_recursive(&self.threads_dir(), "")? {
            let name_str = name.to_string();
            let Some(decoded) = self
                .decode_flat_thread_entry(&name_str)
                .or_else(|| (!name_str.starts_with("__heddle_flat/")).then_some(name_str))
            else {
                continue;
            };
            let tname = ThreadName::new(&decoded);
            if let Some(change_id) =
                self.read_change_id_at(&self.thread_path(&tname)?, "thread", &decoded)?
            {
                loose.insert(decoded, change_id);
            }
        }
        Ok(loose)
    }

    fn scan_loose_markers(&self) -> Result<BTreeMap<String, ChangeId>> {
        let mut markers = BTreeMap::new();
        for name in self.list_refs_recursive(&self.markers_dir(), "")? {
            let name_str = name.to_string();
            if let Some(change_id) =
                self.read_change_id_at(&self.marker_path(&name_str)?, "marker", &name_str)?
            {
                markers.insert(name_str, change_id);
            }
        }
        Ok(markers)
    }

    fn scan_remote_threads(&self, remote: &str) -> Result<BTreeMap<String, ChangeId>> {
        let mut threads = BTreeMap::new();
        for name in self.list_remote_threads_from_storage(remote)? {
            let name_str = name.to_string();
            if let Some(change_id) = self.read_change_id_at(
                &self.remote_thread_path(remote, &name_str)?,
                "remote thread",
                &format!("{remote}/{name_str}"),
            )? {
                threads.insert(name_str, change_id);
            }
        }
        Ok(threads)
    }
}

/// Insert `name` into the sorted `entries`, or update it in place if present.
/// Keeps `entries` sorted by name (the from-storage rebuild sorts the same way).
fn upsert_entry(
    entries: &mut Vec<RefSummaryEntry>,
    name: &str,
    change_id: ChangeId,
    source: RefSummarySource,
) {
    match entries.binary_search_by(|entry| entry.name.as_str().cmp(name)) {
        Ok(idx) => {
            entries[idx].change_id = change_id;
            entries[idx].source = source;
        }
        Err(idx) => entries.insert(
            idx,
            RefSummaryEntry {
                name: name.to_string(),
                change_id,
                source,
            },
        ),
    }
}

fn file_len_or_zero(path: &std::path::Path) -> u64 {
    std::fs::metadata(path).map(|meta| meta.len()).unwrap_or(0)
}

fn parse_summary_change_id(contents: &str) -> Result<ChangeId> {
    parse_change_id_text(contents).map_err(|error| HeddleError::InvalidObject(error.to_string()))
}