navid/veins / commit

28d6bd8b6446

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

parents: 3fcc3c75bd9f

Browse files at this commit · Download source

store: various optimizations
--- a/.vnexclude+++ b/.vnexclude@@ -8,3 +8,4 @@ compare_impls.py BENCH_RS_CPP.json BENCH_RS_CPP.md+xveins/gmon.out--- a/xveins/src/store/store.cpp+++ b/xveins/src/store/store.cpp@@ -195,10 +195,42 @@     return ctx; } +ZSTD_CCtx* thread_compress_context() {+    thread_local ZSTD_CCtx* ctx = ZSTD_createCCtx();+    return ctx;+}++struct BodyView {+    const std::uint8_t* data = nullptr;+    std::size_t size = 0;+};++// Reusable, uninitialised scratch storage. One buffer per delta-chain depth so+// a nested decode can keep its base body alive while the caller decompresses.+struct PackScratch {+    std::vector<std::unique_ptr<std::uint8_t[]>> buffers;+    std::vector<std::size_t> capacities;++    std::uint8_t* buffer(int depth, std::size_t need) {+        const auto level = static_cast<std::size_t>(depth);+        if (buffers.size() <= level) {+            buffers.resize(level + 1);+            capacities.resize(level + 1, 0);+        }+        if (capacities[level] < need) {+            buffers[level] = std::make_unique_for_overwrite<std::uint8_t[]>(need);+            capacities[level] = need;+        }+        return buffers[level].get();+    }+};+ } // namespace -static Result<std::vector<std::uint8_t>> pack_get(const Pack& pack, std::size_t record_index,-                                                  int depth) {+// Decodes a pack record into scratch memory without allocating or zero-filling+// a buffer per object. Callers that need ownership copy the returned view.+static Result<BodyView> pack_view(const Pack& pack, std::size_t record_index, int depth,+                                  PackScratch& scratch) {     if (record_index >= pack.records.size())         return fail(ErrorKind::Corrupt, 0);     if (depth > 32)@@ -206,23 +238,20 @@     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>{};+        return BodyView{};     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 == 0)+        return BodyView{pack.data.data() + 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);+        std::uint8_t* out = scratch.buffer(depth, raw_len);+        const std::size_t n = ZSTD_decompressDCtx(thread_decompress_context(), out, raw_len,+                                                  pack.data.data() + off, stored_len);         if (ZSTD_isError(n) || n != raw_len)             return fail(ErrorKind::Corrupt, off);-        return out;+        return BodyView{out, raw_len};     }     if (rec.compression != 2)         return fail(ErrorKind::InvalidValue, off);@@ -240,20 +269,26 @@     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);+    auto base_body = pack_view(pack, *base_index, depth + 1, scratch);     if (!base_body)         return unexpected(base_body.error());-    std::vector<std::uint8_t> out(raw_len);+    std::uint8_t* out = scratch.buffer(depth, 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());+        ZSTD_decompress_usingDict(thread_decompress_context(), out, 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;+    return BodyView{out, raw_len}; }  Result<std::vector<std::uint8_t>> Pack::get(std::size_t record_index) const {-    return pack_get(*this, record_index, 0);+    PackScratch scratch;+    auto body = pack_view(*this, record_index, 0, scratch);+    if (!body)+        return unexpected(body.error());+    if (body->size == 0)+        return std::vector<std::uint8_t>{};+    return std::vector<std::uint8_t>(body->data, body->data + body->size); }  static std::size_t pack_type_limit(std::uint8_t type) {@@ -464,9 +499,16 @@ static std::vector<std::uint8_t> zstd_compress(Bytes data, int level) {     if (data.empty())         return {};+    ZSTD_CCtx* ctx = thread_compress_context();+    if (!ctx)+        return {};+    ZSTD_CCtx_reset(ctx, ZSTD_reset_session_only);+    if (ZSTD_isError(ZSTD_CCtx_setParameter(ctx, ZSTD_c_compressionLevel, level)))+        return {};+    (void)ZSTD_CCtx_setParameter(ctx, ZSTD_c_checksumFlag, 0);     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);+    const std::size_t n = ZSTD_compress2(ctx, out.data(), bound, data.data(), data.size());     if (ZSTD_isError(n) || n >= data.size())         return {};     out.resize(n);@@ -528,6 +570,11 @@     std::uint64_t length = 0; }; +// Candidate base selection only needs relative sizes, so probe at a cheap+// level and re-compress the winner at the requested level. The frames that end+// up in the pack are always produced at `level`.+static int probe_level(int level) { return level > 1 ? 1 : level; }+ // 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@@ -658,8 +705,8 @@                     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))+                    if (!zstd_compress_dict(body, bytes_of(pending[base_index].object->body),+                                            probe_level(level), frame))                         continue;                     best = std::min(best, frame.size() + 10);                 }@@ -792,7 +839,6 @@             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 ||@@ -812,20 +858,25 @@                                      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))+                std::vector<std::uint8_t> probe;+                if (!zstd_compress_dict(target_body, bytes_of(base.object->body),+                                        probe_level(level), probe))                     continue;-                const std::size_t framed = frame.size() + 10;+                const std::size_t framed = probe.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);+                std::vector<std::uint8_t> frame;+                if (zstd_compress_dict(target_body,+                                       bytes_of(pending[best_base].object->body), level, frame) &&+                    frame.size() + 10 < solo) {+                    target.base = best_base;+                    target.compression = 2;+                    target.compressed = std::move(frame);+                }             }         }     }@@ -1003,6 +1054,7 @@     std::vector<RawObject> objects;     std::set<Id> seen;     std::uint64_t before = 0;+    PackScratch scratch;     auto names = list_directory(source_dir);     std::sort(names.begin(), names.end());     for (const auto& name : names) {@@ -1028,7 +1080,7 @@             const auto& record = pack->records[i];             if (!seen.insert(record.id).second)                 continue;-            auto body = pack->get(i);+            auto body = pack_view(*pack, i, 0, scratch);             if (!body) {                 error_prefix();                 std::cout << "cannot read object " << hex_encode(Bytes(record.id.data(), ID_LEN))@@ -1035,7 +1087,10 @@                           << "\n";                 return 1;             }-            objects.push_back(RawObject{record.type, std::move(*body), record.id});+            std::vector<std::uint8_t> owned;+            if (body->size > 0)+                owned.assign(body->data, body->data + body->size);+            objects.push_back(RawObject{record.type, std::move(owned), record.id});         }     }     if (objects.empty()) {@@ -1219,6 +1274,29 @@ #endif } +// Zero-copy variant of read_handle_range: returns a view into the mapping when+// one is available, otherwise falls back to a pread into `scratch`.+static std::optional<Bytes> handle_view(StoreHandle& handle, std::uint64_t offset,+                                        std::size_t length, std::vector<std::uint8_t>& scratch) {+    if (static_cast<std::uint64_t>(length) > MAX_STORE_PACK_BYTES)+        return std::nullopt;+#if !defined(_WIN32)+    std::size_t mapped_len = 0;+    if (const void* mapped = handle_mapping(handle, mapped_len)) {+        if (offset >= mapped_len)+            return Bytes{};+        const std::size_t available = static_cast<std::size_t>(+            std::min<std::uint64_t>(length, mapped_len - offset));+        return Bytes(static_cast<const std::uint8_t*>(mapped) + offset, available);+    }+#endif+    auto data = read_handle_range(handle, offset, length);+    if (!data)+        return std::nullopt;+    scratch = std::move(*data);+    return Bytes(scratch.data(), scratch.size());+}+ static bool handle_index(StoreHandle& handle) {     if (handle.index)         return true;@@ -1324,10 +1402,11 @@  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);+    std::vector<std::uint8_t> scratch;+    auto header = handle_view(handle, offset, 96, scratch);     if (!header || header->size() < 34)         return std::nullopt;-    Reader r(bytes_of(*header));+    Reader r(*header);     const auto id = r.id();     const auto type = r.u8();     const auto compression = r.u8();@@ -1392,16 +1471,18 @@ 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));+    std::vector<std::uint8_t> scratch;+    auto stored = handle_view(handle, loc.data_offset, static_cast<std::size_t>(loc.stored_len),+                              scratch);     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);+        return std::vector<std::uint8_t>(stored->begin(), stored->end());     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());+        const std::size_t n = ZSTD_decompressDCtx(thread_decompress_context(), out.data(), raw_len,+                                                  stored->data(), stored->size());         if (ZSTD_isError(n) || n != raw_len)             return fail(ErrorKind::Corrupt, loc.data_offset);         return out;@@ -1408,7 +1489,7 @@     }     if (loc.compression != 2)         return fail(ErrorKind::InvalidValue, loc.data_offset);-    Reader header(bytes_of(*stored));+    Reader header(*stored);     const auto base_off = header.varint();     if (!base_off || *base_off >= loc.record_offset)         return fail(ErrorKind::Corrupt, loc.data_offset);@@ -2793,17 +2874,19 @@          Store store;         store.handles() = std::move(handles);+        PackScratch scratch;         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);+                auto body = pack_view(*handle.pack, j, 0, scratch);                 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));+                const Bytes body_bytes = body->size == 0 ? Bytes{} : Bytes(body->data, body->size);+                check_object(ctx, store, handle.path, rec.id, rec.type, body_bytes);             }         }         check_op_log(ctx, store);