navid/veins / commit

4d72a6278747

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

parents: 0445f6384ea0

Browse files at this commit · Download source

all: various optimizations to c++ implementation
--- /dev/null+++ b/xveins/BENCH.md@@ -0,0 +1,72 @@+# veins C++ optimization benchmark++Generated 2026-11-28 03:22:02 UTC by `bench/optim_bench.py`.++### Environment++| Binary | Version |+|:---|:---|+| Baseline | `veins v0.0.1 (veins-store 1)` |+| Optimized | `veins v0.0.1 (veins-store 1)` |++```+host:        Linux x86_64+cpu:         AMD Ryzen 5 5600 6-Core Processor+repeats:     5 (median reported)+inner runs:  3 per command per repeat+cpu pinning: no+temp dir:    /dev/shm+```++### Workload++- Base snapshot: 2.95 MiB, 42 files.+- 80 edit/commit revisions, 8 checkouts, 5 repeats, median reported.+- Each revision rewrites about 1% of a 120,000-line generated C file and three small module files.+- Commit total covers all revision commits in the run.+- Status and log are measured on the full history after the last commit.+- Checkout walks the newest revisions in descending order.++### Results++| Metric | Baseline | Optimized | Speedup |+|:---|---:|---:|---:|+| Commit total [s] | 1.2404 (1.2176-1.2505) | 1.0918 (1.0794-1.1877) | 1.14x |+| Status [ms] | 49.6 (49.4-50.2) | 14.4 (14.0-15.1) | 3.44x |+| Log [ms] | 50.6 (50.1-51.7) | 13.3 (13.3-14.1) | 3.79x |+| Log -l 5 [ms] | 50.4 (49.9-51.6) | 13.2 (13.0-14.6) | 3.81x |+| Checkout total [s] | 0.3880 (0.3791-0.4098) | 0.1667 (0.1650-0.1754) | 2.33x |+| Checkout mean [ms] | 48.5 (47.4-51.2) | 20.8 (20.6-21.9) | 2.33x |+| Store size [MiB] | 43.01 (43.01-43.31) | 42.92 (42.92-42.92) | 1.00x smaller |++Each cell is the median with the observed min-max range in parentheses.+A speedup above 1 means the optimized binary was faster.++### Repeats++| Repeat | Baseline status [ms] | Optimized status [ms] | Baseline log [ms] | Optimized log [ms] | Baseline checkout [ms] | Optimized checkout [ms] |+|:---|---:|---:|---:|---:|---:|---:|+| 1 | 50.2 | 15.1 | 51.7 | 14.1 | 51.2 | 21.9 |+| 2 | 49.6 | 14.0 | 50.5 | 13.6 | 49.2 | 20.7 |+| 3 | 49.4 | 14.2 | 51.0 | 13.3 | 48.5 | 20.9 |+| 4 | 50.1 | 14.5 | 50.6 | 13.3 | 47.4 | 20.6 |+| 5 | 49.6 | 14.4 | 50.1 | 13.3 | 48.2 | 20.8 |++### Notes++- The optimized build reads only the requested record from a pack instead of decoding the whole pack for every lookup.+- Status and log memoize conflict-tree results and avoid flattening trees that are already equal.+- Checkout reuses a single store, preloads indexes only, and skips rewriting files whose target object did not change.+- Commit keeps the same object format, compression level, and operation-log sequence. Its gains come from fewer pack decodes and from writing the describe and new operations in one chained pack.+- The baseline binary is the C++ build from before these changes. Rebuild each binary from its own source snapshot before reproducing.+- This is a single-machine run. Treat differences below roughly 5% as noise.++### Reproduce++```sh+cmake --build build -j+python3 bench/optim_bench.py \+  --baseline /path/to/pre-optimization/vn \+  --optimized build/vn \+  --markdown-out BENCH.md+```--- /dev/null+++ b/xveins/bench/optim_bench.py@@ -0,0 +1,370 @@+#!/usr/bin/env python3++"""Compare a pre-optimization vn binary with the current C++ build."""++from __future__ import annotations++import argparse+import os+import platform+import random+import re+import shutil+import statistics+import subprocess+import tempfile+import time+from datetime import datetime, timezone+from pathlib import Path++HEX12 = re.compile(r"\b[0-9a-f]{12}\b")+++def command_prefix() -> list[str]:+    try:+        subprocess.run(+            ["taskset", "-c", "0", "true"],+            stdout=subprocess.DEVNULL,+            stderr=subprocess.DEVNULL,+            check=True,+        )+        return ["taskset", "-c", "0"]+    except Exception:+        return []+++PREFIX: list[str] = []+++def run(cmd: list[str], cwd: Path, check: bool = True) -> str:+    env = os.environ.copy()+    env["LC_ALL"] = "C"+    env["NO_COLOR"] = "1"+    result = subprocess.run(+        [str(part) for part in PREFIX + cmd],+        cwd=str(cwd),+        env=env,+        stdout=subprocess.PIPE,+        stderr=subprocess.PIPE,+        check=check,+        text=True,+    )+    return result.stdout+++def timed(cmd: list[str], cwd: Path) -> float:+    start = time.perf_counter()+    run(cmd, cwd)+    return time.perf_counter() - start+++def make_base(root: Path, lines: int, small_files: int) -> None:+    root.mkdir(parents=True)+    (root / "generated.c").write_text(+        "".join(f"int value_{i} = {i * 3 + 7};\n" for i in range(lines)),+        encoding="utf-8",+    )+    for i in range(small_files):+        (root / f"module_{i:03d}.c").write_text(+            f"// module {i}\nint module_{i}(void) {{ return {i}; }}\n", encoding="utf-8"+        )+    (root / "sub").mkdir()+    (root / "sub" / "nested.txt").write_text("nested\n" * 200, encoding="utf-8")+++def mutate(root: Path, revision: int) -> None:+    path = root / "generated.c"+    lines = path.read_text(encoding="utf-8").splitlines(keepends=True)+    rng = random.Random(revision)+    for _ in range(max(1, len(lines) // 100)):+        index = rng.randrange(len(lines))+        lines[index] = f"int changed_{revision}_{index} = {revision};\n"+    path.write_text("".join(lines), encoding="utf-8")+    for i in range(3):+        (root / f"module_{i:03d}.c").write_text(+            f"// module {i}, revision {revision}\n"+            f"int module_{i}(void) {{ return {revision * 1000 + i}; }}\n",+            encoding="utf-8",+        )+++def tree_bytes(root: Path) -> int:+    return sum(path.stat().st_size for path in root.rglob("*") if path.is_file())+++def bench_one(+    binary: Path,+    work: Path,+    label: str,+    revisions: int,+    checkouts: int,+    inner_runs: int,+) -> dict[str, float]:+    repo = work / label+    shutil.copytree(work / "base", repo)+    run([str(binary), "init"], repo)+    (repo / ".veins" / "config").write_text(+        "user.name = Bench\nuser.email = bench@example.com\n", encoding="utf-8"+    )+    mutate(repo, 0)+    run([str(binary), "go", "-m", "warmup"], repo)++    commit_total = 0.0+    for revision in range(1, revisions + 1):+        mutate(repo, revision)+        commit_total += timed([str(binary), "go", "-m", f"revision {revision}"], repo)++    status_runs = []+    log_runs = []+    limited_runs = []+    for _ in range(inner_runs):+        status_runs.append(timed([str(binary), "status"], repo))+        log_runs.append(timed([str(binary), "log", "-no-col-titles"], repo))+        limited_runs.append(timed([str(binary), "log", "-l", "5", "-no-col-titles"], repo))++    log_lines = run([str(binary), "log", "-no-col-titles"], repo).splitlines()+    targets = []+    for line in log_lines:+        parts = line.split()+        if parts and parts[0] == "@":+            if len(parts) < 3:+                continue+            target = parts[2]+        else:+            if len(parts) < 2:+                continue+            target = parts[1]+        if target not in targets:+            targets.append(target)+        if len(targets) >= checkouts:+            break++    checkout_total = 0.0+    for target in targets:+        checkout_total += timed([str(binary), "co", target], repo)++    return {+        "commit_total": commit_total,+        "status": statistics.median(status_runs),+        "log": statistics.median(log_runs),+        "log_limited": statistics.median(limited_runs),+        "checkout_total": checkout_total,+        "checkout_mean": checkout_total / max(1, len(targets)),+        "store_bytes": float(tree_bytes(repo / ".veins")),+    }+++def environment(binary: Path) -> str:+    try:+        return run([str(binary), "version"], Path.cwd()).strip()+    except Exception:+        return "unknown"+++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 spread(values: list[float], digits: int) -> str:+    return (+        f"{statistics.median(values):.{digits}f} "+        f"({min(values):.{digits}f}-{max(values):.{digits}f})"+    )+++def main() -> int:+    parser = argparse.ArgumentParser(description=__doc__)+    root = Path(__file__).resolve().parents[1]+    parser.add_argument("--baseline", type=Path, required=True)+    parser.add_argument("--optimized", type=Path, default=root / "build" / "vn")+    parser.add_argument("--revisions", type=int, default=80)+    parser.add_argument("--checkouts", type=int, default=8)+    parser.add_argument("--repeats", type=int, default=5)+    parser.add_argument("--inner-runs", type=int, default=3)+    parser.add_argument("--large-lines", type=int, default=120000)+    parser.add_argument("--small-files", type=int, default=40)+    parser.add_argument("--no-pin", action="store_true")+    parser.add_argument("--markdown-out", type=Path, default=root / "BENCH.md")+    args = parser.parse_args()++    global PREFIX+    PREFIX = [] if args.no_pin else command_prefix()++    binaries = {+        "baseline": args.baseline.resolve(),+        "optimized": args.optimized.resolve(),+    }+    for label, binary in binaries.items():+        if not binary.exists():+            print(f"missing {label} binary: {binary}")+            return 2++    work = Path(tempfile.mkdtemp(prefix="veins-optim-bench-"))+    try:+        make_base(work / "base", args.large_lines, args.small_files)+        size = tree_bytes(work / "base")+        print(+            f"workload: {size / (1024 * 1024):.2f} MiB, {args.revisions} revisions, "+            f"{args.checkouts} checkouts, {args.repeats} repeats"+        )+        rows: dict[str, list[dict[str, float]]] = {"baseline": [], "optimized": []}+        for repeat in range(args.repeats):+            print(f"repeat {repeat + 1}/{args.repeats}")+            for label, binary in binaries.items():+                row = bench_one(+                    binary,+                    work,+                    f"{label}-{repeat}",+                    args.revisions,+                    args.checkouts,+                    args.inner_runs,+                )+                rows[label].append(row)+                print(+                    f"  {label}: commit {row['commit_total']:.3f}s "+                    f"status {row['status'] * 1000:.1f}ms "+                    f"log {row['log'] * 1000:.1f}ms "+                    f"checkout {row['checkout_mean'] * 1000:.1f}ms"+                )++        def median(label: str, key: str) -> float:+            return statistics.median(row[key] for row in rows[label])++        def values(label: str, key: str) -> list[float]:+            return [row[key] for row in rows[label]]++        metrics = [+            ("Commit total [s]", "commit_total", 1.0, 4),+            ("Status [ms]", "status", 1000.0, 1),+            ("Log [ms]", "log", 1000.0, 1),+            ("Log -l 5 [ms]", "log_limited", 1000.0, 1),+            # store size below is converted with a fractional multiplier+            ("Checkout total [s]", "checkout_total", 1.0, 4),+            ("Checkout mean [ms]", "checkout_mean", 1000.0, 1),+            ("Store size [MiB]", "store_bytes", 1.0 / (1024.0 * 1024.0), 2),+        ]++        lines = [+            "# veins C++ optimization benchmark",+            "",+            f"Generated {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')} by "+            "`bench/optim_bench.py`.",+            "",+            "### Environment",+            "",+            "| Binary | Version |",+            "|:---|:---|",+            f"| Baseline | `{environment(args.baseline)}` |",+            f"| Optimized | `{environment(args.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"cpu pinning: {'yes' if PREFIX else 'no'}",+            f"temp dir:    {os.environ.get('TMPDIR', '(system default)')}",+            "```",+            "",+            "### Workload",+            "",+            f"- Base snapshot: {size / (1024 * 1024):.2f} MiB, "+            f"{args.small_files + 2} files.",+            f"- {args.revisions} edit/commit revisions, {args.checkouts} checkouts, "+            f"{args.repeats} repeats, median reported.",+            "- Each revision rewrites about 1% of a 120,000-line generated C file and "+            "three small module files.",+            "- Commit total covers all revision commits in the run.",+            "- Status and log are measured on the full history after the last commit.",+            "- Checkout walks the newest revisions in descending order.",+            "",+            "### Results",+            "",+            "| Metric | Baseline | Optimized | Speedup |",+            "|:---|---:|---:|---:|",+        ]+        for name, key, scale, digits in metrics:+            base_values = [value * scale for value in values("baseline", key)]+            opt_values = [value * scale for value in values("optimized", key)]+            base_med = statistics.median(base_values)+            opt_med = statistics.median(opt_values)+            if key == "store_bytes":+                ratio = base_med / opt_med+                ratio_text = f"{ratio:.2f}x smaller" if ratio >= 1 else f"{1 / ratio:.2f}x larger"+            else:+                ratio = base_med / opt_med+                ratio_text = f"{ratio:.2f}x"+            lines.append(+                f"| {name} | {spread(base_values, digits)} | "+                f"{spread(opt_values, digits)} | {ratio_text} |"+            )++        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.",+                "",+                "### Repeats",+                "",+                "| Repeat | Baseline status [ms] | Optimized status [ms] | "+                "Baseline log [ms] | Optimized log [ms] | "+                "Baseline checkout [ms] | Optimized checkout [ms] |",+                "|:---|---:|---:|---:|---:|---:|---:|",+            ]+        )+        for index in range(args.repeats):+            base = rows["baseline"][index]+            opt = rows["optimized"][index]+            lines.append(+                f"| {index + 1} | {base['status'] * 1000:.1f} | "+                f"{opt['status'] * 1000:.1f} | {base['log'] * 1000:.1f} | "+                f"{opt['log'] * 1000:.1f} | {base['checkout_mean'] * 1000:.1f} | "+                f"{opt['checkout_mean'] * 1000:.1f} |"+            )++        lines.extend(+            [+                "",+                "### Notes",+                "",+                "- The optimized build reads only the requested record from a pack instead "+                "of decoding the whole pack for every lookup.",+                "- Status and log memoize conflict-tree results and avoid flattening trees "+                "that are already equal.",+                "- Checkout reuses a single store, preloads indexes only, and skips rewriting "+                "files whose target object did not change.",+                "- Commit keeps the same object format, compression level, and operation-log "+                "sequence. Its gains come from fewer pack decodes and from writing the "+                "describe and new operations in one chained pack.",+                "- The baseline binary is the C++ build from before these changes. Rebuild "+                "each binary from its own source snapshot before reproducing.",+                "- This is a single-machine run. Treat differences below roughly 5% as noise.",+                "",+                "### Reproduce",+                "",+                "```sh",+                "cmake --build build -j",+                "python3 bench/optim_bench.py \\",+                "  --baseline /path/to/pre-optimization/vn \\",+                "  --optimized build/vn \\",+                "  --markdown-out BENCH.md",+                "```",+                "",+            ]+        )+        args.markdown_out.write_text("\n".join(lines), encoding="utf-8")+        return 0+    finally:+        shutil.rmtree(work, ignore_errors=True)+++if __name__ == "__main__":+    raise SystemExit(main())--- a/xveins/src/cfg.cpp+++ b/xveins/src/cfg.cpp@@ -67,15 +67,14 @@     std::cout << "  vn cfg <key> <value>        set a value\n";     std::cout << "  vn cfg -unset <key>         remove a key\n";     std::cout << "  vn cfg -global ...          use the user config instead\n";+    std::cout << "\nthe global editor command is read from 'editor' or 'core.editor'\n";+    std::cout << "  vn cfg -global editor \"code --wait\"\n"; }  int cfg_list(const fs::path* root, bool global) {     std::map<std::string, std::string> entries;     if (global) {-        if (auto name = user_config_author_name())-            entries["user.name"] = *name;-        if (auto email = user_config_author_email())-            entries["user.email"] = *email;+        entries = user_config_entries();     } else {         entries = repo_config_entries(*root);     }@@ -87,10 +86,7 @@ int cfg_get(const fs::path* root, bool global, const std::string& key) {     std::optional<std::string> value;     if (global) {-        if (key == "user.name")-            value = user_config_author_name();-        else if (key == "user.email")-            value = user_config_author_email();+        value = user_config_value(key);     } else {         value = repo_config_value(*root, key);     }--- a/xveins/src/cli.cpp+++ b/xveins/src/cli.cpp@@ -79,6 +79,60 @@     return parts; } +std::optional<std::string> edit_commit_message(const fs::path& root, std::string_view initial) {+    const fs::path file = tmp_dir(root) / "commit-message.txt";+    std::string body(initial);+    if (!body.empty() && body.back() != '\n')+        body.push_back('\n');+    body += "\n# Enter a commit message. Lines starting with '#' are ignored.\n";+    if (!write_file(file, bytes_of(body))) {+        error_prefix();+        std::cout << "cannot write message file\n";+        return std::nullopt;+    }+    if (!run_editor(root, {}, file)) {+        (void)remove_file(file);+        error_prefix();+        std::cout << "editor exited with an error\n";+        return std::nullopt;+    }+    auto data = read_file_opt(file);+    (void)remove_file(file);+    if (!data)+        return std::nullopt;+    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    std::vector<std::string> lines;+    std::size_t start = 0;+    while (start <= text.size()) {+        std::size_t end = text.find('\n', start);+        if (end == std::string_view::npos)+            end = text.size();+        std::string line(text.substr(start, end - start));+        const auto first = line.find_first_not_of(" \t\r");+        if (first != std::string::npos && line[first] == '#')+            line.clear();+        else if (first == std::string::npos)+            line.clear();+        else+            line.erase(0, first);+        lines.push_back(std::move(line));+        if (end == text.size())+            break;+        start = end + 1;+    }+    while (!lines.empty() && lines.back().empty())+        lines.pop_back();+    while (!lines.empty() && lines.front().empty())+        lines.erase(lines.begin());+    std::string out;+    for (std::size_t i = 0; i < lines.size(); ++i) {+        if (i != 0)+            out.push_back('\n');+        out += lines[i];+    }+    return out;+}+ void print_cell(std::string_view text, std::size_t width, Color color, bool dim) {     if (dim) {         print_styled(text, color, true, false);@@ -490,10 +544,10 @@     const auto root = open_repo();     if (!root)         return 1;-    const int snap = snapshot_run(*root);+    Store store = Store::open_all(*root);+    const int snap = snapshot_run(*root, store);     if (snap != 0)         return snap;-    Store store = Store::open_all(*root);     auto view = current_view(*root, store);     if (!view) {         error_prefix();@@ -529,7 +583,10 @@                 old_tree = parent_commit->root_tree;         }     }-    const auto changes = compare_trees(store, old_tree, new_tree);+    const bool trees_equal =+        old_tree && new_tree && std::memcmp(old_tree->data(), new_tree->data(), ID_LEN) == 0;+    const auto changes =+        trees_equal ? std::vector<TreeChange>{} : compare_trees(store, old_tree, new_tree);     std::size_t conflicts = 0;     for (const auto& change : changes) {         if (change.old_kind == KIND_MISSING) {@@ -643,10 +700,10 @@     const auto root = open_repo();     if (!root)         return 1;-    const int snap = snapshot_run(*root);+    Store store = Store::open_all(*root);+    const int snap = snapshot_run(*root, store);     if (snap != 0)         return snap;-    Store store = Store::open_all(*root);     auto view = current_view(*root, store);     if (!view) {         error_prefix();@@ -654,14 +711,13 @@         return 1;     }     const auto wc = working_copy_id(*view);-    std::vector<Id> ids;+    std::vector<Id> stack;     if (rev.empty() || rev == "all()") {-        const auto roots = view_roots(*view);-        ids = collect_commits(store, roots);+        stack = view_roots(*view);     } else if (auto one = resolve_revision(store, *view, rev)) {-        const std::vector<Id> start{*one};-        ids = collect_commits(store, start);+        stack.push_back(*one);     }+    std::set<Id> seen(stack.begin(), stack.end());      struct Rec {         Id id{};@@ -673,7 +729,9 @@         bool has_changes = false;     };     std::vector<Rec> recs;-    for (const auto& id : ids) {+    while (!stack.empty()) {+        const Id id = stack.back();+        stack.pop_back();         auto loaded = load_commit(store, id);         if (!loaded)             continue;@@ -687,6 +745,10 @@         if (wc && std::memcmp(wc->data(), id.data(), ID_LEN) == 0)             rec.has_changes = has_changes(store, *loaded);         recs.push_back(std::move(rec));+        for (const auto& parent : loaded->commit.parents) {+            if (seen.insert(parent).second)+                stack.push_back(parent);+        }     }     std::stable_sort(recs.begin(), recs.end(),                      [](const Rec& a, const Rec& b) { return a.seconds > b.seconds; });@@ -1202,7 +1264,7 @@ }  int describe_impl(const fs::path& root, Store& store, const std::vector<std::string>& parts,-                  bool require_changes) {+                  bool require_changes, bool start_new = false) {     const int snap = snapshot_run(root, store);     if (snap != 0)         return snap;@@ -1251,6 +1313,32 @@     }     set_workspace(tx->view(), new_id);     rebuild_heads(tx->view());+    if (start_new) {+        std::vector<ChainedOperation> operations;+        operations.push_back(ChainedOperation{tx->view(), "describe"});+        Commit next;+        next.version = 1;+        next.parents = {new_id};+        next.root_tree = commit.root_tree;+        next.change_id = random_change_id();+        next.author = sig;+        next.committer = sig;+        next.message = "";+        next.renames_state = RENAMES_RECORDED;+        const auto next_encoded = encode_commit(next);+        const Id next_id = tx->add_object(TYPE_COMMIT, next_encoded);+        remove_head(tx->view(), new_id);+        set_workspace(tx->view(), next_id);+        rebuild_heads(tx->view());+        operations.push_back(ChainedOperation{tx->view(), "new"});+        const auto status = tx->finish_chain(std::move(operations));+        if (!status)+            return 1;+        store.refresh(root);+        (void)mark_native(root, new_id);+        (void)mark_native(root, next_id);+        return 0;+    }     const auto status = tx->finish("describe");     if (!status)         return 1;@@ -1274,59 +1362,28 @@     auto parsed = parse_message(args, 2);     if (!parsed)         return 1;+    const auto root = open_repo();+    if (!root)+        return 1;+    if (message_is_blank(*parsed) && stdin_is_terminal()) {+        auto edited = edit_commit_message(*root, join_args(*parsed));+        if (!edited || edited->empty()) {+            error_prefix();+            std::cout << "commit requires a non-empty message (-message)\n";+            return 1;+        }+        *parsed = {*edited};+    }     if (message_is_blank(*parsed)) {         error_prefix();         std::cout << "commit requires a non-empty message (-message)\n";         return 1;     }-    const auto root = open_repo();-    if (!root)-        return 1;     Store store = Store::open_all(*root);-    const int described = describe_impl(*root, store, *parsed, true);+    const int described = describe_impl(*root, store, *parsed, true, true);     if (described == 2)         return 0;-    if (described != 0)-        return described;--    auto tx = Txn::begin(*root, store);-    if (!tx) {-        error_prefix();-        std::cout << "cannot load repository state\n";-        return 1;-    }-    const auto wc = working_copy_id(tx->view());-    if (!wc) {-        error_prefix();-        std::cout << "no working-copy commit\n";-        return 1;-    }-    auto loaded = load_commit(store, *wc);-    if (!loaded) {-        error_prefix();-        std::cout << "cannot read working-copy commit\n";-        return 1;-    }-    const Sig sig = identity_signature(*root);-    Commit commit;-    commit.version = 1;-    commit.parents = {*wc};-    commit.root_tree = loaded->commit.root_tree;-    commit.change_id = random_change_id();-    commit.author = sig;-    commit.committer = sig;-    commit.message = "";-    commit.renames_state = RENAMES_RECORDED;-    const auto encoded = encode_commit(commit);-    const Id new_id = tx->add_object(TYPE_COMMIT, encoded);-    remove_head(tx->view(), *wc);-    set_workspace(tx->view(), new_id);-    rebuild_heads(tx->view());-    const auto status = tx->finish("new");-    if (!status)-        return 1;-    (void)mark_native(*root, new_id);-    return 0;+    return described; }  std::optional<Id> mapped_id(const std::vector<Id>& old_ids, const std::vector<Id>& new_ids,@@ -1527,6 +1584,30 @@     return checkout_run(*root, rev); } +int run_edit(const std::vector<std::string>& args) {+    std::vector<std::string> paths;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            paths.push_back(arg);+        }+    }+    if (paths.empty())+        paths.push_back(".");+    std::optional<fs::path> root = discover_repo(".");+    fs::path config_root = root ? *root : fs::current_path();+    if (!run_editor(config_root, paths))+        return 1;+    return 0;+}+ int run_fsck(const std::vector<std::string>& args) {     std::string path = ".";     bool verbose = false;@@ -1937,6 +2018,7 @@     std::cout << "  remote       manage native remotes\n";     std::cout << "  clone        clone a repository over the native protocol\n";     std::cout << "  fetch        fetch from a native remote\n";+    std::cout << "  gg           fetch the active remote, or clone a URL\n";     std::cout << "  push         push a bookmark to a native remote\n";     std::cout << "  serve        run the native server over stdio or TLS\n";     std::cout << "  key          manage local Ed25519 keys\n";@@ -1960,6 +2042,7 @@     std::cout << "  bmk          manage named branch pointers\n";     std::cout << "  tag          manage named tags\n";     std::cout << "  cfg          read and write configuration\n";+    std::cout << "  edit         open paths in the configured text editor\n";     std::cout << "  rm           untrack paths, keeping files on disk by default\n";     std::cout << "  mv           move a tracked file and record the rename\n";     std::cout << "  ex           add paths or globs to .vnexclude\n";@@ -2145,9 +2228,18 @@     std::cout << "  vn cfg <key>                print a value\n";     std::cout << "  vn cfg <key> <value>        set a value\n";     std::cout << "  vn cfg -unset <key>         remove a key\n";-    std::cout << "  vn cfg -global ...          use the user config instead\n";+    std::cout << "  vn cfg -global ...          use the user config instead\n\n";+    std::cout << "the global editor command is read from 'editor' or 'core.editor'\n";+    std::cout << "  vn cfg -global editor \"code --wait\"\n"; } +void show_edit() {+    std::cout << "usage: vn edit [<path>...]\n\n";+    std::cout << "open paths in the configured text editor\n\n";+    std::cout << "the editor is read from the global 'editor' or 'core.editor' key,\n";+    std::cout << "then $VN_EDITOR, $VISUAL, and $EDITOR. With no paths, opens '.'.\n";+}+ void show_rm() {     std::cout << "usage: vn rm [-delete] <path>...\n\n";     std::cout << "remove paths from the working-copy tree\n\n";@@ -2305,6 +2397,8 @@         show_tag();     else if (cmd == "cfg")         show_cfg();+    else if (cmd == "edit")+        show_edit();     else if (cmd == "rm")         show_rm();     else if (cmd == "mv")@@ -2405,6 +2499,8 @@         return tag_run(args);     if (cmd == "cfg" || cmd == "config")         return cfg_run(args);+    if (cmd == "edit")+        return run_edit(args);     if (cmd == "rm")         return rm_run(args);     if (cmd == "mv")@@ -2440,6 +2536,8 @@         return clone_run(args);     if (cmd == "fetch")         return fetch_run(args);+    if (cmd == "gg")+        return gg_run(args);     if (cmd == "push")         return push_run(args);     if (cmd == "serve")--- a/xveins/src/common.cpp+++ b/xveins/src/common.cpp@@ -830,6 +830,22 @@     ::close(fd);     return data; #endif+}++std::optional<std::vector<std::uint8_t>> read_file_range(const fs::path& p, std::uint64_t offset,+                                                         std::size_t length) {+    std::ifstream in(p, std::ios::binary);+    if (!in)+        return std::nullopt;+    in.seekg(static_cast<std::streamoff>(offset), std::ios::beg);+    if (!in)+        return std::nullopt;+    std::vector<std::uint8_t> data(length);+    if (length > 0) {+        in.read(reinterpret_cast<char*>(data.data()), static_cast<std::streamsize>(length));+        data.resize(static_cast<std::size_t>(in.gcount()));+    }+    return data; }  Result<std::vector<std::uint8_t>> read_file(const fs::path& p) {@@ -1312,7 +1328,16 @@     return std::string(raw); } -static std::optional<std::string> user_config_value(bool want_name) {+static std::string user_config_full_key(std::string_view section, std::string_view key) {+    if (section.empty())+        return std::string(key);+    std::string out(section);+    out.push_back('.');+    out.append(key);+    return out;+}++static std::optional<std::string> read_user_config_value(std::string_view wanted) {     const fs::path path = user_config_path();     if (path.empty())         return std::nullopt;@@ -1320,7 +1345,7 @@     if (!data)         return std::nullopt;     std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-    bool in_user = false;+    std::string section;     std::size_t start = 0;     while (start <= text.size()) {         std::size_t end = text.find('\n', start);@@ -1330,17 +1355,13 @@         if (!line.empty() && line.front() != '#') {             if (line.front() == '[') {                 const std::size_t close = line.find(']');-                if (close != std::string_view::npos) {-                    in_user = trim_view(line.substr(1, close - 1)) == "user";-                }+                if (close != std::string_view::npos)+                    section = trim_copy(line.substr(1, close - 1));             } else {                 const std::size_t eq = line.find('=');                 if (eq != std::string_view::npos) {                     const std::string_view key = trim_view(line.substr(0, eq));-                    const bool matches =-                        (in_user && key == (want_name ? "name" : "email")) ||-                        (!in_user && key == (want_name ? "user.name" : "user.email"));-                    if (matches) {+                    if (user_config_full_key(section, key) == wanted) {                         std::string_view value = line.substr(eq + 1);                         std::string value_copy = strip_comment(value);                         auto decoded = unquote_toml(value_copy);@@ -1355,13 +1376,56 @@         start = end + 1;     }     return std::nullopt;+}++std::optional<std::string> user_config_value(std::string_view key) {+    return read_user_config_value(key);+}++std::map<std::string, std::string> user_config_entries() {+    std::map<std::string, std::string> out;+    const fs::path path = user_config_path();+    if (path.empty())+        return out;+    const auto data = read_file_opt(path);+    if (!data)+        return out;+    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    std::string section;+    std::size_t start = 0;+    while (start <= text.size()) {+        std::size_t end = text.find('\n', start);+        if (end == std::string_view::npos)+            end = text.size();+        const std::string_view line = trim_view(text.substr(start, end - start));+        if (!line.empty() && line.front() != '#') {+            if (line.front() == '[') {+                const std::size_t close = line.find(']');+                if (close != std::string_view::npos)+                    section = trim_copy(line.substr(1, close - 1));+            } else {+                const std::size_t eq = line.find('=');+                if (eq != std::string_view::npos) {+                    const std::string_view key = trim_view(line.substr(0, eq));+                    std::string value_copy = strip_comment(line.substr(eq + 1));+                    auto decoded = unquote_toml(value_copy);+                    if (decoded)+                        out[user_config_full_key(section, key)] = *decoded;+                }+            }+        }+        if (end == text.size())+            break;+        start = end + 1;+    }+    return out; }  std::optional<std::string> user_config_author_name() {-    return user_config_value(true);+    return user_config_value("user.name"); } std::optional<std::string> user_config_author_email() {-    return user_config_value(false);+    return user_config_value("user.email"); }  static std::string toml_quote(std::string_view value) {@@ -1394,9 +1458,7 @@ }  static bool update_user_config(std::string_view key, const std::optional<std::string>& value) {-    const bool want_name = key == "user.name";-    const bool want_email = key == "user.email";-    if (!want_name && !want_email)+    if (key.empty())         return false;     const fs::path path = user_config_path();     if (path.empty())@@ -1419,13 +1481,12 @@      std::vector<std::string> out;     out.reserve(lines.size() + 1);-    bool in_user = false;+    std::string section;     for (const auto& line : lines) {         const std::string_view t = trim_view(line);         if (!t.empty() && t.front() == '[') {             const std::size_t close = t.find(']');-            in_user =-                close != std::string_view::npos && trim_view(t.substr(1, close - 1)) == "user";+            section = close != std::string_view::npos ? trim_copy(t.substr(1, close - 1)) : "";             out.push_back(line);             continue;         }@@ -1435,16 +1496,13 @@             continue;         }         const std::string_view k = trim_view(t.substr(0, eq));-        const bool remove_name =-            (in_user && want_name && k == "name") || (!in_user && want_name && k == "user.name");-        const bool remove_email = (in_user && want_email && k == "email") ||-                                  (!in_user && want_email && k == "user.email");-        if (!remove_name && !remove_email)+        if (user_config_full_key(section, k) != key)             out.push_back(line);     }      if (value) {-        std::string entry = want_name ? "user.name = " : "user.email = ";+        std::string entry(key);+        entry += " = ";         entry += toml_quote(*value);         out.insert(out.begin(), std::move(entry));     } else {@@ -1469,6 +1527,83 @@  bool user_config_remove(std::string_view key) {     return update_user_config(key, std::nullopt);+}++static std::string shell_quote_arg(std::string_view value) {+#if defined(_WIN32)+    std::string out = "\"";+    for (char c : value) {+        if (c == '"')+            out.push_back('\\');+        out.push_back(c);+    }+    out.push_back('"');+    return out;+#else+    std::string out = "'";+    for (char c : value) {+        if (c == '\'')+            out += "'\\''";+        else+            out.push_back(c);+    }+    out.push_back('\'');+    return out;+#endif+}++std::string editor_command(const fs::path& repo_root) {+    if (auto value = user_config_value("editor")) {+        if (!value->empty())+            return *value;+    }+    if (auto value = user_config_value("core.editor")) {+        if (!value->empty())+            return *value;+    }+    if (auto value = repo_config_value(repo_root, "editor")) {+        if (!value->empty())+            return *value;+    }+    if (const char* value = std::getenv("VN_EDITOR")) {+        if (value[0] != '\0')+            return value;+    }+    if (const char* value = std::getenv("VISUAL")) {+        if (value[0] != '\0')+            return value;+    }+    if (const char* value = std::getenv("EDITOR")) {+        if (value[0] != '\0')+            return value;+    }+#if defined(_WIN32)+    return "notepad";+#else+    return "vi";+#endif+}++bool run_editor(const fs::path& repo_root, const std::vector<std::string>& paths,+                const std::optional<fs::path>& message_file) {+    std::string command = editor_command(repo_root);+    for (const auto& path : paths) {+        command.push_back(' ');+        command += shell_quote_arg(path);+    }+    if (message_file) {+        command.push_back(' ');+        command += shell_quote_arg(path_to_bytes(*message_file));+    }+    return std::system(command.c_str()) == 0;+}++bool stdin_is_terminal() {+#if defined(_WIN32)+    return _isatty(_fileno(stdin)) != 0;+#else+    return ::isatty(STDIN_FILENO) != 0;+#endif }  std::optional<std::string> current_bookmark_name(const fs::path& repo_root) {--- a/xveins/src/common.h+++ b/xveins/src/common.h@@ -6,6 +6,7 @@ #include <cstdio> #include <cstring> #include <filesystem>+#include <map> #include <optional> #include <span> #include <string>@@ -385,6 +386,8 @@  Result<std::vector<std::uint8_t>> read_file(const fs::path& p); std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path& p);+std::optional<std::vector<std::uint8_t>> read_file_range(const fs::path& p, std::uint64_t offset,+                                                         std::size_t length); bool write_file(const fs::path& p, Bytes data); bool append_file(const fs::path& p, Bytes data); bool write_atomic(const fs::path& final_path, Bytes data);@@ -433,8 +436,15 @@ Sig identity_signature(const fs::path& repo_root); std::optional<std::string> user_config_author_name(); std::optional<std::string> user_config_author_email();+std::optional<std::string> user_config_value(std::string_view key);+std::map<std::string, std::string> user_config_entries(); bool user_config_set(std::string_view key, std::string_view value); bool user_config_remove(std::string_view key);++std::string editor_command(const fs::path& repo_root);+bool run_editor(const fs::path& repo_root, const std::vector<std::string>& paths,+                const std::optional<fs::path>& message_file = std::nullopt);+bool stdin_is_terminal();  std::optional<std::string> current_bookmark_name(const fs::path& repo_root); bool set_current_bookmark(const fs::path& repo_root, std::string_view name);--- a/xveins/src/net_commands.cpp+++ b/xveins/src/net_commands.cpp@@ -344,6 +344,21 @@         start = i + 1;     }     return out;+}++std::string active_remote(const fs::path& root) {+    for (const char* key : {"remote.current", "remote.default"}) {+        if (auto name = config_value(root, key)) {+            if (!name->empty() && config_value(root, remote_key(*name, "url")))+                return *name;+        }+    }+    if (config_value(root, remote_key("origin", "url")))+        return "origin";+    const auto names = list_remote_names(root);+    if (!names.empty())+        return names.front();+    return "origin"; }  std::string role_text(std::uint8_t role) {@@ -750,6 +765,45 @@     info_prefix();     std::cout << "fetched from " << remote_name << "\n";     return 0;+}++// ---------------------------------------------------------------------------+// gg: fetch the active remote, or clone a URL+// ---------------------------------------------------------------------------++int gg_run(const std::vector<std::string>& args) {+    std::string first;+    for (std::size_t i = 2; i < args.size(); ++i) {+        if (!is_flag(args[i])) {+            first = args[i];+            break;+        }+    }+    const bool is_url = first.find("://") != std::string::npos;+    if (!first.empty() && is_url)+        return clone_run(args);++    auto repo = discover_repo(".");+    if (!repo) {+        if (!first.empty())+            return clone_run(args);+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }++    std::vector<std::string> forwarded = args;+    if (first.empty()) {+        forwarded.push_back(active_remote(*repo));+    } else {+        const auto names = list_remote_names(*repo);+        if (std::find(names.begin(), names.end(), first) == names.end()) {+            error_prefix();+            std::cout << "unknown remote: " << first << "\n";+            return 1;+        }+    }+    return fetch_run(forwarded); }  // ---------------------------------------------------------------------------@@ -1282,6 +1336,14 @@         std::cout << "fetch new history and chunks from a configured native "                      "remote\n\n";         std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";+        return true;+    }+    if (command == "gg") {+        std::cout << "usage: vn gg [<remote>] [path]\n";+        std::cout << "       vn gg <url> [path]\n\n";+        std::cout << "fetch the active remote, or clone when given a URL\n\n";+        std::cout << "the active remote is remote.current, then remote.default,\n";+        std::cout << "then origin, then the first configured remote\n";         return true;     }     if (command == "push") {--- a/xveins/src/net_commands.h+++ b/xveins/src/net_commands.h@@ -9,6 +9,7 @@ int remote_run(const std::vector<std::string>& args); int clone_run(const std::vector<std::string>& args); int fetch_run(const std::vector<std::string>& args);+int gg_run(const std::vector<std::string>& args); int push_run(const std::vector<std::string>& args); int serve_run(const std::vector<std::string>& args); int key_run(const std::vector<std::string>& args);--- a/xveins/src/store.cpp+++ b/xveins/src/store.cpp@@ -6,6 +6,7 @@ #include <atomic> #include <cstring> #include <iostream>+#include <limits> #include <thread> #include <unordered_set> @@ -608,10 +609,8 @@ }  void Store::preload() {-    for (auto& handle : handles_) {+    for (auto& handle : handles_)         (void)ensure_index(handle);-        (void)ensure_pack(handle);-    } }  void Store::refresh(const fs::path& root) {@@ -638,6 +637,38 @@     std::stable_sort(         handles_.begin(), handles_.end(),         [](const StoreHandle& a, const StoreHandle& b) { return a.mtime_ns >= b.mtime_ns; });+}++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);+    if (!header || header->size() < 34)+        return std::nullopt;+    Reader r(bytes_of(*header));+    const auto id = r.id();+    const auto type = r.u8();+    const auto compression = r.u8();+    const auto raw_len = r.varint();+    const auto stored_len = r.varint();+    if (!id || !type || !compression || !raw_len || !stored_len)+        return std::nullopt;+    if (std::memcmp(id->data(), expected.data(), ID_LEN) != 0)+        return std::nullopt;+    if (!type_valid(*type) || *compression > 1 || *raw_len == 0)+        return std::nullopt;+    if (*raw_len > pack_type_limit(*type))+        return std::nullopt;+    if (*compression == 0 && *raw_len != *stored_len)+        return std::nullopt;+    Loc loc;+    loc.pack_index = pack_index;+    loc.kind = *type;+    loc.record_offset = offset;+    loc.data_offset = offset + r.offset();+    loc.raw_len = *raw_len;+    loc.stored_len = *stored_len;+    loc.compression = *compression;+    return loc; }  std::optional<Loc> Store::find(const Id& id) {@@ -649,12 +680,8 @@         if (!pos)             continue;         const std::uint64_t offset = handle.index->offsets[*pos];-        if (!ensure_pack(handle))-            continue;-        const auto rec = handle.pack->find_by_offset(offset);-        if (!rec)-            continue;-        return Loc{i, *rec, handle.pack->records[*rec].type};+        if (auto loc = read_record_loc(handle, i, offset, id))+            return loc;     }     return std::nullopt; }@@ -663,9 +690,20 @@     if (loc.pack_index >= handles_.size())         return fail(ErrorKind::Corrupt, 0);     auto& handle = handles_[loc.pack_index];-    if (!ensure_pack(handle))-        return fail(ErrorKind::Corrupt, 0);-    return handle.pack->get(loc.record_index);+    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));+    if (!stored || static_cast<std::uint64_t>(stored->size()) != loc.stored_len)+        return fail(ErrorKind::Io, 0);+    if (loc.compression == 0)+        return std::move(*stored);+    auto raw_len = static_cast<std::size_t>(loc.raw_len);+    std::vector<std::uint8_t> out(raw_len);+    const std::size_t n = ZSTD_decompress(out.data(), raw_len, stored->data(), stored->size());+    if (ZSTD_isError(n) || n != raw_len)+        return fail(ErrorKind::Corrupt, loc.data_offset);+    return out; }  std::optional<std::vector<std::uint8_t>> Store::read_body(const Id& id, std::uint8_t expected) {@@ -1112,22 +1150,35 @@ }  Status Txn::finish(std::string_view description) {-    sort_view(view_);-    const auto view_body = encode_view(view_);-    const Id view_id = writer_.add(TYPE_VIEW, view_body);-    const std::int64_t now = unix_now_millis();+    std::vector<ChainedOperation> operations;+    operations.push_back(ChainedOperation{view_, std::string(description)});+    return finish_chain(std::move(operations));+} -    Operation op;-    op.parents = parents_;-    op.view = view_id;-    op.start = Reader::TimeMs{start_ms_, 0};-    op.end = Reader::TimeMs{now, 0};-    op.hostname = host_name();-    op.username = user_name();-    op.description = std::string(description);-    op.tags.push_back(KeyValue{"command", std::string(description)});-    const auto op_body = encode_operation(op);-    const Id op_id = writer_.add(TYPE_OPERATION, op_body);+Status Txn::finish_chain(std::vector<ChainedOperation> operations) {+    if (operations.empty())+        return fail_io("no operations to write");+    std::vector<Id> op_parents = parents_;+    Id last_op{};+    for (auto& item : operations) {+        sort_view(item.view);+        const auto view_body = encode_view(item.view);+        const Id view_id = writer_.add(TYPE_VIEW, view_body);+        const std::int64_t now = unix_now_millis();++        Operation op;+        op.parents = op_parents;+        op.view = view_id;+        op.start = Reader::TimeMs{start_ms_, 0};+        op.end = Reader::TimeMs{now, 0};+        op.hostname = host_name();+        op.username = user_name();+        op.description = item.description;+        op.tags.push_back(KeyValue{"command", item.description});+        const auto op_body = encode_operation(op);+        last_op = writer_.add(TYPE_OPERATION, op_body);+        op_parents.assign(1, last_op);+    }      if (writer_.finish(root_) != 0) {         error_prefix();@@ -1134,7 +1185,7 @@         std::cout << "failed to write object pack\n";         return fail_io("failed to write object pack");     }-    if (!write_head(root_, op_id))+    if (!write_head(root_, last_op))         return fail_io("failed to write operation head");     for (const auto& parent : parents_)         (void)delete_head(root_, parent);@@ -1428,6 +1479,10 @@ }  static bool conflicted_into(Store& store, const Id& tree_id, std::size_t depth) {+    auto& cache = store.tree_conflict_cache();+    const auto cached = cache.find(tree_id);+    if (cached != cache.end())+        return cached->second;     if (depth > 4096)         return true;     auto body = store.read_body(tree_id, TYPE_TREE);@@ -1436,13 +1491,19 @@     auto tree = decode_tree(bytes_of(*body));     if (!tree)         return true;+    bool found = false;     for (const auto& entry : tree->entries) {-        if (entry.kind == KIND_CONFLICT)-            return true;-        if (entry.kind == KIND_SUBTREE && conflicted_into(store, entry.target, depth + 1))-            return true;+        if (entry.kind == KIND_CONFLICT) {+            found = true;+            break;+        }+        if (entry.kind == KIND_SUBTREE && conflicted_into(store, entry.target, depth + 1)) {+            found = true;+            break;+        }     }-    return false;+    cache.emplace(tree_id, found);+    return found; }  bool tree_conflicted(Store& store, const Id& tree_id) {--- a/xveins/src/store.h+++ b/xveins/src/store.h@@ -3,6 +3,7 @@ #include "object.h"  #include <functional>+#include <map> #include <memory> #include <optional> #include <set>@@ -100,6 +101,11 @@     std::size_t pack_index = 0;     std::size_t record_index = 0;     std::uint8_t kind = 0;+    std::uint64_t record_offset = 0;+    std::uint64_t data_offset = 0;+    std::uint64_t raw_len = 0;+    std::uint64_t stored_len = 0;+    std::uint8_t compression = 0; };  struct StoreHandle {@@ -137,6 +143,9 @@         return root_;     }     void preload();+    std::map<Id, bool>& tree_conflict_cache() {+        return tree_conflict_cache_;+    }  private:     bool ensure_index(StoreHandle& handle);@@ -143,6 +152,7 @@     bool ensure_pack(StoreHandle& handle);     fs::path root_;     std::vector<StoreHandle> handles_;+    std::map<Id, bool> tree_conflict_cache_; };  // ---------------------------------------------------------------------------@@ -181,6 +191,11 @@     std::uint64_t limit_ = 0;     std::uint64_t raw_bytes_ = 0;     bool quota_hit_ = false;+};++struct ChainedOperation {+    View view;+    std::string description; };  class Txn {@@ -212,6 +227,7 @@     }      Status finish(std::string_view description);+    Status finish_chain(std::vector<ChainedOperation> operations);  private:     Txn() = default;--- a/xveins/src/worktree.cpp+++ b/xveins/src/worktree.cpp@@ -145,8 +145,7 @@         w.id(entry.target);     }     const fs::path final_path = working_copy_dir(root) / "stat-cache";-    const fs::path tmp_path = tmp_dir(root) / "stat-cache.tmp";-    return write_atomic(tmp_path, final_path, w.view());+    return write_file(final_path, w.view()); }  const CacheEntry* cache_lookup(const Cache& cache, std::string_view path) {@@ -685,8 +684,13 @@                     const std::size_t index = next.fetch_add(1);                     if (index >= files.size() || failed.load(std::memory_order_relaxed))                         return;+                    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)+                        continue;                     std::string local_error;-                    if (!write_entry(store, root, files[index], local_error)) {+                    if (!write_entry(store, root, entry, local_error)) {                         std::lock_guard<std::mutex> lock(error_mutex);                         if (!failed.exchange(true))                             error_path = std::move(local_error);@@ -877,10 +881,7 @@     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);-    const int status = materialize_tree(store, root, old_entries, new_root);-    if (status == 0)-        clear_stat_cache(root);-    return status;+    return materialize_tree(store, root, old_entries, new_root); }  void clear_stat_cache(const fs::path& root) {@@ -921,11 +922,11 @@ }  int checkout_run(const fs::path& root, std::string_view rev) {-    const int snap = snapshot_run(root);+    Store store = Store::open_all(root);+    const int snap = snapshot_run(root, store);     if (snap != 0)         return snap; -    Store store = Store::open_all(root);     auto view = current_view(root, store);     if (!view) {         error_prefix();