navid/veins / commit

4e72d654a1f0

Navid M <navidmomtahen@gmail.com> · 2026-11-28

parents: cfc60fff7721

Browse files at this commit · Download source

opt: fix excessive openat calls for log subcommand
--- /dev/null+++ b/xveins/BENCH_SPECTRE.md@@ -0,0 +1,70 @@+# veins C++ spectre benchmark++Generated 2026-11-28 16:37:48 UTC by `bench/spectre_bench.py`.++### Environment++| Binary | Version | Path |+|:---|:---|:---|+| Baseline | `veins v0.0.1 (veins-store 1)` | `/tmp/opencode/veins-clang-build/vn` |+| Optimized | `veins v0.0.1 (veins-store 1)` | `/home/navid/Desktop/projects/veins2/xveins/build/vn` |++```+host:        Linux x86_64+cpu:         AMD Ryzen 5 5600 6-Core Processor+repeats:     7 (median reported)+inner runs:  5 per command per repeat+repository:  /home/navid/Desktop/projects/spectre2+commits:     2601+pack bytes:  576.3 MiB+```++### Workload++- Read-only commands run against an existing veins repository with a large pack.+- Each cell is the median of the per-repeat command medians.+- Progress output is disabled; both binaries write to a pipe.+- Baseline and optimized outputs are compared byte-for-byte before timing.++### Results++| Metric | Baseline | Optimized | Speedup |+|:---|---:|---:|---:|+| Log [ms] | 146.4 (143.4-152.0) | 24.3 (23.9-25.1) | 6.01x |+| Log -l 1 [ms] | 145.1 (143.5-148.5) | 24.1 (23.8-25.3) | 6.03x |+| Log -l 1000 [ms] | 160.3 (157.7-162.2) | 55.0 (52.7-55.7) | 2.91x |+| Status [ms] | 169.1 (165.2-172.0) | 55.8 (55.0-57.0) | 3.03x |+| Show [ms] | 20.0 (19.5-21.0) | 17.9 (17.7-21.9) | 1.12x |++Each cell is the median with the observed min-max range in parentheses.+A speedup above 1 means the optimized binary was faster.++### Git reference++Timed against `/home/navid/Desktop/projects/spectre` with the same machine and warm cache.++| Command | Median |+|:---|---:|+| `git log -n 20` | 2.8 ms |+| `git log -n 1` | 2.9 ms |+| `git log -n 1000` | 13.4 ms |+| `git log` (all) | 20.4 ms |++### Notes++- Pack reads keep one file descriptor per pack and use positional reads. The baseline reopened and seeked the pack for every record header and body.+- Log no longer computes conflict state for commits outside the requested window, and divergence detection is linear instead of quadratic.+- `git log -n N` truncates by date after reading N commits. `vn log` still walks the full reachable graph so every child is printed before its parents; compare it with full `git log` rather than `git log -n 20`.+- Git import, git materialize, cloning, and push report progress on stderr when stderr is a terminal. Progress output is suppressed for pipes, so the timings above are unaffected by it.+- Git import is dominated by copying the mirror and reading git objects, not by veins pack lookups. It is not part of this optimization; enable it with `--import-repeats N` when you want a rough import timing.+- This is a single-machine run. Treat differences below roughly 5% as noise.++### Reproduce++```sh+cmake --build build -j+python3 bench/spectre_bench.py \+  --baseline /path/to/pre-optimization/vn \+  --repo /path/to/spectre2 \+  --markdown-out BENCH_SPECTRE.md+```--- /dev/null+++ b/xveins/bench/spectre_bench.py@@ -0,0 +1,353 @@+#!/usr/bin/env python3++"""Compare a baseline vn binary with the current build on a real repository.++The default repository is ../spectre2, a 2,600-commit veins repository whose+pack index is large enough to make pack lookups the dominant cost of read-only+commands. A git import benchmark can be enabled with --git-source.+"""++from __future__ import annotations++import argparse+import os+import platform+import shutil+import statistics+import subprocess+import tempfile+import time+from datetime import datetime, timezone+from pathlib import Path+++def cpu_name() -> str:+    try:+        with open("/proc/cpuinfo", encoding="utf-8") as handle:+            for line in handle:+                if line.startswith("model name"):+                    return line.split(":", 1)[1].strip()+    except Exception:+        pass+    return platform.processor() or platform.machine()+++def run(binary: Path, args: list[str], cwd: Path, check: bool = True) -> str:+    env = os.environ.copy()+    env["LC_ALL"] = "C"+    env["NO_COLOR"] = "1"+    env["NO_PROGRESS"] = "1"+    result = subprocess.run(+        [str(binary), *args],+        cwd=str(cwd),+        env=env,+        stdout=subprocess.PIPE,+        stderr=subprocess.PIPE,+        check=check,+        text=True,+    )+    return result.stdout+++def timed(binary: Path, args: list[str], cwd: Path) -> float:+    start = time.perf_counter()+    run(binary, args, cwd)+    return time.perf_counter() - start+++def spread(values: list[float], digits: int) -> str:+    return (+        f"{statistics.median(values):.{digits}f} "+        f"({min(values):.{digits}f}-{max(values):.{digits}f})"+    )+++def command_median(binary: Path, args: list[str], cwd: Path, runs: int) -> float:+    return statistics.median(timed(binary, args, cwd) for _ in range(runs))+++def timed_git(args: list[str], cwd: Path) -> float:+    env = os.environ.copy()+    env["LC_ALL"] = "C"+    env["GIT_PAGER"] = "cat"+    start = time.perf_counter()+    subprocess.run(+        ["git", "-C", str(cwd), *args],+        env=env,+        stdout=subprocess.DEVNULL,+        stderr=subprocess.DEVNULL,+        check=True,+    )+    return time.perf_counter() - start+++def version(binary: Path) -> str:+    try:+        return run(binary, ["version"], Path.cwd()).strip()+    except Exception:+        return "unknown"+++def repo_info(binary: Path, repo: Path) -> tuple[int, int]:+    pack_dir = repo / ".veins" / "store" / "packs"+    pack_bytes = sum(path.stat().st_size for path in pack_dir.glob("*.vpack"))+    try:+        log = run(binary, ["log", "-l", "1000000", "-no-col-titles"], repo)+        commits = max(0, len(log.splitlines()) - 1)+    except Exception:+        commits = 0+    return commits, pack_bytes+++def bench_import(binary: Path, git_source: Path, work: Path, label: str) -> float:+    target = work / label+    if target.exists():+        shutil.rmtree(target)+    start = time.perf_counter()+    run(binary, ["init", str(target), f"-git-import:{git_source}"], work)+    elapsed = time.perf_counter() - start+    shutil.rmtree(target, ignore_errors=True)+    return elapsed+++def main() -> int:+    parser = argparse.ArgumentParser(description=__doc__)+    root = Path(__file__).resolve().parents[1]+    parser.add_argument(+        "--repo",+        type=Path,+        default=root.parent.parent / "spectre2",+        help="veins repository to benchmark (default: ../spectre2 next to the source tree)",+    )+    parser.add_argument("--baseline", type=Path, required=True)+    parser.add_argument("--optimized", type=Path, default=root / "build" / "vn")+    parser.add_argument("--repeats", type=int, default=7)+    parser.add_argument("--inner-runs", type=int, default=3)+    parser.add_argument(+        "--git-source",+        type=Path,+        default=root.parent.parent / "spectre",+        help="git repository used for the optional import benchmark",+    )+    parser.add_argument("--import-repeats", type=int, default=0)+    parser.add_argument("--markdown-out", type=Path, default=root / "BENCH_SPECTRE.md")+    args = parser.parse_args()++    repo = args.repo.resolve()+    baseline = args.baseline.resolve()+    optimized = args.optimized.resolve()+    for label, binary in (("baseline", baseline), ("optimized", optimized)):+        if not binary.exists():+            print(f"missing {label} binary: {binary}")+            return 2+    if not (repo / ".veins").is_dir():+        print(f"not a veins repository: {repo}")+        return 2++    commands = {+        "log": ["log"],+        "log_l1": ["log", "-l", "1"],+        "log_l1000": ["log", "-l", "1000"],+        "status": ["status"],+        "show": ["show"],+    }++    # Make sure both binaries agree before timing anything.+    for name, command in commands.items():+        reference = run(baseline, command, repo)+        candidate = run(optimized, command, repo)+        if reference != candidate:+            print(f"output mismatch for vn {' '.join(command)} in {repo}")+            return 3++    print(f"repository: {repo}")+    commits, pack_bytes = repo_info(optimized, repo)+    print(f"commits: {commits}, packs: {pack_bytes / (1024 * 1024):.1f} MiB")++    rows: dict[str, dict[str, list[float]]] = {+        name: {"baseline": [], "optimized": []} for name in commands+    }+    for repeat in range(args.repeats):+        print(f"repeat {repeat + 1}/{args.repeats}")+        for name, command in commands.items():+            for label, binary in (("baseline", baseline), ("optimized", optimized)):+                value = command_median(binary, command, repo, args.inner_runs)+                rows[name][label].append(value)+            base_ms = statistics.median(rows[name]["baseline"]) * 1000+            opt_ms = statistics.median(rows[name]["optimized"]) * 1000+            print(f"  {name:<10} baseline {base_ms:7.1f}ms  optimized {opt_ms:7.1f}ms")++    import_rows: dict[str, list[float]] = {"baseline": [], "optimized": []}+    if args.import_repeats > 0:+        if not (args.git_source / ".git").is_dir():+            print(f"--git-source is not a git repository: {args.git_source}")+            return 2+        work = Path(tempfile.mkdtemp(prefix="veins-spectre-import-"))+        try:+            for label, binary in (("baseline", baseline), ("optimized", optimized)):+                print(f"import warmup {label}")+                bench_import(binary, args.git_source.resolve(), work, f"warmup-{label}")+            for repeat in range(args.import_repeats):+                print(f"import repeat {repeat + 1}/{args.import_repeats}")+                order = [("baseline", baseline), ("optimized", optimized)]+                if repeat % 2 == 1:+                    order.reverse()+                for label, binary in order:+                    value = bench_import(+                        binary, args.git_source.resolve(), work, f"{label}-{repeat}"+                    )+                    import_rows[label].append(value)+                    print(f"  import {label:<9} {value:.3f}s")+        finally:+            shutil.rmtree(work, ignore_errors=True)++    git_reference: dict[str, float] = {}+    git_source = args.git_source.resolve()+    if (git_source / ".git").is_dir():+        print("git reference")+        for name, git_args in (+            ("log", ["log", "-n", "20"]),+            ("log_l1", ["log", "-n", "1"]),+            ("log_l1000", ["log", "-n", "1000"]),+            ("log_full", ["log"]),+        ):+            values = [timed_git(git_args, git_source) for _ in range(args.inner_runs)]+            git_reference[name] = statistics.median(values)+            print(f"  git {name:<10} {git_reference[name] * 1000:7.1f}ms")++    names = {+        "log": "Log [ms]",+        "log_l1": "Log -l 1 [ms]",+        "log_l1000": "Log -l 1000 [ms]",+        "status": "Status [ms]",+        "show": "Show [ms]",+    }+    lines = [+        "# veins C++ spectre benchmark",+        "",+        f"Generated {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')} by "+        "`bench/spectre_bench.py`.",+        "",+        "### Environment",+        "",+        "| Binary | Version | Path |",+        "|:---|:---|:---|",+        f"| Baseline | `{version(baseline)}` | `{baseline}` |",+        f"| Optimized | `{version(optimized)}` | `{optimized}` |",+        "",+        "```",+        f"host:        {platform.system()} {platform.machine()}",+        f"cpu:         {cpu_name()}",+        f"repeats:     {args.repeats} (median reported)",+        f"inner runs:  {args.inner_runs} per command per repeat",+        f"repository:  {repo}",+        f"commits:     {commits}",+        f"pack bytes:  {pack_bytes / (1024 * 1024):.1f} MiB",+        "```",+        "",+        "### Workload",+        "",+        "- Read-only commands run against an existing veins repository with a large pack.",+        "- Each cell is the median of the per-repeat command medians.",+        "- Progress output is disabled; both binaries write to a pipe.",+        "- Baseline and optimized outputs are compared byte-for-byte before timing.",+    ]+    if args.import_repeats > 0:+        lines.append(+            f"- Git import runs {args.import_repeats}x from `{args.git_source.resolve()}` "+            "into a fresh temporary repository."+        )+    lines.extend(+        [+            "",+            "### Results",+            "",+            "| Metric | Baseline | Optimized | Speedup |",+            "|:---|---:|---:|---:|",+        ]+    )+    for name in commands:+        base_values = [value * 1000 for value in rows[name]["baseline"]]+        opt_values = [value * 1000 for value in rows[name]["optimized"]]+        base_med = statistics.median(base_values)+        opt_med = statistics.median(opt_values)+        ratio = base_med / opt_med if opt_med > 0 else float("inf")+        lines.append(+            f"| {names[name]} | {spread(base_values, 1)} | "+            f"{spread(opt_values, 1)} | {ratio:.2f}x |"+        )+    if import_rows["baseline"]:+        base_values = import_rows["baseline"]+        opt_values = import_rows["optimized"]+        base_med = statistics.median(base_values)+        opt_med = statistics.median(opt_values)+        ratio = base_med / opt_med if opt_med > 0 else float("inf")+        lines.append(+            f"| Git import [s] | {spread(base_values, 3)} | "+            f"{spread(opt_values, 3)} | {ratio:.2f}x |"+        )++    lines.extend(+        [+            "",+            "Each cell is the median with the observed min-max range in parentheses.",+            "A speedup above 1 means the optimized binary was faster.",+        ]+    )++    if git_reference:+        lines.extend(+            [+                "",+                "### Git reference",+                "",+                f"Timed against `{git_source}` with the same machine and warm cache.",+                "",+                "| Command | Median |",+                "|:---|---:|",+                f"| `git log -n 20` | {git_reference['log'] * 1000:.1f} ms |",+                f"| `git log -n 1` | {git_reference['log_l1'] * 1000:.1f} ms |",+                f"| `git log -n 1000` | {git_reference['log_l1000'] * 1000:.1f} ms |",+                f"| `git log` (all) | {git_reference['log_full'] * 1000:.1f} ms |",+            ]+        )++    lines.extend(+        [+            "",+            "### Notes",+            "",+            "- Pack reads keep one file descriptor per pack and use positional reads. "+            "The baseline reopened and seeked the pack for every record header and body.",+            "- Log no longer computes conflict state for commits outside the requested "+            "window, and divergence detection is linear instead of quadratic.",+            "- `git log -n N` truncates by date after reading N commits. `vn log` still "+            "walks the full reachable graph so every child is printed before its parents; "+            "compare it with full `git log` rather than `git log -n 20`.",+            "- Git import, git materialize, cloning, and push report progress on stderr "+            "when stderr is a terminal. Progress output is suppressed for pipes, so the "+            "timings above are unaffected by it.",+            "- Git import is dominated by copying the mirror and reading git objects, not "+            "by veins pack lookups. It is not part of this optimization; enable it with "+            "`--import-repeats N` when you want a rough import timing.",+            "- This is a single-machine run. Treat differences below roughly 5% as noise.",+            "",+            "### Reproduce",+            "",+            "```sh",+            "cmake --build build -j",+            "python3 bench/spectre_bench.py \\",+            "  --baseline /path/to/pre-optimization/vn \\",+            "  --repo /path/to/spectre2 \\",+            "  --markdown-out BENCH_SPECTRE.md",+            "```",+            "",+        ]+    )+    args.markdown_out.write_text("\n".join(lines), encoding="utf-8")+    print(f"wrote {args.markdown_out}")+    return 0+++if __name__ == "__main__":+    raise SystemExit(main())--- a/xveins/src/cli.cpp+++ b/xveins/src/cli.cpp@@ -14,6 +14,7 @@ #include <map> #include <set> #include <sstream>+#include <unordered_map>  namespace vn { @@ -624,13 +625,21 @@     if (conflicts > 0)         std::cout << conflicts << " conflict(s)\n"; -    const std::vector<Id> start{*wc};-    const auto ancestry = collect_commits(store, start);+    std::vector<Id> stack{*wc};+    std::set<Id> seen;     std::size_t conflicted_commits = 0;-    for (const auto& id : ancestry) {+    while (!stack.empty()) {+        const Id id = stack.back();+        stack.pop_back();+        if (!seen.insert(id).second)+            continue;         auto loaded = load_commit(store, id);-        if (loaded && tree_conflicted(store, loaded->commit.root_tree))+        if (!loaded)+            continue;+        if (tree_conflicted(store, loaded->commit.root_tree))             ++conflicted_commits;+        for (const auto& parent : loaded->commit.parents)+            stack.push_back(parent);     }     if (conflicted_commits > 0)         std::cout << conflicted_commits << " conflicted commit(s) in ancestry\n";@@ -742,6 +751,7 @@      struct Rec {         Id id{};+        Id root_tree{};         std::vector<Id> parents;         std::string change;         std::int64_t seconds = 0;@@ -759,12 +769,12 @@             continue;         Rec rec;         rec.id = id;+        rec.root_tree = loaded->commit.root_tree;         rec.parents = loaded->commit.parents;         rec.change = base32_encode(loaded->commit.change_id);         rec.seconds = loaded->commit.committer.seconds;         rec.message = first_line(loaded->commit.message);         rec.author = loaded->commit.author.name;-        rec.conflicted = tree_conflicted(store, loaded->commit.root_tree);         if (wc && std::memcmp(wc->data(), id.data(), ID_LEN) == 0)             rec.has_changes = has_changes(store, *loaded);         recs.push_back(std::move(rec));@@ -794,6 +804,9 @@         }     } +    for (auto& rec : recs)+        rec.conflicted = tree_conflicted(store, rec.root_tree);+     std::vector<std::string> change_ids;     for (const auto& rec : recs)         change_ids.push_back(rec.change);@@ -801,10 +814,12 @@     std::size_t w_change = 6;     std::size_t w_date = 19;     std::size_t w_author = 6;+    std::unordered_map<std::string, std::size_t> change_counts;     for (std::size_t i = 0; i < recs.size(); ++i) {         const auto cid = short_change_id(change_ids, i);         w_change = std::max(w_change, cid.size());         w_author = std::max(w_author, recs[i].author.size());+        ++change_counts[recs[i].change];     }     if (col_titles) {         print_cell("", 1, Color::Default, false);@@ -848,13 +863,7 @@             std::cout << " <" << name << ">";         if (rec.conflicted)             std::cout << " (conflicted)";-        bool divergent = false;-        for (std::size_t j = 0; j < recs.size(); ++j) {-            if (j != i && recs[j].change == rec.change) {-                divergent = true;-                break;-            }-        }+        bool divergent = change_counts[rec.change] > 1;         if (divergent)             std::cout << " (divergent)";         std::cout << "\n";--- a/xveins/src/common.cpp+++ b/xveins/src/common.cpp@@ -727,6 +727,160 @@ void info_prefix() {     print_styled("info", Color::Cyan, false, false);     std::cout << ": ";+}++namespace {++bool progress_enabled() {+    if (const char* value = std::getenv("NO_PROGRESS")) {+        if (value[0] != '\0' && std::strcmp(value, "0") != 0)+            return false;+    }+    if (const char* value = std::getenv("VN_NO_PROGRESS")) {+        if (value[0] != '\0' && std::strcmp(value, "0") != 0)+            return false;+    }+    if (const char* value = std::getenv("VN_PROGRESS")) {+        if (value[0] != '\0' && std::strcmp(value, "0") != 0)+            return true;+    }+    const char* term = std::getenv("TERM");+    if (term != nullptr && std::strcmp(term, "dumb") == 0)+        return false;+    return stderr_is_terminal();+}++std::size_t progress_bar_width() {+    return 24;+}++} // namespace++Progress::Progress(std::string label, std::size_t total)+    : label_(std::move(label)), total_(total), enabled_(progress_enabled()) {}++Progress::~Progress() {+    if (!enabled_ || !drawn_ || finished_)+        return;+    std::cerr << "\r\x1b[2K";+    std::cerr.flush();+}++void Progress::set_total(std::size_t total) {+    std::lock_guard<std::mutex> lock(mutex_);+    total_ = total;+    refresh_locked(true);+}++void Progress::update(std::size_t done, bool force) {+    std::lock_guard<std::mutex> lock(mutex_);+    done_ = done;+    refresh_locked(force);+}++void Progress::advance(std::size_t amount) {+    std::lock_guard<std::mutex> lock(mutex_);+    done_ += amount;+    refresh_locked(false);+}++void Progress::finish() {+    std::lock_guard<std::mutex> lock(mutex_);+    if (!enabled_ || finished_)+        return;+    finished_ = true;+    if (total_ > 0) {+        if (done_ < total_)+            done_ = total_;+        if (!drawn_ || last_done_ != done_ || last_total_ != total_)+            draw_locked();+        std::cerr << "\n";+        std::cerr.flush();+    } else if (drawn_) {+        std::cerr << "\r\x1b[2K";+        std::cerr.flush();+    }+    drawn_ = false;+}++void Progress::clear() {+    std::lock_guard<std::mutex> lock(mutex_);+    if (!enabled_)+        return;+    if (drawn_) {+        std::cerr << "\r\x1b[2K";+        std::cerr.flush();+    }+    drawn_ = false;+    finished_ = true;+}++void Progress::refresh_locked(bool force) {+    if (!enabled_ || finished_)+        return;+    const auto now = std::chrono::steady_clock::now();+    const bool complete = total_ > 0 && done_ >= total_;+    if (!force && !complete && now - last_draw_ < std::chrono::milliseconds(66))+        return;+    last_draw_ = now;+    draw_locked();+    drawn_ = true;+}++void Progress::draw_locked() {+    const bool color = colors_enabled();+    std::ostringstream line;+    if (color)+        line << "\r\x1b[2K\x1b[1m\x1b[36minfo\x1b[0m: ";+    else+        line << "\r\x1b[2Kinfo: ";+    line << label_ << "  ";+    if (total_ > 0) {+        const std::size_t width = progress_bar_width();+        const std::size_t filled = std::min<std::size_t>(+            width,+            static_cast<std::size_t>((static_cast<unsigned long long>(done_) * width) / total_));+        if (filled > 0) {+            if (color)+                line << "\x1b[32m";+            for (std::size_t i = 0; i < filled; ++i)+                line << "\u2588";+        }+        if (filled < width) {+            if (color)+                line << "\x1b[2m";+            for (std::size_t i = filled; i < width; ++i)+                line << "\u2591";+        }+        if (color)+            line << "\x1b[0m";+        const std::size_t percent = std::min<std::size_t>(+            100, static_cast<std::size_t>((static_cast<unsigned long long>(done_) * 100) / total_));+        if (color)+            line << " \x1b[36m";+        else+            line << " ";+        line << percent << "%";+        if (color)+            line << "\x1b[0m\x1b[2m";+        line << " " << done_ << "/" << total_;+        if (color)+            line << "\x1b[0m";+    } else {+        static constexpr char spin[] = "|/-\\";+        const char frame = spin[done_ % 4];+        if (color)+            line << "\x1b[36m" << frame << "\x1b[0m\x1b[2m";+        else+            line << frame;+        line << " " << done_;+        if (color)+            line << "\x1b[0m";+    }+    last_done_ = done_;+    last_total_ = total_;+    std::cerr << line.str();+    std::cerr.flush(); }  // ---------------------------------------------------------------------------@@ -1611,6 +1765,14 @@     return _isatty(_fileno(stdout)) != 0; #else     return ::isatty(STDOUT_FILENO) != 0;+#endif+}++bool stderr_is_terminal() {+#if defined(_WIN32)+    return _isatty(_fileno(stderr)) != 0;+#else+    return ::isatty(STDERR_FILENO) != 0; #endif } --- a/xveins/src/common.h+++ b/xveins/src/common.h@@ -7,6 +7,7 @@ #include <cstring> #include <filesystem> #include <map>+#include <mutex> #include <optional> #include <span> #include <string>@@ -375,6 +376,37 @@ void error_prefix(); void warning_prefix(); void info_prefix();++// A lightweight, throttled progress bar drawn on stderr. It stays silent when+// stderr is not a terminal, so piped output is unchanged.+class Progress {+public:+    explicit Progress(std::string label, std::size_t total = 0);+    Progress(const Progress&) = delete;+    Progress& operator=(const Progress&) = delete;+    ~Progress();++    void set_total(std::size_t total);+    void update(std::size_t done, bool force = false);+    void advance(std::size_t amount = 1);+    void finish();+    void clear();++private:+    void refresh_locked(bool force);+    void draw_locked();++    std::mutex mutex_;+    std::string label_;+    std::size_t total_ = 0;+    std::size_t done_ = 0;+    std::size_t last_done_ = 0;+    std::size_t last_total_ = 0;+    bool enabled_ = false;+    bool drawn_ = false;+    bool finished_ = false;+    std::chrono::steady_clock::time_point last_draw_{};+};  // --------------------------------------------------------------------------- // Filesystem helpers@@ -446,6 +478,7 @@                 const std::optional<fs::path>& message_file = std::nullopt); bool stdin_is_terminal(); bool stdout_is_terminal();+bool stderr_is_terminal(); std::string pager_command(const fs::path& repo_root); bool run_pager(const fs::path& repo_root, std::string_view text); --- a/xveins/src/git.cpp+++ b/xveins/src/git.cpp@@ -173,7 +173,12 @@     auto commit = decode_commit(bytes_of(*body));     if (!commit)         return 1;-    return checkout_materialize_commit(root, store, std::nullopt, commit->root_tree);+    Progress progress("checking out files");+    const int status =+        checkout_materialize_commit(root, store, std::nullopt, commit->root_tree, &progress);+    if (status == 0)+        progress.finish();+    return status; }  std::vector<Id> ordered_commits(Store& store, const std::vector<Id>& roots) {@@ -760,23 +765,28 @@     std::vector<CommitRecord> records;     std::set<Oid, OidLess> seen;     std::vector<Oid> stack(tips.rbegin(), tips.rend());-    while (!stack.empty()) {-        const Oid oid = stack.back();-        stack.pop_back();-        if (commits_map.get(oid) || seen.count(oid))-            continue;-        seen.insert(oid);-        auto object = git::read_object(*repo, oid);-        if (!object)-            continue;-        if (object->kind != git::KIND_COMMIT)-            continue;-        auto parsed = git::parse_commit(Bytes(object->body.data(), object->body.size()));-        if (!parsed)-            continue;-        records.push_back(CommitRecord{oid, std::move(object->body), std::move(*parsed)});-        for (const auto& parent : records.back().parsed.parents)-            stack.push_back(parent);+    {+        Progress progress("reading git history");+        while (!stack.empty()) {+            const Oid oid = stack.back();+            stack.pop_back();+            if (commits_map.get(oid) || seen.count(oid))+                continue;+            seen.insert(oid);+            auto object = git::read_object(*repo, oid);+            if (!object)+                continue;+            if (object->kind != git::KIND_COMMIT)+                continue;+            auto parsed = git::parse_commit(Bytes(object->body.data(), object->body.size()));+            if (!parsed)+                continue;+            records.push_back(CommitRecord{oid, std::move(object->body), std::move(*parsed)});+            for (const auto& parent : records.back().parsed.parents)+                stack.push_back(parent);+            progress.update(seen.size());+        }+        progress.finish();     }      const std::size_t n = records.size();@@ -820,15 +830,23 @@     }      bool build_failed = false;-    for (std::size_t idx : order) {-        auto imported = git::import_tree(writer, *repo, trees_map, blobs_map,-                                         records[idx].parsed.tree, raw_saves, new_trees, new_blobs);-        if (!imported) {-            build_failed = true;-            break;+    {+        Progress progress("importing trees", order.size());+        for (std::size_t idx : order) {+            auto imported =+                git::import_tree(writer, *repo, trees_map, blobs_map, records[idx].parsed.tree,+                                 raw_saves, new_trees, new_blobs);+            if (!imported) {+                build_failed = true;+                break;+            }+            progress.advance();         }+        if (!build_failed)+            progress.finish();     }     if (!build_failed) {+        Progress progress("importing commits", order.size());         for (std::size_t idx : order) {             const auto& record = records[idx];             auto tree = trees_map.get(record.parsed.tree);@@ -865,7 +883,10 @@                                                   Bytes(record.body.data(), record.body.size()));             if (!is_canonical)                 raw_saves.emplace_back(id, record.body);+            progress.advance();         }+        if (!build_failed)+            progress.finish();     }     if (build_failed) {         error_prefix();@@ -1002,44 +1023,51 @@     MaterializeCtx ctx{root, store, tx->writer(), {}, {}, {}, {}, {}, 0, 0, 0, false};     const auto roots = view_roots(*view);     const auto ordered = ordered_commits(store, roots);-    for (const auto& old_id : ordered) {-        auto body = store.read_body(old_id, TYPE_COMMIT);-        if (!body)-            break;-        auto commit = decode_commit(bytes_of(*body));-        if (!commit)-            break;-        auto mapped_root = materialize_tree(ctx, commit->root_tree, 0);-        if (!mapped_root)-            break;-        bool changed = std::memcmp(mapped_root->data(), commit->root_tree.data(), ID_LEN) != 0;-        std::vector<Id> parents;-        parents.reserve(commit->parents.size());-        bool parents_ok = true;-        for (const auto& parent : commit->parents) {-            auto it = ctx.commits.find(parent);-            if (it == ctx.commits.end()) {-                parents_ok = false;+    {+        Progress progress("materializing commits", ordered.size());+        for (const auto& old_id : ordered) {+            auto body = store.read_body(old_id, TYPE_COMMIT);+            if (!body)+                break;+            auto commit = decode_commit(bytes_of(*body));+            if (!commit)+                break;+            auto mapped_root = materialize_tree(ctx, commit->root_tree, 0);+            if (!mapped_root)                 break;+            bool changed = std::memcmp(mapped_root->data(), commit->root_tree.data(), ID_LEN) != 0;+            std::vector<Id> parents;+            parents.reserve(commit->parents.size());+            bool parents_ok = true;+            for (const auto& parent : commit->parents) {+                auto it = ctx.commits.find(parent);+                if (it == ctx.commits.end()) {+                    parents_ok = false;+                    break;+                }+                parents.push_back(it->second);+                if (std::memcmp(it->second.data(), parent.data(), ID_LEN) != 0)+                    changed = true;             }-            parents.push_back(it->second);-            if (std::memcmp(it->second.data(), parent.data(), ID_LEN) != 0)-                changed = true;-        }-        if (!parents_ok)-            break;-        if (!changed) {-            ctx.commits[old_id] = old_id;-            continue;+            if (!parents_ok)+                break;+            if (!changed) {+                ctx.commits[old_id] = old_id;+                progress.advance();+                continue;+            }+            commit->root_tree = *mapped_root;+            commit->parents = std::move(parents);+            const Id new_id = ctx.writer.add(TYPE_COMMIT, encode_commit(*commit));+            ctx.commits[old_id] = new_id;+            ++ctx.new_commits;+            ctx.changed = true;+            if (auto raw = git::load_raw(root, old_id))+                ctx.raw_saves.emplace_back(new_id, std::move(*raw));+            progress.advance();         }-        commit->root_tree = *mapped_root;-        commit->parents = std::move(parents);-        const Id new_id = ctx.writer.add(TYPE_COMMIT, encode_commit(*commit));-        ctx.commits[old_id] = new_id;-        ++ctx.new_commits;-        ctx.changed = true;-        if (auto raw = git::load_raw(root, old_id))-            ctx.raw_saves.emplace_back(new_id, std::move(*raw));+        if (ctx.commits.size() == ordered.size())+            progress.finish();     }     if (ctx.commits.size() != ordered.size()) {         error_prefix();--- a/xveins/src/net_commands.cpp+++ b/xveins/src/net_commands.cpp@@ -12,6 +12,7 @@ #include <charconv> #include <cstddef> #include <cstring>+#include <functional> #include <iostream> #include <optional> #include <set>@@ -287,13 +288,17 @@     return std::move(walker.chunk_out); } -std::vector<Id> objects_for_commits(Store& store, const std::vector<Id>& commits) {+std::vector<Id> objects_for_commits(Store& store, const std::vector<Id>& commits,+                                    const std::function<void(std::size_t)>& progress = {}) {     Walker walker{store, true};+    std::size_t done = 0;     for (const auto& id : commits) {         walker.add_object(id);         auto loaded = load_commit(store, id);         if (loaded)             walker.walk_tree(loaded->commit.root_tree);+        if (progress)+            progress(++done);     }     return std::move(walker.object_out); }@@ -903,7 +908,12 @@             roots.push_back(tag.target);         }         commits = collect_commits(store, roots);-        objects = objects_for_commits(store, commits);+        {+            Progress progress("collecting objects", commits.size());+            objects = objects_for_commits(store, commits,+                                          [&](std::size_t done) { progress.update(done); });+            progress.finish();+        }     }     const std::string repo_name = proto::url_repo_name(*url);     auto client = proto::Client::connect(*url, key, repo_name, pin);@@ -943,7 +953,17 @@         std::cout << "nothing to push, everything is up to date\n";         return 0;     }-    if (!client->push_objects(root, objects)) {+    bool pushed = false;+    if (!objects.empty()) {+        Progress progress("pushing objects", objects.size());+        pushed =+            client->push_objects(root, objects, [&](std::size_t done) { progress.update(done); });+        if (pushed)+            progress.finish();+    } else {+        pushed = client->push_objects(root, objects);+    }+    if (!pushed) {         report_client_error(*client, "push failed");         return 1;     }--- a/xveins/src/protocol.cpp+++ b/xveins/src/protocol.cpp@@ -822,7 +822,8 @@     return true; } -bool Client::push_objects(const fs::path& repo, const std::vector<Id>& ids) {+bool Client::push_objects(const fs::path& repo, const std::vector<Id>& ids,+                          const std::function<void(std::size_t)>& progress) {     const std::uint32_t rid = static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);     if (!wire::write_frame(stream_, wire::PUT_RECORDS, rid, Bytes{})) {         set_error("connection closed while starting push");@@ -832,6 +833,7 @@     blake3_hasher hasher;     blake3_hasher_init(&hasher);     bool good = true;+    std::size_t done = 0;     for (const auto& id : ids) {         const auto loc = store.find(id);         if (!loc) {@@ -852,6 +854,8 @@             good = false;             break;         }+        if (progress)+            progress(++done);     }     std::array<std::uint8_t, 32> digest{};     blake3_hasher_finalize(&hasher, digest.data(), digest.size());--- a/xveins/src/protocol.h+++ b/xveins/src/protocol.h@@ -5,6 +5,7 @@ #include "wire.h"  #include <cstdint>+#include <functional> #include <optional> #include <string> #include <string_view>@@ -133,7 +134,8 @@     bool fetch_skeleton(const fs::path& repo, const std::vector<Id>& wants);     bool get_chunks(const fs::path& repo, const std::vector<Id>& ids);     bool have_query(const std::vector<Id>& ids, std::vector<std::uint8_t>& bits);-    bool push_objects(const fs::path& repo, const std::vector<Id>& ids);+    bool push_objects(const fs::path& repo, const std::vector<Id>& ids,+                      const std::function<void(std::size_t)>& progress = {});     bool update_refs(const std::vector<UpdateRef>& updates);     bool whoami(std::uint8_t& role, std::string& fingerprint); --- a/xveins/src/store.cpp+++ b/xveins/src/store.cpp@@ -4,6 +4,8 @@  #include <algorithm> #include <atomic>+#include <cerrno>+#include <cstdlib> #include <cstring> #include <iostream> #include <limits>@@ -14,6 +16,11 @@  #include <zstd.h> +#if !defined(_WIN32)+#include <fcntl.h>+#include <unistd.h>+#endif+ namespace vn {  namespace {@@ -545,6 +552,86 @@ // Store // --------------------------------------------------------------------------- +#if !defined(_WIN32)+StoreHandle::StoreHandle(StoreHandle&& other) noexcept+    : path(std::move(other.path)), mtime_ns(other.mtime_ns), index(std::move(other.index)),+      pack(std::move(other.pack)), fd(other.fd.load(std::memory_order_relaxed)) {+    other.fd.store(-1, std::memory_order_relaxed);+}++StoreHandle& StoreHandle::operator=(StoreHandle&& other) noexcept {+    if (this == &other)+        return *this;+    const int current = fd.load(std::memory_order_relaxed);+    if (current >= 0)+        ::close(current);+    path = std::move(other.path);+    mtime_ns = other.mtime_ns;+    index = std::move(other.index);+    pack = std::move(other.pack);+    fd.store(other.fd.load(std::memory_order_relaxed), std::memory_order_relaxed);+    other.fd.store(-1, std::memory_order_relaxed);+    return *this;+}++StoreHandle::~StoreHandle() {+    const int current = fd.load(std::memory_order_relaxed);+    if (current >= 0)+        ::close(current);+}+#else+StoreHandle::StoreHandle(StoreHandle&& other) noexcept = default;+StoreHandle& StoreHandle::operator=(StoreHandle&& other) noexcept = default;+StoreHandle::~StoreHandle() = default;+#endif++static int handle_fd(StoreHandle& handle) {+#if !defined(_WIN32)+    const int cached = handle.fd.load(std::memory_order_acquire);+    if (cached >= 0)+        return cached;+    const int opened = ::open(handle.path.c_str(), O_RDONLY | O_CLOEXEC);+    if (opened < 0)+        return -1;+    int expected = -1;+    if (!handle.fd.compare_exchange_strong(expected, opened, std::memory_order_acq_rel,+                                           std::memory_order_acquire)) {+        ::close(opened);+        return expected;+    }+    return opened;+#else+    (void)handle;+    return -1;+#endif+}++static std::optional<std::vector<std::uint8_t>>+read_handle_range(StoreHandle& handle, std::uint64_t offset, std::size_t length) {+#if !defined(_WIN32)+    const int fd = handle_fd(handle);+    if (fd < 0)+        return std::nullopt;+    std::vector<std::uint8_t> data(length);+    std::size_t done = 0;+    while (done < length) {+        const ssize_t n =+            ::pread(fd, data.data() + done, length - done, static_cast<off_t>(offset + done));+        if (n > 0) {+            done += static_cast<std::size_t>(n);+        } else if (n < 0 && errno == EINTR) {+            continue;+        } else {+            break;+        }+    }+    data.resize(done);+    return data;+#else+    return read_file_range(handle.path, offset, length);+#endif+}+ static bool handle_index(StoreHandle& handle) {     if (handle.index)         return true;@@ -611,8 +698,10 @@ }  void Store::preload() {-    for (auto& handle : handles_)+    for (auto& handle : handles_) {         (void)ensure_index(handle);+        (void)handle_fd(handle);+    } }  void Store::refresh(const fs::path& root) {@@ -643,7 +732,7 @@  static std::optional<Loc> read_record_loc(StoreHandle& handle, std::size_t pack_index,                                           std::uint64_t offset, const Id& expected) {-    auto header = read_file_range(handle.path, offset, 96);+    auto header = read_handle_range(handle, offset, 96);     if (!header || header->size() < 34)         return std::nullopt;     Reader r(bytes_of(*header));@@ -695,7 +784,7 @@     if (loc.stored_len > std::numeric_limits<std::size_t>::max())         return fail(ErrorKind::LimitExceeded, loc.data_offset);     auto stored =-        read_file_range(handle.path, loc.data_offset, static_cast<std::size_t>(loc.stored_len));+        read_handle_range(handle, loc.data_offset, static_cast<std::size_t>(loc.stored_len));     if (!stored || static_cast<std::uint64_t>(stored->size()) != loc.stored_len)         return fail(ErrorKind::Io, 0);     if (loc.compression == 0)--- a/xveins/src/store.h+++ b/xveins/src/store.h@@ -2,6 +2,7 @@  #include "object.h" +#include <atomic> #include <functional> #include <map> #include <memory>@@ -113,6 +114,16 @@     std::uint64_t mtime_ns = 0;     std::optional<Index> index;     std::optional<Pack> pack;+#if !defined(_WIN32)+    std::atomic<int> fd{-1};+#endif++    StoreHandle() = default;+    StoreHandle(const StoreHandle&) = delete;+    StoreHandle& operator=(const StoreHandle&) = delete;+    StoreHandle(StoreHandle&& other) noexcept;+    StoreHandle& operator=(StoreHandle&& other) noexcept;+    ~StoreHandle(); };  class Store {--- a/xveins/src/worktree.cpp+++ b/xveins/src/worktree.cpp@@ -595,7 +595,7 @@ }  int materialize_tree(Store& store, const fs::path& root, const std::vector<FlatEntry>& old_entries,-                     const Id& new_root) {+                     const Id& new_root, Progress* progress) {     auto checked_entries = flatten_tree_checked(store, new_root);     if (!checked_entries) {         error_prefix();@@ -665,6 +665,8 @@     }      std::string error_path;+    if (progress && (!files.empty() || !conflicts.empty()))+        progress->set_total(files.size() + conflicts.size());     if (!files.empty()) {         std::size_t workers = available_cpu_count();         if (workers == 0)@@ -687,8 +689,11 @@                     const auto& entry = files[index];                     const FlatEntry* old_entry = find_flat(old_entries, entry.path);                     if (old_entry && old_entry->kind == entry.kind &&-                        std::memcmp(old_entry->target.data(), entry.target.data(), ID_LEN) == 0)+                        std::memcmp(old_entry->target.data(), entry.target.data(), ID_LEN) == 0) {+                        if (progress)+                            progress->advance();                         continue;+                    }                     std::string local_error;                     if (!write_entry(store, root, entry, local_error)) {                         std::lock_guard<std::mutex> lock(error_mutex);@@ -696,6 +701,8 @@                             error_path = std::move(local_error);                         return;                     }+                    if (progress)+                        progress->advance();                 }             });         }@@ -702,6 +709,8 @@         for (auto& thread : threads)             thread.join();         if (failed.load()) {+            if (progress)+                progress->clear();             error_prefix();             std::cout << "checkout failed at: " << error_path << "\n";             return 1;@@ -709,12 +718,18 @@     }     for (const auto& conflict : conflicts) {         if (!materialize_conflict(store, root, conflict.path, conflict.target, error_path)) {+            if (progress)+                progress->clear();             error_prefix();             std::cout << "checkout failed at: " << error_path << "\n";             return 1;         }+        if (progress)+            progress->advance();     } +    if (progress)+        progress->finish();     info_prefix();     std::cout << "checked out " << files.size() << " files\n";     return 0;@@ -877,11 +892,11 @@ // ---------------------------------------------------------------------------  int checkout_materialize_commit(const fs::path& root, Store& store, std::optional<Id> old_root,-                                const Id& new_root) {+                                const Id& new_root, Progress* progress) {     if (old_root && std::memcmp(old_root->data(), new_root.data(), ID_LEN) == 0)         return 0;     const auto old_entries = flatten_or_empty(store, old_root);-    return materialize_tree(store, root, old_entries, new_root);+    return materialize_tree(store, root, old_entries, new_root, progress); }  void clear_stat_cache(const fs::path& root) {--- a/xveins/src/worktree.h+++ b/xveins/src/worktree.h@@ -13,7 +13,7 @@ int checkout_run(const fs::path& root, std::string_view rev); std::optional<Id> create_working_copy_commit(Txn& tx, const Id& parent); int checkout_materialize_commit(const fs::path& root, Store& store, std::optional<Id> old_root,-                                const Id& new_root);+                                const Id& new_root, Progress* progress = nullptr); int checkout_materialize_optional(const fs::path& root, Store& store, std::optional<Id> old_root,                                   std::optional<Id> new_root); void clear_stat_cache(const fs::path& root);