navid/veins / ea3ea6b96e721105660cd9ea15ce43ea04777600d6e64c04753f3d38768cfea1 / xveins/src/store/store.cpp

store.cpp

← xveins/src/store · 98893 bytes · raw · download

#include "store/store.h"

#include "git/git.h"

#include <algorithm>
#include <atomic>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <limits>
#include <queue>
#include <thread>
#include <unordered_map>
#include <unordered_set>

#include <zstd.h>

#if !defined(_WIN32)
#include <fcntl.h>
#include <unistd.h>
#endif

namespace vn {

namespace {
PromisorFetcher promisor_fetcher;
} // namespace

void set_promisor_fetcher(PromisorFetcher fetcher) {
    promisor_fetcher = std::move(fetcher);
}


fs::path veins_dir(const fs::path& root) {
    return root / ".veins";
}
fs::path packs_dir(const fs::path& root) {
    return veins_dir(root) / "store" / "packs";
}
fs::path tmp_dir(const fs::path& root) {
    return veins_dir(root) / "store" / "tmp";
}
fs::path op_heads_dir(const fs::path& root) {
    return veins_dir(root) / "op-heads";
}
fs::path git_dir(const fs::path& root) {
    return veins_dir(root) / "git";
}
fs::path git_map_dir(const fs::path& root) {
    return veins_dir(root) / "git-map";
}
fs::path working_copy_dir(const fs::path& root) {
    return veins_dir(root) / "working-copy";
}
fs::path resolutions_dir(const fs::path& root) {
    return veins_dir(root) / "resolutions";
}
fs::path config_path(const fs::path& root) {
    return veins_dir(root) / "config";
}
fs::path format_path(const fs::path& root) {
    return veins_dir(root) / "format";
}

static std::uint64_t repo_storage_usage(const fs::path& root) {
    std::uint64_t total = 0;
    for (const auto& name : list_directory(packs_dir(root))) {
        const auto info = stat_path(packs_dir(root) / path_from_bytes(name));
        if (info && info->kind == 1)
            total += info->size;
    }
    return total;
}

std::uint64_t storage_usage(const fs::path& dir) {
    if (!stat_path(dir)) {
        return 0;
    }
    if (stat_path(format_path(dir))) {
        return repo_storage_usage(dir);
    }
    std::uint64_t total = 0;
    for (const auto& name : list_directory(dir)) {
        const fs::path child = dir / path_from_bytes(name);
        const auto info = stat_path(child);
        if (info && info->kind == 2)
            total += repo_storage_usage(child);
    }
    return total;
}

std::optional<fs::path> discover_repo(const fs::path& start) {
    std::error_code ec;
    fs::path current = fs::absolute(start, ec);
    if (ec)
        return std::nullopt;
    current = fs::weakly_canonical(current, ec);
    if (ec)
        return std::nullopt;
    for (;;) {
        if (path_is_file(current / ".veins" / "format"))
            return current;
        const fs::path parent = current.parent_path();
        if (parent == current || parent.empty())
            return std::nullopt;
        current = parent;
    }
}

static bool migrate_dir(const fs::path& from, const fs::path& to) {
    if (path_is_dir(from) && !path_is_dir(to)) {
        std::error_code ec;
        fs::rename(from, to, ec);
        return !ec;
    }
    return true;
}

static bool ensure_layout(const fs::path& root) {
    if (!migrate_dir(veins_dir(root) / "op_heads", op_heads_dir(root)))
        return false;
    if (!migrate_dir(veins_dir(root) / "working_copy", working_copy_dir(root)))
        return false;
    const fs::path dirs[] = {
        veins_dir(root),           veins_dir(root) / "store",
        packs_dir(root),           tmp_dir(root),
        op_heads_dir(root),        git_map_dir(root),
        git_map_dir(root) / "raw", working_copy_dir(root),
        resolutions_dir(root),
    };
    for (const auto& dir : dirs) {
        if (!ensure_directory(dir))
            return false;
    }
    return true;
}

static std::string store_format_text() {
    return "veins-store " + std::to_string(STORE_VERSION);
}

Result<fs::path> init_repo(const fs::path& path) {
    fs::path root = path.lexically_normal();
    if (root.empty())
        root = ".";
    if (!path_is_dir(root)) {
        if (!ensure_directory(root))
            return unexpected(Error{ErrorKind::Io, 4, "init failed"});
    }
    const fs::path format = format_path(root);
    const std::string expected = store_format_text();
    if (path_exists(format)) {
        auto data = read_file(format);
        if (!data)
            return unexpected(Error{ErrorKind::Io, 3, "init failed"});
        if (!equals(bytes_of(*data), bytes_of(expected)))
            return unexpected(Error{ErrorKind::InvalidValue, 2, "init failed"});
    }
    if (!ensure_layout(root))
        return unexpected(Error{ErrorKind::Io, 4, "init failed"});
    if (!path_exists(format)) {
        if (!write_file(format, bytes_of(expected)))
            return unexpected(Error{ErrorKind::Io, 11, "init failed"});
    }
    if (!path_exists(config_path(root))) {
        (void)write_file(config_path(root), Bytes{});
    }
    return root;
}


std::optional<std::size_t> Pack::find_by_offset(std::uint64_t offset) const {
    std::size_t lo = 0;
    std::size_t hi = records.size();
    while (lo < hi) {
        const std::size_t mid = lo + (hi - lo) / 2;
        const std::uint64_t cur = records[mid].record_off;
        if (cur == offset)
            return mid;
        if (cur < offset)
            lo = mid + 1;
        else
            hi = mid;
    }
    return std::nullopt;
}

namespace {

ZSTD_DCtx* thread_decompress_context() {
    thread_local ZSTD_DCtx* ctx = ZSTD_createDCtx();
    return ctx;
}

} // namespace

static Result<std::vector<std::uint8_t>> pack_get(const Pack& pack, std::size_t record_index,
                                                  int depth) {
    if (record_index >= pack.records.size())
        return fail(ErrorKind::Corrupt, 0);
    if (depth > 32)
        return fail(ErrorKind::LimitExceeded, 0);
    const PackRecord& rec = pack.records[record_index];
    const auto raw_len = static_cast<std::size_t>(rec.raw_len);
    if (raw_len == 0)
        return std::vector<std::uint8_t>{};
    const auto off = static_cast<std::size_t>(rec.data_off);
    const auto stored_len = static_cast<std::size_t>(rec.stored_len);
    if (off > pack.data.size() || stored_len > pack.data.size() - off)
        return fail(ErrorKind::Corrupt, off);
    if (rec.compression == 0) {
        return std::vector<std::uint8_t>(pack.data.begin() + static_cast<std::ptrdiff_t>(off),
                                         pack.data.begin() +
                                             static_cast<std::ptrdiff_t>(off + stored_len));
    }
    if (rec.compression == 1) {
        std::vector<std::uint8_t> out(raw_len);
        const std::size_t n =
            ZSTD_decompress(out.data(), raw_len, pack.data.data() + off, stored_len);
        if (ZSTD_isError(n) || n != raw_len)
            return fail(ErrorKind::Corrupt, off);
        return out;
    }
    if (rec.compression != 2)
        return fail(ErrorKind::InvalidValue, off);

    // Delta record: a varint base-record offset followed by a zstd frame whose
    // dictionary is the base record's raw body. Base offsets decrease, and the
    // recursion is capped so a hostile pack cannot exhaust the stack.
    Reader header(Bytes(pack.data.data() + off, stored_len));
    const auto base_off = header.varint();
    if (!base_off || *base_off >= rec.record_off)
        return fail(ErrorKind::Corrupt, off);
    const auto frame = header.raw(header.remaining());
    if (!frame || frame->empty())
        return fail(ErrorKind::Corrupt, off);
    const auto base_index = pack.find_by_offset(*base_off);
    if (!base_index)
        return fail(ErrorKind::Corrupt, off);
    auto base_body = pack_get(pack, *base_index, depth + 1);
    if (!base_body)
        return unexpected(base_body.error());
    std::vector<std::uint8_t> out(raw_len);
    const std::size_t n =
        ZSTD_decompress_usingDict(thread_decompress_context(), out.data(), raw_len, frame->data(),
                                  frame->size(), base_body->data(), base_body->size());
    if (ZSTD_isError(n) || n != raw_len)
        return fail(ErrorKind::Corrupt, off);
    return out;
}

Result<std::vector<std::uint8_t>> Pack::get(std::size_t record_index) const {
    return pack_get(*this, record_index, 0);
}

static std::size_t pack_type_limit(std::uint8_t type) {
    return type == TYPE_CHUNK ? MAX_CHUNK_LEN : MAX_OBJECT_BODY;
}

Result<Pack> decode_pack(std::vector<std::uint8_t> data) {
    constexpr std::size_t header_len = 16;
    constexpr std::size_t record_min = 36;
    if (data.size() < header_len + 32)
        return fail(ErrorKind::UnexpectedEnd, 0);
    if (std::memcmp(data.data(), "VPK1", 4) != 0)
        return fail(ErrorKind::InvalidMagic, 0);
    Reader header(Bytes(data.data(), header_len));
    (void)header.raw(4);
    const auto version = header.u32le();
    if (!version)
        return unexpected(version.error());
    if (*version != 1)
        return fail(ErrorKind::UnsupportedVersion, 4);
    const auto count_u64 = header.u64le();
    if (!count_u64)
        return unexpected(count_u64.error());

    const std::size_t body_end = data.size() - 32;
    const auto digest = blake3_hash(Bytes(data.data(), body_end));
    if (!equals(Bytes(digest.data(), digest.size()), Bytes(data.data() + body_end, 32)))
        return fail(ErrorKind::HashMismatch, body_end);

    if (*count_u64 > body_end / record_min)
        return fail(ErrorKind::LimitExceeded, 8);
    const std::size_t count = static_cast<std::size_t>(*count_u64);

    Reader r(Bytes(data.data(), body_end));
    (void)r.raw(header_len);
    Pack pack;
    pack.records.reserve(count);
    for (std::size_t i = 0; i < count; ++i) {
        PackRecord rec;
        rec.record_off = r.offset();
        const auto id = r.id();
        if (!id)
            return unexpected(id.error());
        rec.id = *id;
        const auto kind = r.u8();
        if (!kind)
            return unexpected(kind.error());
        if (!type_valid(*kind))
            return fail(ErrorKind::InvalidValue, r.offset() - 1);
        rec.type = *kind;
        const auto comp = r.u8();
        if (!comp)
            return unexpected(comp.error());
        if (*comp > 2)
            return fail(ErrorKind::InvalidValue, r.offset() - 1);
        rec.compression = *comp;
        const std::size_t at = r.offset();
        const auto raw_len = r.varint();
        if (!raw_len)
            return unexpected(raw_len.error());
        const auto stored_len = r.varint();
        if (!stored_len)
            return unexpected(stored_len.error());
        if (*raw_len == 0)
            return fail(ErrorKind::InvalidValue, at);
        if (*raw_len > pack_type_limit(rec.type))
            return fail(ErrorKind::LimitExceeded, at);
        if (rec.compression == 0 && *raw_len != *stored_len)
            return fail(ErrorKind::InvalidValue, at);
        if (*stored_len > r.remaining())
            return fail(ErrorKind::UnexpectedEnd, at);
        rec.raw_len = *raw_len;
        rec.stored_len = *stored_len;
        rec.data_off = r.offset();
        if (rec.compression == 2) {
            Reader delta(Bytes(data.data() + rec.data_off, static_cast<std::size_t>(*stored_len)));
            const auto base_off = delta.varint();
            if (!base_off || *base_off >= rec.record_off || delta.remaining() == 0)
                return fail(ErrorKind::InvalidValue, rec.data_off);
        }
        const auto body = r.raw(static_cast<std::size_t>(*stored_len));
        if (!body)
            return unexpected(body.error());
        pack.records.push_back(rec);
    }
    if (r.offset() != body_end)
        return fail(ErrorKind::TrailingBytes, r.offset());
    std::memcpy(pack.trailer.data(), data.data() + body_end, 32);
    pack.data = std::move(data);
    return pack;
}


std::optional<std::size_t> Index::find(const Id& id) const {
    std::size_t lo = 0;
    std::size_t hi = ids.size();
    while (lo < hi) {
        const std::size_t mid = lo + (hi - lo) / 2;
        const int c = std::memcmp(ids[mid].data(), id.data(), ID_LEN);
        if (c == 0)
            return mid;
        if (c < 0)
            lo = mid + 1;
        else
            hi = mid;
    }
    return std::nullopt;
}

Result<Index>
decode_index(std::vector<std::uint8_t> data,
             const std::optional<std::array<std::uint8_t, 32>>& expected_pack_trailer) {
    constexpr std::size_t base = 1032 + 64;
    if (data.size() < base)
        return fail(ErrorKind::UnexpectedEnd, 0);
    if (std::memcmp(data.data(), "VIX1", 4) != 0)
        return fail(ErrorKind::InvalidMagic, 0);
    Reader r(Bytes(data.data(), data.size()));
    (void)r.raw(4);
    const auto version = r.u32le();
    if (!version)
        return unexpected(version.error());
    if (*version != 1)
        return fail(ErrorKind::UnsupportedVersion, 4);
    std::array<std::uint32_t, 256> fanout{};
    std::uint32_t prev = 0;
    for (std::size_t i = 0; i < 256; ++i) {
        const auto v = r.u32le();
        if (!v)
            return unexpected(v.error());
        if (*v < prev)
            return fail(ErrorKind::Unsorted, r.offset() - 4);
        prev = *v;
        fanout[i] = *v;
    }
    const std::size_t body = data.size() - base;
    if (body % 40 != 0)
        return fail(ErrorKind::TrailingBytes, base);
    const std::size_t count = body / 40;
    if (count != fanout[255])
        return fail(ErrorKind::Corrupt, 1032);

    Index index;
    index.ids.resize(count);
    index.offsets.resize(count);
    std::memcpy(index.ids.data(), data.data() + 1032, count * 32);
    std::memcpy(index.offsets.data(), data.data() + 1032 + count * 32, count * 8);
    std::memcpy(index.pack_trailer.data(), data.data() + 1032 + count * 32 + count * 8, 32);
    const std::size_t index_trailer_off = data.size() - 32;
    const auto digest = blake3_hash(Bytes(data.data(), index_trailer_off));
    if (!equals(Bytes(digest.data(), digest.size()), Bytes(data.data() + index_trailer_off, 32)))
        return fail(ErrorKind::HashMismatch, index_trailer_off);
    if (expected_pack_trailer &&
        !equals(Bytes(index.pack_trailer.data(), 32), Bytes(expected_pack_trailer->data(), 32)))
        return fail(ErrorKind::Corrupt, index_trailer_off);

    std::array<std::uint32_t, 256> counts{};
    for (std::size_t i = 0; i < count; ++i) {
        if (i > 0) {
            const int c = std::memcmp(index.ids[i - 1].data(), index.ids[i].data(), ID_LEN);
            if (c == 0)
                return fail(ErrorKind::Duplicate, 1032 + i * 32);
            if (c > 0)
                return fail(ErrorKind::Unsorted, 1032 + i * 32);
        }
        counts[index.ids[i][0]]++;
    }
    std::uint32_t running = 0;
    for (std::size_t i = 0; i < 256; ++i) {
        running += counts[i];
        if (fanout[i] != running)
            return fail(ErrorKind::Corrupt, 8 + i * 4);
    }
    return Result<Index>(std::move(index));
}

static void write_u64le(std::vector<std::uint8_t>& out, std::size_t off, std::uint64_t value) {
    for (int i = 0; i < 8; ++i)
        out[off + static_cast<std::size_t>(i)] =
            static_cast<std::uint8_t>((value >> (i * 8)) & 255u);
}

std::vector<std::uint8_t> encode_index(const std::vector<RecordMeta>& records,
                                       const std::array<std::uint8_t, 32>& trailer) {
    std::array<std::uint32_t, 256> counts{};
    for (const auto& rec : records)
        counts[rec.id[0]]++;
    ByteWriter w(records.size() * 40 + 128);
    w.raw("VIX1");
    w.u32le(1);
    std::uint32_t running = 0;
    for (std::size_t i = 0; i < 256; ++i) {
        running += counts[i];
        w.u32le(running);
    }
    for (const auto& rec : records)
        w.id(rec.id);
    for (const auto& rec : records)
        w.u64le(rec.offset);
    w.raw(Bytes(trailer.data(), trailer.size()));
    auto bytes = w.take();
    const auto digest = blake3_hash(bytes_of(bytes));
    bytes.insert(bytes.end(), digest.begin(), digest.end());
    return bytes;
}


static std::vector<std::uint8_t> zstd_compress(Bytes data, int level) {
    if (data.empty())
        return {};
    const std::size_t bound = ZSTD_compressBound(data.size());
    std::vector<std::uint8_t> out(bound);
    const std::size_t n = ZSTD_compress(out.data(), bound, data.data(), data.size(), level);
    if (ZSTD_isError(n) || n >= data.size())
        return {};
    out.resize(n);
    out.shrink_to_fit();
    return out;
}

namespace {

struct PackIdHash {
    std::size_t operator()(const Id& id) const noexcept {
        std::uint64_t h = 1469598103934665603ull;
        for (auto b : id) {
            h ^= b;
            h *= 1099511628211ull;
        }
        return static_cast<std::size_t>(h);
    }
};

struct PackIdEq {
    bool operator()(const Id& a, const Id& b) const noexcept {
        return std::memcmp(a.data(), b.data(), ID_LEN) == 0;
    }
};

// A zstd frame that can use another object's bytes as a dictionary.
bool zstd_compress_dict(Bytes data, Bytes dict, int level, std::vector<std::uint8_t>& out) {
    if (data.empty())
        return false;
    static thread_local ZSTD_CCtx* ctx = ZSTD_createCCtx();
    ZSTD_CCtx_reset(ctx, ZSTD_reset_session_only);
    if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_compressionLevel, level)))
        return false;
    (void)ZSTD_CCtx_setParameter(ctx, ZSTD_c_checksumFlag, 0);
    if (ZSTD_isError(ZSTD_CCtx_loadDictionary(ctx, dict.data(), dict.size())))
        return false;
    out.resize(ZSTD_compressBound(data.size()));
    const std::size_t n = ZSTD_compress2(ctx, out.data(), out.size(), data.data(), data.size());
    if (ZSTD_isError(n) || n >= data.size())
        return false;
    out.resize(n);
    out.shrink_to_fit();
    return true;
}

struct PendingObject {
    const RawObject* object = nullptr;
    Id id{};
    std::uint8_t compression = 0;
    std::vector<std::uint8_t> compressed;
    std::optional<std::size_t> base;
};

struct BlobRoot {
    std::size_t pending_index = 0;
    std::vector<BlobEntry> entries;
    std::vector<std::uint64_t> offsets;
    std::uint64_t length = 0;
};

// Rewrites pending chunk records as deltas against the chunk at the same
// position in a previous version of the same file. File versions are found
// through the blob manifests in the pack: two manifests that share chunks are
// successive versions of one file, and manifests of similar length are tried
// when edits touched every chunk. Chains are bounded by the caller.
void select_pack_deltas(std::vector<PendingObject>& pending, int level) {
    std::unordered_map<Id, std::size_t, PackIdHash, PackIdEq> blob_index;
    std::unordered_map<Id, std::size_t, PackIdHash, PackIdEq> chunk_index;
    for (std::size_t i = 0; i < pending.size(); ++i) {
        const auto type = pending[i].object->type;
        if (type == TYPE_BLOB)
            blob_index.emplace(pending[i].id, i);
        else if (type == TYPE_CHUNK)
            chunk_index.emplace(pending[i].id, i);
    }
    if (blob_index.empty() || chunk_index.empty())
        return;

    std::unordered_map<Id, char, PackIdHash, PackIdEq> children;
    for (std::size_t i = 0; i < pending.size(); ++i) {
        if (pending[i].object->type != TYPE_BLOB)
            continue;
        auto blob = decode_blob(bytes_of(pending[i].object->body));
        if (!blob || blob->form != BlobForm::Interior)
            continue;
        for (const auto& entry : blob->entries)
            children.emplace(entry.id, 1);
    }

    std::vector<BlobRoot> roots;
    for (std::size_t i = 0; i < pending.size(); ++i) {
        if (pending[i].object->type != TYPE_BLOB)
            continue;
        auto blob = decode_blob(bytes_of(pending[i].object->body));
        if (!blob || blob->form == BlobForm::Inline)
            continue;
        if (children.find(pending[i].id) != children.end())
            continue;
        BlobRoot root;
        root.pending_index = i;
        bool ok = true;
        std::function<bool(const Id&, std::size_t)> flatten = [&](const Id& id,
                                                                  std::size_t depth) -> bool {
            if (depth > 64)
                return false;
            auto it = blob_index.find(id);
            if (it == blob_index.end())
                return false;
            auto child = decode_blob(bytes_of(pending[it->second].object->body));
            if (!child)
                return false;
            if (child->form == BlobForm::Leaf) {
                for (const auto& entry : child->entries)
                    root.entries.push_back(entry);
                return true;
            }
            if (child->form != BlobForm::Interior)
                return false;
            for (const auto& entry : child->entries) {
                if (!flatten(entry.id, depth + 1))
                    return false;
            }
            return true;
        };
        if (blob->form == BlobForm::Leaf) {
            for (const auto& entry : blob->entries)
                root.entries.push_back(entry);
        } else {
            ok = flatten(pending[i].id, 0);
        }
        if (!ok || root.entries.empty())
            continue;
        std::uint64_t offset = 0;
        for (const auto& entry : root.entries) {
            root.offsets.push_back(offset);
            offset += entry.length;
        }
        root.length = offset;
        roots.push_back(std::move(root));
    }
    if (roots.size() < 2)
        return;

    std::vector<std::size_t> parent(roots.size(), SIZE_MAX);
    {
        std::unordered_map<Id, std::size_t, PackIdHash, PackIdEq> last_root;
        std::unordered_map<std::uint64_t, std::vector<std::size_t>> last_bucket;

        auto score = [&](std::size_t target,
                         std::size_t base) -> std::pair<std::size_t, std::size_t> {
            const BlobRoot& tr = roots[target];
            const BlobRoot& br = roots[base];
            const std::size_t count = tr.entries.size();
            std::size_t sampled = 0;
            std::size_t delta_sum = 0;
            std::size_t solo_sum = 0;
            for (std::size_t s = 0; s < 3 && count > 0; ++s) {
                const std::size_t k = (count * (2 * s + 1)) / 6;
                if (k >= count)
                    continue;
                auto it = chunk_index.find(tr.entries[k].id);
                if (it == chunk_index.end())
                    continue;
                const std::size_t index = it->second;
                if (pending[index].base)
                    continue;
                const Bytes body = bytes_of(pending[index].object->body);
                const std::size_t solo = pending[index].compression == 1
                                             ? pending[index].compressed.size()
                                             : body.size();
                if (solo == 0)
                    continue;
                ++sampled;
                solo_sum += solo;
                std::size_t best = solo;
                const auto lower =
                    std::lower_bound(br.offsets.begin(), br.offsets.end(), tr.offsets[k]);
                const std::size_t near = static_cast<std::size_t>(lower - br.offsets.begin());
                for (int d = -1; d <= 1; ++d) {
                    const std::ptrdiff_t candidate = static_cast<std::ptrdiff_t>(near) + d;
                    if (candidate < 0 ||
                        candidate >= static_cast<std::ptrdiff_t>(br.entries.size()))
                        continue;
                    auto bit = chunk_index.find(br.entries[static_cast<std::size_t>(candidate)].id);
                    if (bit == chunk_index.end())
                        continue;
                    const std::size_t base_index = bit->second;
                    if (base_index >= index)
                        continue;
                    std::vector<std::uint8_t> frame;
                    if (!zstd_compress_dict(body, bytes_of(pending[base_index].object->body), level,
                                            frame))
                        continue;
                    best = std::min(best, frame.size() + 10);
                }
                delta_sum += best;
            }
            if (sampled == 0)
                return {SIZE_MAX, 0};
            return {delta_sum, solo_sum};
        };

        constexpr std::size_t max_candidates = 16;
        for (std::size_t r = 0; r < roots.size(); ++r) {
            std::vector<std::size_t> candidates;
            std::unordered_map<std::size_t, std::size_t> votes;
            for (const auto& entry : roots[r].entries) {
                auto it = last_root.find(entry.id);
                if (it == last_root.end())
                    continue;
                const auto& candidate = roots[it->second];
                if (candidate.length == 0 || roots[r].length == 0)
                    continue;
                const double ratio =
                    static_cast<double>(candidate.length) / static_cast<double>(roots[r].length);
                if (ratio < 0.4 || ratio > 2.5)
                    continue;
                ++votes[it->second];
            }
            std::size_t voted = SIZE_MAX;
            std::size_t voted_count = 0;
            for (const auto& [candidate, count] : votes) {
                if (count > voted_count || (count == voted_count && candidate < voted)) {
                    voted_count = count;
                    voted = candidate;
                }
            }
            if (voted != SIZE_MAX)
                candidates.push_back(voted);

            const std::uint64_t low = (roots[r].length * 9) / 10;
            const std::uint64_t high = (roots[r].length * 11) / 10;
            std::unordered_map<std::size_t, std::uint64_t> nearby;
            for (std::uint64_t bucket = low >> 13; bucket <= (high >> 13); ++bucket) {
                auto it = last_bucket.find(bucket);
                if (it == last_bucket.end())
                    continue;
                for (std::size_t candidate : it->second) {
                    const auto& other = roots[candidate];
                    if (other.length == 0 || roots[r].length == 0)
                        continue;
                    const double ratio =
                        static_cast<double>(other.length) / static_cast<double>(roots[r].length);
                    if (ratio < 0.9 || ratio > 1.1)
                        continue;
                    const std::uint64_t diff = other.length > roots[r].length
                                                   ? other.length - roots[r].length
                                                   : roots[r].length - other.length;
                    auto seen = nearby.find(candidate);
                    if (seen == nearby.end() || diff < seen->second)
                        nearby.emplace(candidate, diff);
                }
            }
            std::vector<std::pair<std::uint64_t, std::size_t>> ranked;
            for (const auto& [candidate, diff] : nearby)
                ranked.emplace_back(diff, candidate);
            std::sort(ranked.begin(), ranked.end(), [](const auto& a, const auto& b) {
                if (a.first != b.first)
                    return a.first < b.first;
                return a.second > b.second;
            });
            for (const auto& [diff, candidate] : ranked)
                candidates.push_back(candidate);
            std::vector<std::size_t> unique_candidates;
            unique_candidates.reserve(candidates.size());
            for (std::size_t candidate : candidates) {
                if (std::find(unique_candidates.begin(), unique_candidates.end(), candidate) ==
                    unique_candidates.end())
                    unique_candidates.push_back(candidate);
            }
            candidates = std::move(unique_candidates);
            if (candidates.size() > max_candidates)
                candidates.resize(max_candidates);

            std::size_t best = SIZE_MAX;
            std::size_t best_sum = SIZE_MAX;
            std::size_t best_solo = 0;
            for (std::size_t candidate : candidates) {
                if (candidate == r)
                    continue;
                const auto [sum, solo] = score(r, candidate);
                if (solo == 0 || sum >= solo)
                    continue;
                if (sum < best_sum) {
                    best_sum = sum;
                    best_solo = solo;
                    best = candidate;
                }
            }
            if (best != SIZE_MAX && best_solo > 0)
                parent[r] = best;

            for (const auto& entry : roots[r].entries)
                last_root[entry.id] = r;
            auto& bucket = last_bucket[roots[r].length >> 13];
            bucket.push_back(r);
            if (bucket.size() > 4)
                bucket.erase(bucket.begin());
        }
    }

    for (std::size_t r = 0; r < roots.size(); ++r) {
        if (parent[r] == SIZE_MAX)
            continue;
        const BlobRoot& base_root = roots[parent[r]];
        for (std::size_t k = 0; k < roots[r].entries.size(); ++k) {
            auto it = chunk_index.find(roots[r].entries[k].id);
            if (it == chunk_index.end())
                continue;
            const std::size_t index = it->second;
            PendingObject& target = pending[index];
            if (target.base || target.object->type != TYPE_CHUNK)
                continue;
            const Bytes target_body = bytes_of(target.object->body);
            const std::size_t solo =
                target.compression == 1 ? target.compressed.size() : target.object->body.size();
            if (solo == 0)
                continue;
            const std::uint64_t target_offset = roots[r].offsets[k];
            const auto lower =
                std::lower_bound(base_root.offsets.begin(), base_root.offsets.end(), target_offset);
            std::size_t nearest = static_cast<std::size_t>(lower - base_root.offsets.begin());
            std::size_t best_size = solo;
            std::size_t best_base = SIZE_MAX;
            std::vector<std::uint8_t> best_frame;
            for (int delta = -2; delta <= 2; ++delta) {
                const std::ptrdiff_t candidate = static_cast<std::ptrdiff_t>(nearest) + delta;
                if (candidate < 0 ||
                    candidate >= static_cast<std::ptrdiff_t>(base_root.entries.size()))
                    continue;
                auto base_it =
                    chunk_index.find(base_root.entries[static_cast<std::size_t>(candidate)].id);
                if (base_it == chunk_index.end())
                    continue;
                const std::size_t base_index = base_it->second;
                if (base_index >= index)
                    continue;
                PendingObject& base = pending[base_index];
                if (base.object->type != TYPE_CHUNK || base.object->body.size() == 0)
                    continue;
                const double ratio = static_cast<double>(base.object->body.size()) /
                                     static_cast<double>(target_body.size());
                if (ratio < 0.3 || ratio > 3.0)
                    continue;
                std::vector<std::uint8_t> frame;
                if (!zstd_compress_dict(target_body, bytes_of(base.object->body), level, frame))
                    continue;
                const std::size_t framed = frame.size() + 10;
                if (framed < best_size) {
                    best_size = framed;
                    best_base = base_index;
                    best_frame = std::move(frame);
                }
            }
            if (best_base != SIZE_MAX) {
                target.base = best_base;
                target.compression = 2;
                target.compressed = std::move(best_frame);
            }
        }
    }

    // Bound delta chains. Every link costs one extra dictionary decompression
    // on read, so cap the depth and store deeper objects standalone.
    constexpr int max_delta_depth = 4;
    std::vector<int> depth(pending.size(), 0);
    for (std::size_t i = 0; i < pending.size(); ++i) {
        if (!pending[i].base)
            continue;
        depth[i] = depth[*pending[i].base] + 1;
        if (depth[i] <= max_delta_depth)
            continue;
        pending[i].base.reset();
        pending[i].compression = 0;
        pending[i].compressed.clear();
        depth[i] = 0;
        if (pending[i].object->body.size() >= 64) {
            auto solo = zstd_compress(bytes_of(pending[i].object->body), level);
            if (!solo.empty()) {
                pending[i].compression = 1;
                pending[i].compressed = std::move(solo);
            }
        }
    }
}

} // namespace

PackOutput encode_pack(const std::vector<RawObject>& objects, int level) {
    PackOutput output;
    std::set<Id> seen;
    std::vector<PendingObject> pending;
    pending.reserve(objects.size());
    for (const auto& object : objects) {
        if (!type_valid(object.type))
            continue;
        const Id id = object.id ? *object.id : object_id(object.type, bytes_of(object.body));
        if (!seen.insert(id).second)
            continue;
        PendingObject item;
        item.object = &object;
        item.id = id;
        pending.push_back(std::move(item));
    }

    auto compress_one = [level](PendingObject& item) {
        if (item.object->body.size() < 64)
            return;
        item.compressed = zstd_compress(bytes_of(item.object->body), level);
        item.compression = item.compressed.empty() ? 0 : 1;
    };
    if (pending.size() > 1) {
        std::size_t workers = available_cpu_count();
        if (workers == 0)
            workers = 1;
        workers = std::min<std::size_t>(workers, pending.size());
        workers = std::min<std::size_t>(workers, 16);
        if (workers > 1) {
            std::atomic<std::size_t> next{0};
            std::vector<std::thread> threads;
            threads.reserve(workers);
            for (std::size_t w = 0; w < workers; ++w) {
                threads.emplace_back([&]() {
                    for (;;) {
                        const std::size_t index = next.fetch_add(1);
                        if (index >= pending.size())
                            return;
                        compress_one(pending[index]);
                    }
                });
            }
            for (auto& thread : threads)
                thread.join();
        } else {
            for (auto& item : pending)
                compress_one(item);
        }
    } else {
        for (auto& item : pending)
            compress_one(item);
    }

    select_pack_deltas(pending, level);

    std::vector<RecordMeta> metas;
    metas.reserve(pending.size());
    std::vector<std::uint64_t> record_offsets(pending.size(), 0);
    std::size_t estimate = 16;
    for (const auto& item : pending) {
        std::size_t stored = item.object->body.size();
        if (item.compression != 0)
            stored = item.compressed.size();
        estimate += 32 + 2 + 20 + stored;
    }
    ByteWriter w(estimate);
    w.raw("VPK1");
    w.u32le(1);
    w.u64le(0);
    for (std::size_t i = 0; i < pending.size(); ++i) {
        auto& item = pending[i];
        const auto& object = *item.object;
        const std::uint64_t offset = w.size();
        record_offsets[i] = offset;
        ByteWriter rec(64);
        rec.id(item.id);
        rec.u8(object.type);
        if (item.base) {
            const std::uint64_t base_offset = record_offsets[*item.base];
            ByteWriter stored(item.compressed.size() + 10);
            stored.varint(base_offset);
            stored.raw(bytes_of(item.compressed));
            rec.u8(2);
            rec.varint(object.body.size());
            rec.varint(stored.size());
            rec.raw(stored.view());
        } else {
            const Bytes stored =
                item.compression == 1 ? bytes_of(item.compressed) : bytes_of(object.body);
            rec.u8(item.compression);
            rec.varint(object.body.size());
            rec.varint(stored.size());
            rec.raw(stored);
        }
        w.raw(rec.view());
        metas.push_back(RecordMeta{item.id, offset, object.type, object.body.size()});
    }

    auto pack = w.take();
    write_u64le(pack, 8, static_cast<std::uint64_t>(metas.size()));
    const auto digest = blake3_hash(bytes_of(pack));
    pack.insert(pack.end(), digest.begin(), digest.end());
    std::array<std::uint8_t, 32> trailer{};
    std::memcpy(trailer.data(), digest.data(), 32);

    std::stable_sort(metas.begin(), metas.end(), [](const RecordMeta& a, const RecordMeta& b) {
        return std::memcmp(a.id.data(), b.id.data(), ID_LEN) < 0;
    });
    output.index = encode_index(metas, trailer);
    output.name = hex_encode(Bytes(trailer.data(), trailer.size()));
    output.count = metas.size();
    output.pack = std::move(pack);
    return output;
}

static int write_pack_output(const fs::path& root, const PackOutput& output, std::uint64_t limit) {
    if (output.count == 0)
        return 0;
    if (limit > 0 && output.pack.size() + output.index.size() > limit)
        return 2;
    const fs::path pfinal = packs_dir(root) / (output.name + ".vpack");
    const fs::path ifinal = packs_dir(root) / (output.name + ".vidx");
    const std::string suffix =
        "." + std::to_string(static_cast<unsigned long long>(random_u64())) + ".tmp";
    const fs::path ptmp = tmp_dir(root) / (output.name + ".vpack" + suffix);
    const fs::path itmp = tmp_dir(root) / (output.name + ".vidx" + suffix);
    if (!write_atomic(ptmp, pfinal, bytes_of(output.pack)))
        return 1;
    if (!write_atomic(itmp, ifinal, bytes_of(output.index))) {
        (void)remove_file(pfinal);
        return 1;
    }
    return 0;
}

int write_pack(const fs::path& root, const std::vector<RawObject>& objects, std::uint64_t limit,
               int level) {
    PackOutput output = encode_pack(objects, level);
    return write_pack_output(root, output, limit);
}

int repack_repository(const fs::path& root, int level, bool verbose) {
    const fs::path source_dir = packs_dir(root);
    std::vector<RawObject> objects;
    std::set<Id> seen;
    std::uint64_t before = 0;
    auto names = list_directory(source_dir);
    std::sort(names.begin(), names.end());
    for (const auto& name : names) {
        if (name.size() <= 6 || name.compare(name.size() - 6, 6, ".vpack") != 0)
            continue;
        const std::string base = name.substr(0, name.size() - 6);
        if (!path_is_file(source_dir / path_from_bytes(base + ".vidx")))
            continue;
        auto data = read_file_opt(source_dir / path_from_bytes(name), MAX_STORE_PACK_BYTES);
        if (!data) {
            error_prefix();
            std::cout << "cannot read pack " << name << "\n";
            return 1;
        }
        before += data->size();
        auto pack = decode_pack(std::move(*data));
        if (!pack) {
            error_prefix();
            std::cout << "cannot decode pack " << name << "\n";
            return 1;
        }
        for (std::size_t i = 0; i < pack->records.size(); ++i) {
            const auto& record = pack->records[i];
            if (!seen.insert(record.id).second)
                continue;
            auto body = pack->get(i);
            if (!body) {
                error_prefix();
                std::cout << "cannot read object " << hex_encode(Bytes(record.id.data(), ID_LEN))
                          << "\n";
                return 1;
            }
            objects.push_back(RawObject{record.type, std::move(*body), record.id});
        }
    }
    if (objects.empty()) {
        info_prefix();
        std::cout << "no objects to repack\n";
        return 0;
    }
    PackOutput output = encode_pack(objects, level);
    if (output.count == 0) {
        info_prefix();
        std::cout << "no objects to repack\n";
        return 0;
    }
    const int written = write_pack_output(root, output, 0);
    if (written != 0) {
        error_prefix();
        std::cout << "cannot write repacked pack\n";
        return 1;
    }
    const fs::path dir = packs_dir(root);
    for (const auto& name : list_directory(dir)) {
        if (name.size() <= 6)
            continue;
        const bool is_pack = name.compare(name.size() - 6, 6, ".vpack") == 0;
        const bool is_index = name.compare(name.size() - 5, 5, ".vidx") == 0;
        if (!is_pack && !is_index)
            continue;
        const std::string base = name.substr(0, name.size() - (is_pack ? 6 : 5));
        if (base == output.name)
            continue;
        (void)remove_file(dir / path_from_bytes(name));
    }
    if (verbose) {
        info_prefix();
        std::cout << "repacked " << output.count << " objects, " << (before / 1024) << " KiB -> "
                  << ((output.pack.size() + output.index.size()) / 1024) << " KiB\n";
    }
    return 0;
}


#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 (static_cast<std::uint64_t>(length) > MAX_STORE_PACK_BYTES)
        return std::nullopt;
#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;
    std::string name = basename_string(handle.path);
    if (name.size() <= 6)
        return false;
    name.resize(name.size() - 6);
    const fs::path idx_path = handle.path.parent_path() / (name + ".vidx");
    auto data = read_file_opt(idx_path, MAX_STORE_PACK_BYTES);
    if (!data)
        return false;
    auto decoded = decode_index(std::move(*data));
    if (!decoded)
        return false;
    if (name != hex_encode(Bytes(decoded->pack_trailer.data(), 32)))
        return false;
    handle.index = std::move(*decoded);
    return true;
}

bool Store::ensure_index(StoreHandle& handle) {
    return handle_index(handle);
}

bool Store::ensure_pack(StoreHandle& handle) {
    if (handle.pack)
        return true;
    if (!ensure_index(handle))
        return false;
    auto data = read_file_opt(handle.path, MAX_STORE_PACK_BYTES);
    if (!data)
        return false;
    auto decoded = decode_pack(std::move(*data));
    if (!decoded)
        return false;
    if (!equals(Bytes(decoded->trailer.data(), 32), Bytes(handle.index->pack_trailer.data(), 32)))
        return false;
    handle.pack = std::move(*decoded);
    return true;
}

static std::uint64_t handle_mtime(const fs::path& path) {
    const auto info = stat_path(path);
    return info ? info->mtime_ns : 0;
}

Store Store::open_all(const fs::path& root) {
    Store store;
    store.root_ = root;
    for (const auto& name : list_directory(packs_dir(root))) {
        if (name.size() <= 6)
            continue;
        if (name.compare(name.size() - 6, 6, ".vpack") != 0)
            continue;
        StoreHandle handle;
        handle.path = packs_dir(root) / path_from_bytes(name);
        handle.mtime_ns = handle_mtime(handle.path);
        store.handles_.push_back(std::move(handle));
    }
    std::sort(store.handles_.begin(), store.handles_.end(),
              [](const StoreHandle& a, const StoreHandle& b) {
                  if (a.mtime_ns != b.mtime_ns)
                      return a.mtime_ns > b.mtime_ns;
                  return a.path < b.path;
              });
    return store;
}

void Store::preload() {
    for (auto& handle : handles_) {
        (void)ensure_index(handle);
        (void)handle_fd(handle);
    }
}

void Store::refresh(const fs::path& root) {
    for (const auto& name : list_directory(packs_dir(root))) {
        if (name.size() <= 6)
            continue;
        if (name.compare(name.size() - 6, 6, ".vpack") != 0)
            continue;
        const fs::path path = packs_dir(root) / path_from_bytes(name);
        bool found = false;
        for (const auto& handle : handles_) {
            if (handle.path == path) {
                found = true;
                break;
            }
        }
        if (!found) {
            StoreHandle handle;
            handle.path = path;
            handle.mtime_ns = handle_mtime(path);
            handles_.push_back(std::move(handle));
        }
    }
    std::sort(handles_.begin(), handles_.end(), [](const StoreHandle& a, const StoreHandle& b) {
        if (a.mtime_ns != b.mtime_ns)
            return a.mtime_ns > b.mtime_ns;
        return a.path < b.path;
    });
}

static std::optional<Loc> read_record_loc_at(StoreHandle& handle, std::size_t pack_index,
                                             std::uint64_t offset, const Id* expected = nullptr) {
    auto header = read_handle_range(handle, 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 (expected && std::memcmp(id->data(), expected->data(), ID_LEN) != 0)
        return std::nullopt;
    if (!type_valid(*type) || *compression > 2 || *raw_len == 0)
        return std::nullopt;
    if (*raw_len > pack_type_limit(*type))
        return std::nullopt;
    // Compressed or delta-framed payloads may exceed the raw length by a small
    // amount, but never by an unbounded amount. Refuse absurd stored lengths
    // before the read allocates them.
    if (*stored_len > static_cast<std::uint64_t>(pack_type_limit(*type)) + MAX_CHUNK_LEN)
        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;
}

static std::optional<Loc> read_record_loc(StoreHandle& handle, std::size_t pack_index,
                                          std::uint64_t offset, const Id& expected) {
    return read_record_loc_at(handle, pack_index, offset, &expected);
}

std::optional<Loc> Store::find(const Id& id) {
    for (std::size_t i = 0; i < handles_.size(); ++i) {
        auto& handle = handles_[i];
        if (!ensure_index(handle))
            continue;
        const auto pos = handle.index->find(id);
        if (!pos)
            continue;
        const std::uint64_t offset = handle.index->offsets[*pos];
        if (auto loc = read_record_loc(handle, i, offset, id))
            return loc;
    }
    return std::nullopt;
}

bool Store::contains(const Id& id) {
    for (auto& handle : handles_) {
        if (!ensure_index(handle))
            continue;
        if (handle.index->find(id))
            return true;
    }
    return false;
}

static Result<std::vector<std::uint8_t>> get_loc(StoreHandle& handle, const Loc& loc, int depth) {
    if (depth > 32)
        return fail(ErrorKind::Corrupt, loc.data_offset);
    auto stored =
        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)
        return std::move(*stored);
    auto raw_len = static_cast<std::size_t>(loc.raw_len);
    if (loc.compression == 1) {
        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;
    }
    if (loc.compression != 2)
        return fail(ErrorKind::InvalidValue, loc.data_offset);
    Reader header(bytes_of(*stored));
    const auto base_off = header.varint();
    if (!base_off || *base_off >= loc.record_offset)
        return fail(ErrorKind::Corrupt, loc.data_offset);
    const auto frame = header.raw(header.remaining());
    if (!frame || frame->empty())
        return fail(ErrorKind::Corrupt, loc.data_offset);
    const auto base_loc = read_record_loc_at(handle, loc.pack_index, *base_off);
    if (!base_loc)
        return fail(ErrorKind::Corrupt, loc.data_offset);
    auto base_body = get_loc(handle, *base_loc, depth + 1);
    if (!base_body)
        return unexpected(base_body.error());
    std::vector<std::uint8_t> out(raw_len);
    const std::size_t n =
        ZSTD_decompress_usingDict(thread_decompress_context(), out.data(), raw_len, frame->data(),
                                  frame->size(), base_body->data(), base_body->size());
    if (ZSTD_isError(n) || n != raw_len)
        return fail(ErrorKind::Corrupt, loc.data_offset);
    return out;
}

Result<std::vector<std::uint8_t>> Store::get(const Loc& loc) {
    if (loc.pack_index >= handles_.size())
        return fail(ErrorKind::Corrupt, 0);
    if (loc.stored_len > std::numeric_limits<std::size_t>::max())
        return fail(ErrorKind::LimitExceeded, loc.data_offset);
    return get_loc(handles_[loc.pack_index], loc, 0);
}

std::optional<std::vector<std::uint8_t>> Store::read_body(const Id& id, std::uint8_t expected) {
    auto loc = find(id);
    if (!loc && expected == TYPE_CHUNK && promisor_fetcher && !root_.empty()) {
        if (promisor_fetcher(root_, id)) {
            refresh(root_);
            loc = find(id);
        }
    }
    if (!loc || loc->kind != expected)
        return std::nullopt;
    auto body = get(*loc);
    if (!body)
        return std::nullopt;
    const Id computed = object_id(expected, bytes_of(*body));
    if (std::memcmp(computed.data(), id.data(), ID_LEN) != 0)
        return std::nullopt;
    return std::move(*body);
}

std::optional<View> Store::read_view(const Id& id) {
    auto body = read_body(id, TYPE_VIEW);
    if (!body)
        return std::nullopt;
    auto view = decode_view(bytes_of(*body));
    if (!view)
        return std::nullopt;
    return std::move(*view);
}

std::optional<Operation> Store::read_operation(const Id& id) {
    auto body = read_body(id, TYPE_OPERATION);
    if (!body)
        return std::nullopt;
    auto op = decode_operation(bytes_of(*body));
    if (!op)
        return std::nullopt;
    return std::move(*op);
}

bool Store::has_promisor(const fs::path& root) const {
    auto data = read_file_opt(config_path(root));
    if (!data)
        return false;
    const std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());
    return text.find("promisor") != std::string_view::npos;
}

Id Writer::add(std::uint8_t type, const std::vector<std::uint8_t>& body) {
    const Id id = object_id(type, bytes_of(body));
    if (quota_hit_ || !seen_.insert(id).second)
        return id;
    if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {
        quota_hit_ = true;
        return id;
    }
    raw_bytes_ += body.size();
    objects_.push_back(RawObject{type, body, id});
    if (type != TYPE_CHUNK || cache_chunks_)
        cache_.push_back(RawObject{type, body, id});
    return id;
}

Id Writer::add(std::uint8_t type, std::vector<std::uint8_t>&& body) {
    const Id id = object_id(type, bytes_of(body));
    if (quota_hit_ || !seen_.insert(id).second)
        return id;
    if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {
        quota_hit_ = true;
        return id;
    }
    raw_bytes_ += body.size();
    if (type != TYPE_CHUNK || cache_chunks_)
        cache_.push_back(RawObject{type, body, id});
    objects_.push_back(RawObject{type, std::move(body), id});
    return id;
}

Id Writer::add_known(std::uint8_t type, const Id& id, const std::vector<std::uint8_t>& body) {
    if (quota_hit_ || !seen_.insert(id).second)
        return id;
    if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {
        quota_hit_ = true;
        return id;
    }
    raw_bytes_ += body.size();
    objects_.push_back(RawObject{type, body, id});
    if (type != TYPE_CHUNK || cache_chunks_)
        cache_.push_back(RawObject{type, body, id});
    return id;
}

Id Writer::add_known(std::uint8_t type, const Id& id, std::vector<std::uint8_t>&& body) {
    if (quota_hit_ || !seen_.insert(id).second)
        return id;
    if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {
        quota_hit_ = true;
        return id;
    }
    raw_bytes_ += body.size();
    if (type != TYPE_CHUNK || cache_chunks_)
        cache_.push_back(RawObject{type, body, id});
    objects_.push_back(RawObject{type, std::move(body), id});
    return id;
}

std::optional<std::vector<std::uint8_t>> Writer::find_cached(std::uint8_t type,
                                                             const Id& id) const {
    for (const auto& object : cache_) {
        const Id candidate = object.id ? *object.id : object_id(type, bytes_of(object.body));
        if (object.type == type && std::memcmp(candidate.data(), id.data(), ID_LEN) == 0)
            return object.body;
    }
    return std::nullopt;
}

int Writer::finish(const fs::path& root) {
    if (quota_hit_)
        return 2;
    return write_pack(root, objects_, limit_);
}


static bool id_less(const Id& a, const Id& b) {
    return std::memcmp(a.data(), b.data(), ID_LEN) < 0;
}

static bool id_equal(const Id& a, const Id& b) {
    return std::memcmp(a.data(), b.data(), ID_LEN) == 0;
}

namespace {
struct IdHash {
    std::size_t operator()(const Id& id) const noexcept {
        std::size_t h = 1469598103934665603ull;
        for (auto b : id) {
            h ^= b;
            h *= 1099511628211ull;
        }
        return h;
    }
};
struct IdEq {
    bool operator()(const Id& a, const Id& b) const noexcept {
        return id_equal(a, b);
    }
};
} // namespace

bool contains_id(const std::vector<Id>& ids, const Id& id) {
    return std::find_if(ids.begin(), ids.end(), [&](const Id& x) { return id_equal(x, id); }) !=
           ids.end();
}

bool target_contains(const std::vector<std::optional<Id>>& ids, const Id& id) {
    for (const auto& x : ids) {
        if (x && id_equal(*x, id))
            return true;
    }
    return false;
}

std::optional<Id> working_copy_id(const View& view) {
    for (const auto& workspace : view.working_copies) {
        if (workspace.workspace == "default")
            return workspace.target;
    }
    return std::nullopt;
}

void sort_ids(std::vector<Id>& ids) {
    std::stable_sort(ids.begin(), ids.end(), id_less);
}

void sort_view(View& view) {
    sort_ids(view.heads);
    std::stable_sort(view.bookmarks.begin(), view.bookmarks.end(),
                     [](const Bookmark& a, const Bookmark& b) {
                         return compare(bytes_of(a.name), bytes_of(b.name)) < 0;
                     });
    std::stable_sort(view.tags.begin(), view.tags.end(), [](const TagRef& a, const TagRef& b) {
        return compare(bytes_of(a.name), bytes_of(b.name)) < 0;
    });
    std::stable_sort(view.remote_refs.begin(), view.remote_refs.end(),
                     [](const RemoteRef& a, const RemoteRef& b) {
                         const int c = compare(bytes_of(a.remote), bytes_of(b.remote));
                         if (c != 0)
                             return c < 0;
                         return compare(bytes_of(a.name), bytes_of(b.name)) < 0;
                     });
    std::stable_sort(view.working_copies.begin(), view.working_copies.end(),
                     [](const WorkspaceRef& a, const WorkspaceRef& b) {
                         return compare(bytes_of(a.workspace), bytes_of(b.workspace)) < 0;
                     });
}

void add_unique_head(View& view, const Id& id) {
    if (!contains_id(view.heads, id))
        view.heads.push_back(id);
}

void rebuild_heads(View& view) {
    view.heads.clear();
    for (const auto& bookmark : view.bookmarks) {
        for (const auto& id : bookmark.targets.adds) {
            if (id)
                add_unique_head(view, *id);
        }
    }
    for (const auto& tag : view.tags)
        add_unique_head(view, tag.target);
    for (const auto& workspace : view.working_copies)
        add_unique_head(view, workspace.target);
    sort_ids(view.heads);
}

void set_workspace(View& view, const Id& id) {
    for (auto& workspace : view.working_copies) {
        if (workspace.workspace == "default") {
            workspace.target = id;
            return;
        }
    }
    view.working_copies.push_back(WorkspaceRef{"default", id});
    std::stable_sort(view.working_copies.begin(), view.working_copies.end(),
                     [](const WorkspaceRef& a, const WorkspaceRef& b) {
                         return compare(bytes_of(a.workspace), bytes_of(b.workspace)) < 0;
                     });
}

void remove_head(View& view, const Id& id) {
    view.heads.erase(std::remove_if(view.heads.begin(), view.heads.end(),
                                    [&](const Id& x) { return id_equal(x, id); }),
                     view.heads.end());
}

void move_bookmarks(View& view, const Id& old_id, const Id& new_id) {
    if (id_equal(old_id, new_id))
        return;
    for (auto& bookmark : view.bookmarks) {
        if (target_contains(bookmark.targets.adds, old_id)) {
            bookmark.targets.adds = {new_id};
            bookmark.targets.removes.clear();
        }
    }
}

void set_bookmark_target(View& view, std::string_view name, const Id& id) {
    if (auto index = find_bookmark(view, name)) {
        view.bookmarks[*index].targets.adds = {id};
        view.bookmarks[*index].targets.removes.clear();
        return;
    }
    Bookmark bookmark;
    bookmark.name = std::string(name);
    bookmark.targets.adds = {id};
    view.bookmarks.push_back(std::move(bookmark));
}

std::optional<std::size_t> find_bookmark(const View& view, std::string_view name) {
    for (std::size_t i = 0; i < view.bookmarks.size(); ++i) {
        if (view.bookmarks[i].name == name)
            return i;
    }
    return std::nullopt;
}

std::optional<std::size_t> find_tag(const View& view, std::string_view name) {
    for (std::size_t i = 0; i < view.tags.size(); ++i) {
        if (view.tags[i].name == name)
            return i;
    }
    return std::nullopt;
}

std::vector<std::string> bookmark_names(const View& view, const Id& id) {
    std::vector<std::string> out;
    for (const auto& bookmark : view.bookmarks) {
        if (target_contains(bookmark.targets.adds, id))
            out.push_back(bookmark.name);
    }
    return out;
}

std::vector<std::string> tag_names(const View& view, const Id& id) {
    std::vector<std::string> out;
    for (const auto& tag : view.tags) {
        if (id_equal(tag.target, id))
            out.push_back(tag.name);
    }
    return out;
}

View empty_view() {
    return {};
}

std::vector<Id> read_heads(const fs::path& root) {
    std::vector<Id> out;
    for (const auto& name : list_directory(op_heads_dir(root))) {
        if (name.size() != 64)
            continue;
        Id id{};
        if (!hex_decode(name, MutBytes(id.data(), id.size())))
            continue;
        out.push_back(id);
    }
    sort_ids(out);
    return out;
}

bool write_head(const fs::path& root, const Id& id) {
    const std::string name = hex_encode(id);
    const fs::path final_path = op_heads_dir(root) / name;
    const fs::path tmp_path = tmp_dir(root) / (name + ".tmp");
    return write_atomic(tmp_path, final_path, Bytes{});
}

bool delete_head(const fs::path& root, const Id& id) {
    return remove_file(op_heads_dir(root) / hex_encode(id));
}

static std::optional<View> load_view_for_head(Store& store, const Id& id);
static void merge_view_into(View& dst, const View& src);

std::optional<View> current_view(const fs::path& root, Store& store) {
    const auto heads = read_heads(root);
    if (heads.empty())
        return std::nullopt;
    auto base = load_view_for_head(store, heads.front());
    if (!base)
        return std::nullopt;
    for (std::size_t i = 1; i < heads.size(); ++i) {
        auto extra = load_view_for_head(store, heads[i]);
        if (extra)
            merge_view_into(*base, *extra);
    }
    sort_view(*base);
    return base;
}

static std::optional<View> load_view_for_head(Store& store, const Id& id) {
    auto op = store.read_operation(id);
    if (!op)
        return std::nullopt;
    return store.read_view(op->view);
}

static void merge_view_into(View& dst, const View& src) {
    for (const auto& head : src.heads)
        add_unique_head(dst, head);
    for (const auto& bookmark : src.bookmarks) {
        const auto found = find_bookmark(dst, bookmark.name);
        if (!found) {
            dst.bookmarks.push_back(bookmark);
            continue;
        }
        auto& existing = dst.bookmarks[*found];
        std::optional<Id> a =
            existing.targets.adds.empty() ? std::optional<Id>{} : existing.targets.adds.front();
        std::optional<Id> b =
            bookmark.targets.adds.empty() ? std::optional<Id>{} : bookmark.targets.adds.front();
        const bool same = a.has_value() == b.has_value() && (!a || id_equal(*a, *b));
        if (!same || existing.targets.adds.size() != bookmark.targets.adds.size()) {
            existing.targets.adds = {a, b};
            existing.targets.removes = {std::nullopt};
        }
    }
    for (const auto& tag : src.tags) {
        if (!find_tag(dst, tag.name))
            dst.tags.push_back(tag);
    }
    for (const auto& workspace : src.working_copies) {
        bool found = false;
        for (const auto& existing : dst.working_copies) {
            if (existing.workspace == workspace.workspace) {
                found = true;
                break;
            }
        }
        if (!found)
            dst.working_copies.push_back(workspace);
    }
}


Result<Txn> Txn::begin(const fs::path& root, Store& store) {
    Txn tx;
    tx.root_ = root;
    tx.store_ = &store;
    const auto heads = read_heads(root);
    if (heads.empty()) {
        tx.view_ = empty_view();
    } else if (heads.size() == 1) {
        auto view = load_view_for_head(store, heads.front());
        if (!view)
            return fail_io("cannot load repository state");
        tx.view_ = std::move(*view);
    } else {
        auto base = load_view_for_head(store, heads.front());
        if (!base)
            return fail_io("cannot load repository state");
        for (std::size_t i = 1; i < heads.size(); ++i) {
            auto extra = load_view_for_head(store, heads[i]);
            if (extra)
                merge_view_into(*base, *extra);
        }
        tx.view_ = std::move(*base);
    }
    std::stable_sort(tx.view_.bookmarks.begin(), tx.view_.bookmarks.end(),
                     [](const Bookmark& a, const Bookmark& b) {
                         return compare(bytes_of(a.name), bytes_of(b.name)) < 0;
                     });
    std::stable_sort(tx.view_.tags.begin(), tx.view_.tags.end(),
                     [](const TagRef& a, const TagRef& b) {
                         return compare(bytes_of(a.name), bytes_of(b.name)) < 0;
                     });
    std::stable_sort(tx.view_.working_copies.begin(), tx.view_.working_copies.end(),
                     [](const WorkspaceRef& a, const WorkspaceRef& b) {
                         return compare(bytes_of(a.workspace), bytes_of(b.workspace)) < 0;
                     });
    tx.parents_ = heads;
    tx.start_ms_ = unix_now_millis();
    return Result<Txn>(std::move(tx));
}

static std::string host_name() {
    if (const char* v = std::getenv("HOSTNAME"); v && *v)
        return v;
    return "localhost";
}

static std::string user_name() {
    if (const char* v = std::getenv("USER"); v && *v)
        return v;
#if defined(_WIN32)
    if (const char* w = std::getenv("USERNAME"); w && *w)
        return w;
#endif
    return "unknown";
}

Status Txn::finish(std::string_view description) {
    std::vector<ChainedOperation> operations;
    operations.push_back(ChainedOperation{view_, std::string(description)});
    return finish_chain(std::move(operations));
}

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();
        std::cout << "failed to write object pack\n";
        return fail_io("failed to write object pack");
    }
    if (!write_head(root_, last_op))
        return fail_io("failed to write operation head");
    for (const auto& parent : parents_)
        (void)delete_head(root_, parent);
    return {};
}


static fs::path native_path(const fs::path& root) {
    return git_map_dir(root) / "native";
}

bool mark_native(const fs::path& root, const Id& id) {
    const std::string line = hex_encode(id) + "\n";
    return append_file(native_path(root), bytes_of(line));
}

std::vector<Id> load_native(const fs::path& root) {
    std::vector<Id> out;
    auto data = read_file_opt(native_path(root));
    if (!data)
        return out;
    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());
    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();
        if (end - start >= 64) {
            Id id{};
            if (hex_decode(text.substr(start, 64), MutBytes(id.data(), id.size())))
                out.push_back(id);
        }
        if (end == text.size())
            break;
        start = end + 1;
    }
    return out;
}

bool is_native(const std::vector<Id>& native, const Id& id) {
    return contains_id(native, id);
}


std::optional<LoadedCommit> load_commit(Store& store, const Id& id) {
    auto body = store.read_body(id, TYPE_COMMIT);
    if (!body)
        return std::nullopt;
    auto commit = decode_commit(bytes_of(*body));
    if (!commit)
        return std::nullopt;
    return LoadedCommit{std::move(*commit), std::move(*body)};
}

bool has_changes(Store& store, const LoadedCommit& loaded) {
    if (!loaded.commit.parents.empty()) {
        auto parent = load_commit(store, loaded.commit.parents.front());
        if (!parent)
            return true;
        return !id_equal(parent->commit.root_tree, loaded.commit.root_tree);
    }
    const auto entries = flatten_tree(store, loaded.commit.root_tree);
    return !entries.empty();
}

std::vector<Id> collect_commits(Store& store, std::span<const Id> start) {
    std::vector<Id> out;
    std::vector<Id> stack;
    std::unordered_set<Id, IdHash, IdEq> seen;
    for (const auto& id : start) {
        if (seen.insert(id).second)
            stack.push_back(id);
    }
    while (!stack.empty()) {
        const Id id = stack.back();
        stack.pop_back();
        out.push_back(id);
        auto loaded = load_commit(store, id);
        if (!loaded)
            continue;
        for (const auto& parent : loaded->commit.parents) {
            if (seen.insert(parent).second)
                stack.push_back(parent);
        }
    }
    return out;
}

// Orders log nodes newest-first while keeping every child before its parents.
std::vector<std::size_t> order_log_nodes(const std::vector<LogOrderNode>& nodes) {
    std::unordered_map<Id, std::size_t, IdHash, IdEq> index;
    index.reserve(nodes.size());
    for (std::size_t i = 0; i < nodes.size(); ++i)
        index.emplace(nodes[i].id, i);

    std::vector<std::size_t> unemitted_children(nodes.size(), 0);
    for (const auto& node : nodes) {
        for (const auto& parent : node.parents) {
            const auto found = index.find(parent);
            if (found != index.end())
                ++unemitted_children[found->second];
        }
    }

    struct Ready {
        std::int64_t seconds = 0;
        std::size_t index = 0;
    };
    struct ReadyAfter {
        bool operator()(const Ready& a, const Ready& b) const {
            if (a.seconds != b.seconds)
                return a.seconds < b.seconds;
            return a.index > b.index;
        }
    };
    std::priority_queue<Ready, std::vector<Ready>, ReadyAfter> ready;
    for (std::size_t i = 0; i < nodes.size(); ++i) {
        if (unemitted_children[i] == 0)
            ready.push(Ready{nodes[i].seconds, i});
    }

    std::vector<std::size_t> order;
    order.reserve(nodes.size());
    std::vector<bool> emitted(nodes.size(), false);
    while (!ready.empty()) {
        const Ready next = ready.top();
        ready.pop();
        if (emitted[next.index])
            continue;
        emitted[next.index] = true;
        order.push_back(next.index);
        for (const auto& parent : nodes[next.index].parents) {
            const auto found = index.find(parent);
            if (found == index.end())
                continue;
            std::size_t& count = unemitted_children[found->second];
            if (count > 0)
                --count;
            if (count == 0)
                ready.push(Ready{nodes[found->second].seconds, found->second});
        }
    }
    for (std::size_t i = 0; i < nodes.size(); ++i) {
        if (!emitted[i])
            order.push_back(i);
    }
    return order;
}

std::vector<Id> view_roots(const View& view) {
    std::vector<Id> out;
    auto add = [&](const Id& id) {
        if (!contains_id(out, id))
            out.push_back(id);
    };
    for (const auto& head : view.heads)
        add(head);
    for (const auto& bookmark : view.bookmarks) {
        for (const auto& id : bookmark.targets.adds) {
            if (id)
                add(*id);
        }
    }
    for (const auto& tag : view.tags)
        add(tag.target);
    for (const auto& workspace : view.working_copies)
        add(workspace.target);
    return out;
}

std::vector<Id> all_commits(Store& store, const View& view) {
    const auto roots = view_roots(view);
    return collect_commits(store, roots);
}

static std::optional<Id> bookmark_target(const View& view, std::string_view name) {
    for (const auto& bookmark : view.bookmarks) {
        if (bookmark.name == name) {
            if (bookmark.targets.adds.size() == 1 && bookmark.targets.adds.front())
                return bookmark.targets.adds.front();
            return std::nullopt;
        }
    }
    return std::nullopt;
}

static std::optional<Id> tag_target(const View& view, std::string_view name) {
    for (const auto& tag : view.tags) {
        if (tag.name == name)
            return tag.target;
    }
    return std::nullopt;
}

static std::optional<Id> remote_target(const View& view, std::string_view text) {
    for (const auto& ref : view.remote_refs) {
        const std::string joined = ref.remote + "/" + ref.name;
        if (joined == text)
            return ref.target;
    }
    return std::nullopt;
}

static bool is_hex_char(char c) {
    return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}

static bool is_hex_prefix(std::string_view text) {
    if (text.size() < 4 || text.size() > 64)
        return false;
    for (char c : text) {
        if (!is_hex_char(c))
            return false;
    }
    return true;
}

// Change ids use a lowercase base32 alphabet. A path or an arbitrary word can
// be rejected without walking history, which keeps `vn diff <path>` cheap on
// large repositories.
static bool is_change_id_prefix(std::string_view text) {
    if (text.empty() || text.size() > 26)
        return false;
    for (char raw : text) {
        const char c = (raw >= 'A' && raw <= 'Z') ? static_cast<char>(raw + 32) : raw;
        if (!((c >= 'a' && c <= 'z') || (c >= '2' && c <= '7')))
            return false;
    }
    return true;
}

std::optional<Id> resolve_revision(Store& store, const View& view, std::string_view rev) {
    if (rev.empty() || rev == "@")
        return working_copy_id(view);
    if (auto id = bookmark_target(view, rev))
        return id;
    if (auto id = tag_target(view, rev))
        return id;
    if (auto id = remote_target(view, rev))
        return id;

    // A full commit hash can be checked directly. Walking every reachable
    // commit just to rediscover an exact hash made `vn diff <hash>` scale with
    // total history even though the answer was already addressable.
    if (rev.size() == ID_LEN * 2) {
        if (auto full = parse_id(rev)) {
            if (load_commit(store, *full))
                return full;
        }
        return std::nullopt;
    }

    const bool hex_prefix = is_hex_prefix(rev);
    const bool change_prefix = is_change_id_prefix(rev);
    if (!hex_prefix && !change_prefix)
        return std::nullopt;

    const auto ids = all_commits(store, view);
    std::vector<Id> matches;
    if (hex_prefix) {
        for (const auto& id : ids) {
            const std::string full = hex_encode(id);
            if (base32_prefix_matches(full, rev))
                matches.push_back(id);
        }
    }
    if (matches.empty() && change_prefix) {
        for (const auto& id : ids) {
            auto loaded = load_commit(store, id);
            if (!loaded)
                continue;
            const std::string encoded = base32_encode(loaded->commit.change_id);
            if (base32_prefix_matches(encoded, rev))
                matches.push_back(id);
        }
    }
    if (matches.size() == 1)
        return matches.front();
    return std::nullopt;
}


static void join_path(std::string& prefix, std::string_view name) {
    if (!prefix.empty())
        prefix.push_back('/');
    prefix.append(name);
}

static bool flatten_into(Store& store, const Id& tree_id, std::string& prefix,
                         std::vector<FlatEntry>& out, std::size_t depth) {
    if (depth > MAX_TREE_DEPTH)
        return false;
    auto body = store.read_body(tree_id, TYPE_TREE);
    if (!body)
        return false;
    auto tree = decode_tree(bytes_of(*body));
    if (!tree)
        return false;
    for (const auto& entry : tree->entries) {
        const std::size_t old_size = prefix.size();
        join_path(prefix, entry.name);
        if (entry.kind == KIND_SUBTREE) {
            if (!flatten_into(store, entry.target, prefix, out, depth + 1)) {
                prefix.resize(old_size);
                return false;
            }
            prefix.resize(old_size);
        } else {
            out.push_back(FlatEntry{prefix, entry.kind, entry.target});
            prefix.resize(old_size);
        }
    }
    return true;
}

std::vector<FlatEntry> flatten_tree(Store& store, const Id& tree_id) {
    std::vector<FlatEntry> out;
    std::string prefix;
    (void)flatten_into(store, tree_id, prefix, out, 0);
    std::stable_sort(out.begin(), out.end(), [](const FlatEntry& a, const FlatEntry& b) {
        return compare(bytes_of(a.path), bytes_of(b.path)) < 0;
    });
    return out;
}

Result<std::vector<FlatEntry>> flatten_tree_checked(Store& store, const Id& tree_id) {
    std::vector<FlatEntry> out;
    std::string prefix;
    if (!flatten_into(store, tree_id, prefix, out, 0))
        return fail(ErrorKind::Corrupt, 0);
    std::stable_sort(out.begin(), out.end(), [](const FlatEntry& a, const FlatEntry& b) {
        return compare(bytes_of(a.path), bytes_of(b.path)) < 0;
    });
    return Result<std::vector<FlatEntry>>(std::move(out));
}

std::vector<FlatEntry> flatten_or_empty(Store& store, std::optional<Id> tree_id) {
    if (!tree_id)
        return {};
    return flatten_tree(store, *tree_id);
}

const FlatEntry* find_flat(const std::vector<FlatEntry>& entries, std::string_view path) {
    std::size_t lo = 0;
    std::size_t hi = entries.size();
    while (lo < hi) {
        const std::size_t mid = lo + (hi - lo) / 2;
        const int c = compare(bytes_of(entries[mid].path), bytes_of(path));
        if (c == 0)
            return &entries[mid];
        if (c < 0)
            lo = mid + 1;
        else
            hi = mid;
    }
    return nullptr;
}

int find_tree_name(const Tree& tree, std::string_view name) {
    std::size_t lo = 0;
    std::size_t hi = tree.entries.size();
    while (lo < hi) {
        const std::size_t mid = lo + (hi - lo) / 2;
        const int c = compare(bytes_of(tree.entries[mid].name), bytes_of(name));
        if (c == 0)
            return static_cast<int>(mid);
        if (c < 0)
            lo = mid + 1;
        else
            hi = mid;
    }
    return -1;
}

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 > MAX_TREE_DEPTH)
        return true;
    auto body = store.read_body(tree_id, TYPE_TREE);
    if (!body)
        return true;
    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) {
            found = true;
            break;
        }
        if (entry.kind == KIND_SUBTREE && conflicted_into(store, entry.target, depth + 1)) {
            found = true;
            break;
        }
    }
    cache.emplace(tree_id, found);
    return found;
}

bool tree_conflicted(Store& store, const Id& tree_id) {
    return conflicted_into(store, tree_id, 0);
}

std::vector<TreeChange> compare_trees(Store& store, std::optional<Id> old_tree,
                                      std::optional<Id> new_tree) {
    if (!old_tree && !new_tree)
        return {};
    if (old_tree && new_tree && id_equal(*old_tree, *new_tree))
        return {};
    const auto old_entries = flatten_or_empty(store, old_tree);
    const auto new_entries = flatten_or_empty(store, new_tree);
    std::vector<TreeChange> out;
    std::size_t i = 0;
    std::size_t j = 0;
    while (i < old_entries.size() || j < new_entries.size()) {
        int take = 0;
        if (i >= old_entries.size())
            take = 1;
        else if (j >= new_entries.size())
            take = -1;
        else
            take = compare(bytes_of(old_entries[i].path), bytes_of(new_entries[j].path));
        if (take < 0) {
            out.push_back(TreeChange{old_entries[i].path, old_entries[i].kind, KIND_MISSING,
                                     old_entries[i].target, std::nullopt});
            ++i;
        } else if (take > 0) {
            out.push_back(TreeChange{new_entries[j].path, KIND_MISSING, new_entries[j].kind,
                                     std::nullopt, new_entries[j].target});
            ++j;
        } else {
            const auto& o = old_entries[i];
            const auto& n = new_entries[j];
            const bool same = o.kind == n.kind && id_equal(o.target, n.target);
            if (!same)
                out.push_back(TreeChange{o.path, o.kind, n.kind, o.target, n.target});
            ++i;
            ++j;
        }
    }
    return out;
}


static bool append_blob_data(Store& store, const Id& id, std::vector<std::uint8_t>& out,
                             std::size_t depth) {
    if (depth > 64)
        return false;
    if (is_lazy_blob(id)) {
        auto data = git_read_lazy_blob(store.root(), id);
        if (!data)
            return false;
        out.insert(out.end(), data->begin(), data->end());
        return true;
    }
    auto body = store.read_body(id, TYPE_BLOB);
    if (!body)
        return false;
    auto blob = decode_blob(bytes_of(*body));
    if (!blob)
        return false;
    if (blob->form == BlobForm::Inline) {
        out.insert(out.end(), blob->data.begin(), blob->data.end());
        return true;
    }
    if (blob->form == BlobForm::Leaf) {
        for (const auto& entry : blob->entries) {
            auto chunk = store.read_body(entry.id, TYPE_CHUNK);
            if (!chunk)
                return false;
            out.insert(out.end(), chunk->begin(), chunk->end());
        }
        return true;
    }
    for (const auto& entry : blob->entries) {
        if (!append_blob_data(store, entry.id, out, depth + 1))
            return false;
    }
    return true;
}

std::optional<std::vector<std::uint8_t>> read_blob(Store& store, const Id& id) {
    std::vector<std::uint8_t> out;
    if (!append_blob_data(store, id, out, 0))
        return std::nullopt;
    return out;
}


namespace {

struct FsckCtx {
    fs::path root;
    bool promisor = false;
    bool verbose = false;
    std::size_t errors = 0;
    std::size_t warnings = 0;
};

void fsck_report(FsckCtx& ctx, const fs::path& path, std::string_view text) {
    ++ctx.errors;
    error_prefix();
    std::cout << "fsck: " << path_display(path) << ": " << text << "\n";
}

void fsck_report_id(FsckCtx& ctx, const fs::path& path, std::string_view text, const Id& id) {
    ++ctx.errors;
    error_prefix();
    std::cout << "fsck: " << path_display(path) << ": " << text << " " << hex_encode(id) << "\n";
}

void fsck_warn(FsckCtx& ctx, const fs::path& path, std::string_view text) {
    ++ctx.warnings;
    if (ctx.verbose) {
        warning_prefix();
        std::cout << "fsck: " << path_display(path) << ": " << text << "\n";
    }
}

void fsck_report_decode(FsckCtx& ctx, const fs::path& path, std::string_view what,
                        const Error& error) {
    ++ctx.errors;
    error_prefix();
    std::cout << "fsck: " << path_display(path) << ": invalid " << what << " at byte "
              << error.offset << ": " << error_kind_name(error.kind) << "\n";
}

bool check_format(FsckCtx& ctx) {
    const fs::path path = format_path(ctx.root);
    auto data = read_file_opt(path);
    if (!data) {
        fsck_report(ctx, ctx.root, "missing .veins/format");
        return false;
    }
    const std::string expected = store_format_text();
    bool ok = equals(bytes_of(*data), bytes_of(expected));
    if (!ok && data->size() == expected.size() + 1) {
        ok = equals(bytes_of(*data).first(expected.size()), bytes_of(expected)) &&
             (*data)[expected.size()] == '\n';
    }
    if (!ok) {
        fsck_report(ctx, ctx.root, "unsupported .veins/format");
        return false;
    }
    return true;
}

std::uint8_t expected_type_for_value(std::uint8_t kind) {
    if (kind == 1 || kind == 2 || kind == 3)
        return TYPE_BLOB;
    if (kind == 4)
        return TYPE_TREE;
    if (kind == 6)
        return TYPE_CONFLICT;
    return 0;
}

bool check_ref(FsckCtx& ctx, Store& store, const fs::path& path, const Id& id,
               std::uint8_t expected, std::string_view what) {
    if (expected == TYPE_BLOB && is_lazy_blob(id))
        return true;
    const auto loc = store.find(id);
    if (!loc) {
        const bool promised = ctx.promisor && (expected == TYPE_CHUNK || expected == TYPE_BLOB);
        if (promised)
            fsck_warn(ctx, path, "missing promised object");
        if (!promised) {
            ++ctx.errors;
            error_prefix();
            std::cout << "fsck: " << path_display(path) << ": missing " << what << " object "
                      << hex_encode(id) << "\n";
        }
        return promised;
    }
    if (loc->kind != expected) {
        ++ctx.errors;
        error_prefix();
        std::cout << "fsck: " << path_display(path) << ": object has type " << type_name(loc->kind)
                  << ", expected " << type_name(expected) << " " << hex_encode(id) << "\n";
        return false;
    }
    return true;
}

void check_blob_refs(FsckCtx& ctx, Store& store, const fs::path& path, const Blob& blob) {
    if (blob.form == BlobForm::Inline)
        return;
    const std::uint8_t expected = blob.form == BlobForm::Leaf ? TYPE_CHUNK : TYPE_BLOB;
    for (const auto& entry : blob.entries) {
        (void)check_ref(ctx, store, path, entry.id, expected, "blob");
    }
}

void check_tree_refs(FsckCtx& ctx, Store& store, const fs::path& path, const Tree& tree) {
    for (const auto& entry : tree.entries) {
        std::uint8_t expected = 0;
        if (entry.kind == KIND_FILE || entry.kind == KIND_EXECUTABLE || entry.kind == KIND_SYMLINK)
            expected = TYPE_BLOB;
        else if (entry.kind == KIND_SUBTREE)
            expected = TYPE_TREE;
        else if (entry.kind == KIND_CONFLICT)
            expected = TYPE_CONFLICT;
        if (expected != 0)
            (void)check_ref(ctx, store, path, entry.target, expected, "tree");
    }
}

void check_conflict_refs(FsckCtx& ctx, Store& store, const fs::path& path,
                         const Conflict& conflict) {
    for (const auto& value : conflict.adds) {
        const std::uint8_t expected = expected_type_for_value(value.kind);
        if (expected != 0 && value.target)
            (void)check_ref(ctx, store, path, *value.target, expected, "conflict");
    }
    for (const auto& value : conflict.removes) {
        const std::uint8_t expected = expected_type_for_value(value.kind);
        if (expected != 0 && value.target)
            (void)check_ref(ctx, store, path, *value.target, expected, "conflict");
    }
}

void check_commit_refs(FsckCtx& ctx, Store& store, const fs::path& path, const Commit& commit) {
    for (const auto& parent : commit.parents)
        (void)check_ref(ctx, store, path, parent, TYPE_COMMIT, "parent commit");
    (void)check_ref(ctx, store, path, commit.root_tree, TYPE_TREE, "root tree");
}

void check_operation_refs(FsckCtx& ctx, Store& store, const fs::path& path, const Operation& op) {
    for (const auto& parent : op.parents)
        (void)check_ref(ctx, store, path, parent, TYPE_OPERATION, "parent operation");
    (void)check_ref(ctx, store, path, op.view, TYPE_VIEW, "view");
}

void check_view_refs(FsckCtx& ctx, Store& store, const fs::path& path, const View& view) {
    for (const auto& head : view.heads)
        (void)check_ref(ctx, store, path, head, TYPE_COMMIT, "head commit");
    for (const auto& bookmark : view.bookmarks) {
        for (const auto& id : bookmark.targets.adds) {
            if (id)
                (void)check_ref(ctx, store, path, *id, TYPE_COMMIT, "bookmark");
        }
        for (const auto& id : bookmark.targets.removes) {
            if (id)
                (void)check_ref(ctx, store, path, *id, TYPE_COMMIT, "bookmark");
        }
    }
    for (const auto& tag : view.tags)
        (void)check_ref(ctx, store, path, tag.target, TYPE_COMMIT, "tag");
    for (const auto& ref : view.remote_refs)
        (void)check_ref(ctx, store, path, ref.target, TYPE_COMMIT, "remote ref");
    for (const auto& workspace : view.working_copies)
        (void)check_ref(ctx, store, path, workspace.target, TYPE_COMMIT, "working copy");
}

void check_object(FsckCtx& ctx, Store& store, const fs::path& path, const Id& id, std::uint8_t kind,
                  Bytes body) {
    const Id computed = object_id(kind, body);
    if (!id_equal(computed, id)) {
        fsck_report_id(ctx, path, "hash mismatch for", id);
        return;
    }
    switch (kind) {
    case TYPE_CHUNK:
        if (body.empty() || body.size() > MAX_CHUNK_LEN)
            fsck_report_id(ctx, path, "invalid chunk length for", id);
        return;
    case TYPE_BLOB: {
        auto blob = decode_blob(body);
        if (!blob) {
            fsck_report_decode(ctx, path, "blob", blob.error());
            return;
        }
        check_blob_refs(ctx, store, path, *blob);
        return;
    }
    case TYPE_TREE: {
        auto tree = decode_tree(body);
        if (!tree) {
            fsck_report_decode(ctx, path, "tree", tree.error());
            return;
        }
        check_tree_refs(ctx, store, path, *tree);
        return;
    }
    case TYPE_CONFLICT: {
        auto conflict = decode_conflict(body);
        if (!conflict) {
            fsck_report_decode(ctx, path, "conflict", conflict.error());
            return;
        }
        check_conflict_refs(ctx, store, path, *conflict);
        return;
    }
    case TYPE_COMMIT: {
        auto commit = decode_commit(body);
        if (!commit) {
            fsck_report_decode(ctx, path, "commit", commit.error());
            return;
        }
        check_commit_refs(ctx, store, path, *commit);
        return;
    }
    case TYPE_OPERATION: {
        auto op = decode_operation(body);
        if (!op) {
            fsck_report_decode(ctx, path, "operation", op.error());
            return;
        }
        check_operation_refs(ctx, store, path, *op);
        return;
    }
    case TYPE_VIEW: {
        auto view = decode_view(body);
        if (!view) {
            fsck_report_decode(ctx, path, "view", view.error());
            return;
        }
        check_view_refs(ctx, store, path, *view);
        return;
    }
    default:
        return;
    }
}

} // namespace

static void check_op_log(FsckCtx& ctx, Store& store) {
    const fs::path dir = op_heads_dir(ctx.root);
    if (!path_is_dir(dir)) {
        fsck_report(ctx, dir, "missing op-heads directory");
        return;
    }
    std::vector<Id> frontier;
    for (const auto& name : list_directory(dir)) {
        if (name.size() != 64) {
            fsck_report(ctx, dir, "op-heads entry is not a 64-character id");
            continue;
        }
        Id id{};
        if (!hex_decode(name, MutBytes(id.data(), id.size()))) {
            fsck_report(ctx, dir, "op-heads entry is not hexadecimal");
            continue;
        }
        frontier.push_back(id);
    }
    std::unordered_set<Id, IdHash, IdEq> seen;
    while (!frontier.empty()) {
        const Id id = frontier.back();
        frontier.pop_back();
        if (!seen.insert(id).second)
            continue;
        const auto loc = store.find(id);
        if (!loc) {
            fsck_report_id(ctx, dir, "operation head or parent is missing:", id);
            continue;
        }
        if (loc->kind != TYPE_OPERATION) {
            fsck_report_id(ctx, dir, "op-log entry is not an operation:", id);
            continue;
        }
        auto body = store.get(*loc);
        if (!body) {
            fsck_report_decode(ctx, dir, "operation", body.error());
            continue;
        }
        auto op = decode_operation(bytes_of(*body));
        if (!op) {
            fsck_report_decode(ctx, dir, "operation", op.error());
            continue;
        }
        for (const auto& parent : op->parents)
            frontier.push_back(parent);
        (void)check_ref(ctx, store, dir, op->view, TYPE_VIEW, "operation view");
    }
}

int fsck_repository(const fs::path& root, bool verbose) {
    FsckCtx ctx;
    ctx.root = root;
    ctx.verbose = verbose;
    std::vector<StoreHandle> handles;
    if (check_format(ctx)) {
        auto cfg = read_file_opt(config_path(root));
        if (cfg) {
            const std::string_view text(reinterpret_cast<const char*>(cfg->data()), cfg->size());
            ctx.promisor = text.find("promisor") != std::string_view::npos;
        }
        const fs::path dir = packs_dir(root);
        if (!path_is_dir(dir)) {
            fsck_report(ctx, dir, "missing store/packs directory");
        } else {
            const auto names = list_directory(dir);
            for (const auto& name : names) {
                if (name.size() > 5 && name.compare(name.size() - 5, 5, ".vidx") == 0) {
                    std::string pack_name = name.substr(0, name.size() - 5) + ".vpack";
                    const fs::path ppath = dir / path_from_bytes(pack_name);
                    if (!path_is_file(ppath))
                        fsck_report(ctx, ppath, "index has no pack");
                }
            }
            for (const auto& name : names) {
                if (name.size() <= 6 || name.compare(name.size() - 6, 6, ".vpack") != 0)
                    continue;
                const fs::path ppath = dir / path_from_bytes(name);
                auto pdata = read_file_opt(ppath);
                if (!pdata) {
                    fsck_report(ctx, ppath, "cannot read pack");
                    continue;
                }
                auto pack = decode_pack(std::move(*pdata));
                if (!pack) {
                    fsck_report_decode(ctx, ppath, "pack", pack.error());
                    continue;
                }
                std::string base = name.substr(0, name.size() - 6);
                const fs::path ipath = dir / path_from_bytes(base + ".vidx");
                auto idata = read_file_opt(ipath);
                if (!idata) {
                    fsck_report(ctx, ppath, "pack has no index");
                    continue;
                }
                auto index = decode_index(std::move(*idata), pack->trailer);
                if (!index) {
                    fsck_report_decode(ctx, ipath, "index", index.error());
                    continue;
                }
                bool eligible = true;
                if (index->ids.size() != pack->records.size()) {
                    fsck_report(ctx, ppath, "pack and index object counts differ");
                    eligible = false;
                }
                if (eligible) {
                    std::vector<bool> visited(pack->records.size(), false);
                    for (std::size_t j = 0; j < index->ids.size(); ++j) {
                        const auto rec = pack->find_by_offset(index->offsets[j]);
                        if (!rec) {
                            fsck_report_id(ctx, ppath, "index offset names no record for",
                                           index->ids[j]);
                            eligible = false;
                            continue;
                        }
                        if (!id_equal(pack->records[*rec].id, index->ids[j])) {
                            fsck_report_id(ctx, ppath, "index id does not match record for",
                                           index->ids[j]);
                            eligible = false;
                        }
                        if (visited[*rec]) {
                            fsck_report_id(ctx, ppath, "record indexed more than once",
                                           index->ids[j]);
                            eligible = false;
                        }
                        visited[*rec] = true;
                    }
                    for (std::size_t k = 0; k < pack->records.size(); ++k) {
                        if (!visited[k]) {
                            fsck_report_id(ctx, ppath, "record is not indexed",
                                           pack->records[k].id);
                            eligible = false;
                        }
                    }
                }
                if (!eligible)
                    continue;
                StoreHandle handle;
                handle.path = ppath;
                handle.index = std::move(*index);
                handle.pack = std::move(*pack);
                handles.push_back(std::move(handle));
            }
        }

        Store store;
        store.handles() = std::move(handles);
        for (auto& handle : store.handles()) {
            if (!handle.pack)
                continue;
            for (std::size_t j = 0; j < handle.pack->records.size(); ++j) {
                const auto& rec = handle.pack->records[j];
                auto body = handle.pack->get(j);
                if (!body) {
                    fsck_report_decode(ctx, handle.path, "record", body.error());
                    continue;
                }
                check_object(ctx, store, handle.path, rec.id, rec.type, bytes_of(*body));
            }
        }
        check_op_log(ctx, store);
    }

    if (ctx.warnings > 0 && ctx.verbose) {
        warning_prefix();
        std::cout << ctx.warnings << " warning(s)\n";
    }
    if (ctx.errors == 0) {
        info_prefix();
        std::cout << "fsck: clean\n";
        return 0;
    }
    error_prefix();
    std::cout << ctx.errors << " error(s)\n";
    return 1;
}

} // namespace vn