navid/veins / commit

ab00d535906a

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

parents: 2adfcb3ebdd7

Browse files at this commit · Download source

all: optimizations to store size
--- a/docs/SPECIFICATION_V1.adoc+++ b/docs/SPECIFICATION_V1.adoc@@ -39,7 +39,7 @@ === Non-goals  * Replacing git as an ecosystem. Pull requests, issues, and CI remain git-hosted, and veins interoperates with them through the bridge.-* Delta compression. veins trades some store size for random access and fast reads (see <<sec-perf,Performance requirements>>).+* General delta compression across unrelated objects. veins uses only bounded-depth chunk deltas between successive versions of the same file, so random access stays predictable (see <<sec-pack-deltas>>). * Semantic (AST-level) merging in v1. The merge engine is designed so a structural layer can be added later. * User accounts, passwords, groups, per-bookmark or per-path permissions, or other hosting features in the server. Access control in v1 is per repository and per key (see <<sec-auth,Authentication and authorization>>). * Multi-writer concurrency beyond what the operation log provides (see <<sec-oplog,Operation log>>).@@ -382,7 +382,7 @@  === Pack files -veins has no loose objects and no deltas. Objects are stored in pack files that are written once and never modified.+veins has no loose objects. Objects are stored in pack files that are written once and never modified.  [source,text] ----@@ -396,15 +396,33 @@ record:   id        object ID (32 bytes)   u8        type_byte-  u8        compression (0 = none, 1 = zstd)+  u8        compression (0 = none, 1 = zstd, 2 = zstd delta)   varint    raw_length   varint    stored_length   bytes     stored data (stored_length bytes, no length prefix) ---- -Each record is compressed independently, so any object can be read with one seek and one decompression. Chunks SHOULD be compressed with zstd (level 3 by default). Records that do not shrink SHOULD be stored uncompressed.+Records with compression 0 or 1 are read with one seek and one decompression. Chunks SHOULD be compressed with zstd (level 3 by default). Records that do not shrink SHOULD be stored uncompressed. -Records carry their IDs, so an index can be rebuilt by scanning headers without decompressing or rehashing. This is why there is no "resolving deltas" phase.+Records carry their IDs, so an index can be rebuilt by scanning headers without decompressing or rehashing. Records with compression 2 add a bounded number of base lookups, not a git-style walk of an unbounded delta chain.++[[sec-pack-deltas]]+==== Delta records++Compression 2 stores a zstd frame whose dictionary is another record's raw body:++[source,text]+----+compression 2 payload:+  varint    base_record_offset+  bytes     zstd frame, dictionary = raw body of the base record+----++`raw_length` is the length of the reconstructed object. `base_record_offset` MUST point at a record earlier in the same pack; offsets therefore decrease strictly and cycles are impossible. All object IDs and hashes are computed over the reconstructed body, so a delta record is transparent above the pack layer.++Writers SHOULD use delta records only for chunks, against the chunk at the corresponding position in a previous version of the same file. Writers MUST bound chain depth with a small constant. The reference implementation caps chains at 4 links and stores deeper objects independently, so reading a chunk costs at most five dictionary decompressions.++Readers MUST accept records compressed with 0, 1, and 2. A reader MUST also cap the number of links it follows (the reference implementation uses 32 as a safety limit). A pack written before delta records were introduced contains only 0 and 1 and MUST remain readable. Implementations that predate compression 2 MUST reject such a pack as unsupported rather than returning wrong bytes.  === Index files @@ -439,6 +457,8 @@  * When more than 32 packs exist, the implementation SHOULD merge small packs into a larger one. Merging writes a new pack and index before deleting the sources. * `vn gc` computes the set of objects reachable from every operation in the operation log that has not been expired, and rewrites packs to drop everything else. The default expiry for operations is 90 days (configurable). Unreachable objects younger than 24 hours MUST NOT be deleted, to protect in-flight writes.+* `vn repack` rewrites every indexed pack into one delta-compressed pack. It preserves every object and does not expire operations. The reference implementation provides `vn gc` as an alias for this conservative repack until operation expiry is implemented.+* Repacking MUST write the new pack and index before deleting the source packs, and MUST NOT delete promised-object records. It MUST take the repository lock. * gc MUST NOT delete promised-object records, and MUST take the repository lock.  === Promised objects@@ -1124,7 +1144,7 @@ | `vn key generate\|list\|show\|import` | Manage client keys. | `vn access add\|list\|remove\|anonymous` | Manage a served repository's access file (server side, local only). | `vn whoami [<remote>]` | Report the role and key fingerprint the server grants.-| `vn fsck [-verbose]`, `vn gc` | Verification and garbage collection.+| `vn fsck [-verbose]`, `vn repack [-level:<n>]`, `vn gc` | Verification, pack compaction, and garbage collection. | `vn config`, `vn cfg` | Read and write configuration. | `vn help [<command>]`, `vn -help`, `vn version`, `vn -version` | Show usage or version information. |===@@ -1166,7 +1186,7 @@ | P5 | `vn status` with an unchanged working copy of 100,000 files SHOULD complete within 200 ms (warm cache). | P6 | Exporting one new commit to git SHOULD complete within 1 s (excluding the network). | P7 | Checkout of a large file MUST use bounded memory (chunk-sized buffers).-| P8 | Store size on W1 SHOULD be no more than 2x that of the same history in an aggressively repacked git repository. This is a soft target. Chunking compresses less well than delta chains. This trade-off is accepted.+| P8 | Store size on W1 SHOULD be no more than 2x that of the same history in an aggressively repacked git repository. Delta-compressed chunks recover most of git's delta benefit while preserving random access; bounded chains keep the read cost constant. |===  *Go/no-go gate.* At milestone M1 (see <<sec-milestones,Milestones>>), measure P2 on W1 and W2. If veins is less than 2x faster than git on the clone of W1, stop and reconsider the design (or use jj with a tuned git repack) before building further.--- a/docs/SPECIFICATION_V1.html+++ b/docs/SPECIFICATION_V1.html@@ -472,7 +472,11 @@ <li><a href="#sec-storage">4. Storage</a> <ul class="sectlevel2"> <li><a href="#_repository_layout">4.1. Repository layout</a></li>-<li><a href="#_pack_files">4.2. Pack files</a></li>+<li><a href="#_pack_files">4.2. Pack files</a>+<ul class="sectlevel3">+<li><a href="#sec-pack-deltas">4.2.1. Delta records</a></li>+</ul>+</li> <li><a href="#_index_files">4.3. Index files</a></li> <li><a href="#_writing_and_durability">4.4. Writing and durability</a></li> <li><a href="#_reading_and_verification">4.5. Reading and verification</a></li>@@ -653,7 +657,7 @@ <p>Replacing git as an ecosystem. Pull requests, issues, and CI remain git-hosted, and veins interoperates with them through the bridge.</p> </li> <li>-<p>Delta compression. veins trades some store size for random access and fast reads (see <a href="#sec-perf">Performance requirements</a>).</p>+<p>General delta compression across unrelated objects. veins uses only bounded-depth chunk deltas between successive versions of the same file, so random access stays predictable (see <a href="#sec-pack-deltas">Delta records</a>).</p> </li> <li> <p>Semantic (AST-level) merging in v1. The merge engine is designed so a structural layer can be added later.</p>@@ -1387,7 +1391,7 @@ <div class="sect2"> <h3 id="_pack_files">4.2. Pack files</h3> <div class="paragraph">-<p>veins has no loose objects and no deltas. Objects are stored in pack files that are written once and never modified.</p>+<p>veins has no loose objects. Objects are stored in pack files that are written once and never modified.</p> </div> <div class="listingblock"> <div class="content">@@ -1401,7 +1405,7 @@ record:   id        object ID (32 bytes)   u8        type_byte-  u8        compression (0 = none, 1 = zstd)+  u8        compression (0 = none, 1 = zstd, 2 = zstd delta)   varint    raw_length   varint    stored_length   bytes     stored data (stored_length bytes, no length prefix)</code></pre>@@ -1408,12 +1412,34 @@ </div> </div> <div class="paragraph">-<p>Each record is compressed independently, so any object can be read with one seek and one decompression. Chunks SHOULD be compressed with zstd (level 3 by default). Records that do not shrink SHOULD be stored uncompressed.</p>+<p>Records with compression 0 or 1 are read with one seek and one decompression. Chunks SHOULD be compressed with zstd (level 3 by default). Records that do not shrink SHOULD be stored uncompressed.</p> </div> <div class="paragraph">-<p>Records carry their IDs, so an index can be rebuilt by scanning headers without decompressing or rehashing. This is why there is no "resolving deltas" phase.</p>+<p>Records carry their IDs, so an index can be rebuilt by scanning headers without decompressing or rehashing. Records with compression 2 add a bounded number of base lookups, not a git-style walk of an unbounded delta chain.</p> </div>+<div class="sect3">+<h4 id="sec-pack-deltas">4.2.1. Delta records</h4>+<div class="paragraph">+<p>Compression 2 stores a zstd frame whose dictionary is another record&#8217;s raw body:</p> </div>+<div class="listingblock">+<div class="content">+<pre class="rouge highlight"><code data-lang="text">compression 2 payload:+  varint    base_record_offset+  bytes     zstd frame, dictionary = raw body of the base record</code></pre>+</div>+</div>+<div class="paragraph">+<p><code>raw_length</code> is the length of the reconstructed object. <code>base_record_offset</code> MUST point at a record earlier in the same pack; offsets therefore decrease strictly and cycles are impossible. All object IDs and hashes are computed over the reconstructed body, so a delta record is transparent above the pack layer.</p>+</div>+<div class="paragraph">+<p>Writers SHOULD use delta records only for chunks, against the chunk at the corresponding position in a previous version of the same file. Writers MUST bound chain depth with a small constant. The reference implementation caps chains at 4 links and stores deeper objects independently, so reading a chunk costs at most five dictionary decompressions.</p>+</div>+<div class="paragraph">+<p>Readers MUST accept records compressed with 0, 1, and 2. A reader MUST also cap the number of links it follows (the reference implementation uses 32 as a safety limit). A pack written before delta records were introduced contains only 0 and 1 and MUST remain readable. Implementations that predate compression 2 MUST reject such a pack as unsupported rather than returning wrong bytes.</p>+</div>+</div>+</div> <div class="sect2"> <h3 id="_index_files">4.3. Index files</h3> <div class="listingblock">@@ -1478,6 +1504,12 @@ <p><code>vn gc</code> computes the set of objects reachable from every operation in the operation log that has not been expired, and rewrites packs to drop everything else. The default expiry for operations is 90 days (configurable). Unreachable objects younger than 24 hours MUST NOT be deleted, to protect in-flight writes.</p> </li> <li>+<p><code>vn repack</code> rewrites every indexed pack into one delta-compressed pack. It preserves every object and does not expire operations. The reference implementation provides <code>vn gc</code> as an alias for this conservative repack until operation expiry is implemented.</p>+</li>+<li>+<p>Repacking MUST write the new pack and index before deleting the source packs, and MUST NOT delete promised-object records. It MUST take the repository lock.</p>+</li>+<li> <p>gc MUST NOT delete promised-object records, and MUST take the repository lock.</p> </li> </ul>@@ -1969,7 +2001,7 @@ <div class="sect2"> <h3 id="_path_policies">7.11. Path policies</h3> <div class="paragraph">-<p>A tracked <code>.vnmergedata</code> file assigns merge behavior to paths, with one <code>glob attr=value</code> rule per line (later rules override earlier ones). <code>.veinsattributes</code> is not read. A tracked <code>.vnattribs</code> file classifies paths for generation, binary detection, and line-ending normalization using <code>glob attr...</code> rules; generated paths are excluded from <code>vn inf</code> unless <code>-inc-gen</code> is passed.</p>+<p>A tracked <code>.vnmergedata</code> file assigns merge behavior to paths, with one <code>glob attr=value</code> rule per line (later rules override earlier ones). <code>.veinsattributes</code> is not read.</p> </div> <table class="tableblock frame-all grid-all stretch"> <colgroup>@@ -1995,13 +2027,55 @@ <td class="tableblock halign-left valign-top"><p class="tableblock"><code>merge=regenerate</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">On conflict, take <code>ours</code>, record no conflict, and mark the path as <strong>needing regeneration</strong>.</p></td> </tr>+</tbody>+</table>+<div class="paragraph">+<p>A tracked <code>.vnattribs</code> file classifies paths for generation, binary detection, and line-ending normalization. Rules use <code>glob attr&#8230;&#8203;</code> syntax; later matching rules override individual attributes.</p>+</div>+<table class="tableblock frame-all grid-all stretch">+<colgroup>+<col style="width: 40%;">+<col style="width: 60%;">+</colgroup>+<thead> <tr>-<td class="tableblock halign-left valign-top"><p class="tableblock"><code>generated=true</code></p></td>-<td class="tableblock halign-left valign-top"><p class="tableblock">Informational (hides from review diffs by default).</p></td>+<th class="tableblock halign-left valign-top">Attribute</th>+<th class="tableblock halign-left valign-top">Meaning</th> </tr>+</thead>+<tbody>+<tr>+<td class="tableblock halign-left valign-top"><p class="tableblock"><code>gen</code> / <code>-gen</code></p></td>+<td class="tableblock halign-left valign-top"><p class="tableblock">Mark or unmark a path as generated. Generated files are excluded from <code>vn inf</code> totals unless <code>-inc-gen</code> is passed.</p></td>+</tr>+<tr>+<td class="tableblock halign-left valign-top"><p class="tableblock"><code>txt</code> / <code>bin</code></p></td>+<td class="tableblock halign-left valign-top"><p class="tableblock">Force text or binary classification.</p></td>+</tr>+<tr>+<td class="tableblock halign-left valign-top"><p class="tableblock"><code>eol:lf</code>, <code>eol:crlf</code>, <code>eol:cr</code></p></td>+<td class="tableblock halign-left valign-top"><p class="tableblock">Normalize a text file to LF in the store and write the requested ending on checkout.</p></td>+</tr>+<tr>+<td class="tableblock halign-left valign-top"><p class="tableblock"><code>-eol</code></p></td>+<td class="tableblock halign-left valign-top"><p class="tableblock">Clear an inherited EOL policy.</p></td>+</tr> </tbody> </table> <div class="paragraph">+<p>Example:</p>+</div>+<div class="listingblock">+<div class="content">+<pre class="rouge highlight"><code>*.c txt eol:lf+*.cmd txt eol:crlf+*.ssa gen+**/generated/* gen+*.bin bin+*.exe bin</code></pre>+</div>+</div>+<div class="paragraph"> <p>For <code>merge=regenerate</code>, <code>vn status</code> lists paths that need regeneration. If the local config defines <code>regenerate.&lt;glob&gt; = &lt;command&gt;</code>, <code>vn regenerate</code> runs that command and snapshots the result. A commit that contains a path still marked as needing regeneration triggers a warning. Commands are only read from local config (<code>.veins/config</code>), never from tracked files.</p> </div> <div class="admonitionblock note">@@ -2947,6 +3021,10 @@ <td class="tableblock halign-left valign-top"><p class="tableblock">Show history, newest first, flagging conflicted and divergent changes.</p></td> </tr> <tr>+<td class="tableblock halign-left valign-top"><p class="tableblock"><code>vn inf [-inc-gen]</code></p></td>+<td class="tableblock halign-left valign-top"><p class="tableblock">Show repository, language and author statistics; generated paths are excluded unless <code>-inc-gen</code> is passed.</p></td>+</tr>+<tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>vn show &lt;rev&gt;</code>, <code>vn diff [-rev &lt;rev&gt;]</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Display a commit or a diff.</p></td> </tr>@@ -3019,8 +3097,8 @@ <td class="tableblock halign-left valign-top"><p class="tableblock">Report the role and key fingerprint the server grants.</p></td> </tr> <tr>-<td class="tableblock halign-left valign-top"><p class="tableblock"><code>vn fsck [-verbose]</code>, <code>vn gc</code></p></td>-<td class="tableblock halign-left valign-top"><p class="tableblock">Verification and garbage collection.</p></td>+<td class="tableblock halign-left valign-top"><p class="tableblock"><code>vn fsck [-verbose]</code>, <code>vn repack [-level:&lt;n&gt;]</code>, <code>vn gc</code></p></td>+<td class="tableblock halign-left valign-top"><p class="tableblock">Verification, pack compaction, and garbage collection.</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>vn config</code>, <code>vn cfg</code></p></td>@@ -3125,7 +3203,7 @@ </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">P8</p></td>-<td class="tableblock halign-left valign-top"><p class="tableblock">Store size on W1 SHOULD be no more than 2x that of the same history in an aggressively repacked git repository. This is a soft target. Chunking compresses less well than delta chains. This trade-off is accepted.</p></td>+<td class="tableblock halign-left valign-top"><p class="tableblock">Store size on W1 SHOULD be no more than 2x that of the same history in an aggressively repacked git repository. Delta-compressed chunks recover most of git&#8217;s delta benefit while preserving random access; bounded chains keep the read cost constant.</p></td> </tr> </tbody> </table>@@ -3429,7 +3507,7 @@ <div id="footer"> <div id="footer-text"> Version 0.1-draft<br>-Last updated 2026-11-28 01:19:24 UTC+Last updated 2026-11-28 19:16:07 UTC </div> </div> </body>--- /dev/null+++ b/veins/src/worktree/attr_repro_main.sx@@ -0,0 +1,11 @@+val stdio = use("std/stdio")+val str = use("std/string")+val attr = use("attributes.sx")+pub fn main() i32 = trust {+    val rules: attr.Rules = attr.load(str.from_cstr(c"/tmp"))+    val item = @get(rules.items, 0)+    if item is some r {+        stdio.print("len={d} ptr={d}\n", {r.pattern.len as u64, r.pattern.ptr as u64})+    }+    return 0+}--- a/xveins/src/cli/cli.cpp+++ b/xveins/src/cli/cli.cpp@@ -1,16 +1,17 @@ #include "cli/cli.h"-#include "git/git.h" #include "cli/local_commands.h"-#include "merge/merge.h" #include "cli/net_commands.h"-#include "worktree/pathspec.h"+#include "git/git.h"+#include "merge/merge.h" #include "protocol/promisor.h" #include "store/store.h" #include "worktree/attributes.h"+#include "worktree/pathspec.h" #include "worktree/worktree.h"  #include <algorithm> #include <atomic>+#include <cstdlib> #include <cstring> #include <iostream> #include <map>@@ -186,10 +187,6 @@     return target.substr(0, len); } -// ----------------------------------------------------------------------------// Diff rendering-// ---------------------------------------------------------------------------- struct DiffOp {     char tag = ' ';     std::size_t ai = 0;@@ -503,10 +500,6 @@     return changes.size(); } -// ----------------------------------------------------------------------------// Commands-// ---------------------------------------------------------------------------- int run_init(const std::vector<std::string>& args) {     std::string path = ".";     std::optional<std::string> source;@@ -1748,6 +1741,47 @@     return fsck_repository(*root, verbose); } +int run_repack(const std::vector<std::string>& args) {+    std::string path = ".";+    bool verbose = false;+    int level = 6;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-v" || arg == "-verbose")) {+            verbose = true;+        } else if (!end_flags && arg.starts_with("-level:")) {+            const std::string value = arg.substr(7);+            if (value.empty()) {+                error_prefix();+                std::cout << "-level: requires a value (1-19)\n";+                return 1;+            }+            level = std::atoi(value.c_str());+            if (level < 1 || level > 19) {+                error_prefix();+                std::cout << "compression level must be between 1 and 19\n";+                return 1;+            }+        } else if (!end_flags && is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            path = arg;+        }+    }+    const auto root = discover_repo(path_from_bytes(path));+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository: " << path << "\n";+        return 1;+    }+    return repack_repository(*root, level, verbose);+}+ int run_self_test() {     auto fail = [](std::string_view why) {         error_prefix();@@ -1791,6 +1825,44 @@     if (decoded_index->ids.size() != 1)         return fail("index count"); +    std::vector<std::uint8_t> left(96 * 1024);+    for (std::size_t i = 0; i < left.size(); ++i)+        left[i] = static_cast<std::uint8_t>((i * 31 + (i / 97) * 7) % 251);+    std::vector<std::uint8_t> right = left;+    for (std::size_t i = 48 * 1024; i < 48 * 1024 + 64; ++i)+        right[i] = static_cast<std::uint8_t>((right[i] + 19) % 251);+    std::vector<RawObject> delta_objects;+    auto append_version = [&](const std::vector<std::uint8_t>& data) {+        BlobBuild version = build_blob(bytes_of(data));+        for (auto& object : version.objects) {+            const Id id = object.id ? *object.id : object_id(object.type, bytes_of(object.body));+            delta_objects.push_back(RawObject{object.type, std::move(object.body), id});+        }+    };+    append_version(left);+    append_version(right);+    PackOutput delta_pack = encode_pack(delta_objects);+    auto delta_decoded = decode_pack(delta_pack.pack);+    if (!delta_decoded)+        return fail("delta pack decode");+    bool saw_delta = false;+    for (std::size_t i = 0; i < delta_decoded->records.size(); ++i) {+        const auto& record = delta_decoded->records[i];+        if (record.compression == 2)+            saw_delta = true;+        auto body = delta_decoded->get(i);+        if (!body)+            return fail("delta pack body");+        const Id computed = object_id(record.type, bytes_of(*body));+        if (std::memcmp(computed.data(), record.id.data(), ID_LEN) != 0)+            return fail("delta pack hash");+    }+    if (!saw_delta)+        return fail("delta pack compression");+    auto delta_index = decode_index(delta_pack.index, delta_decoded->trailer);+    if (!delta_index || delta_index->ids.size() != delta_decoded->records.size())+        return fail("delta index");+     info_prefix();     std::cout << "self-test: ok\n";     return 0;@@ -1967,8 +2039,8 @@         const std::string& arg = args[i];         if (!end_flags && arg == "--")             end_flags = true;-        else if (!end_flags && (arg == "-inc-gen" || arg == "-include-generated" ||-                                arg == "--include-generated"))+        else if (!end_flags &&+                 (arg == "-inc-gen" || arg == "-include-generated" || arg == "--include-generated"))             include_generated = true;         else if (!end_flags && is_flag(arg)) {             error_prefix();@@ -2031,10 +2103,9 @@                 result.ext = ext_of(job.entry->path);                 if (auto data = read_blob(store, job.entry->target)) {                     result.bytes = data->size();-                    const bool binary =-                        job.attributes.text == AttributeText::Binary ||-                        (job.attributes.text == AttributeText::Auto &&-                         looks_binary(bytes_of(*data)));+                    const bool binary = job.attributes.text == AttributeText::Binary ||+                                        (job.attributes.text == AttributeText::Auto &&+                                         looks_binary(bytes_of(*data)));                     if (!binary)                         result.lines = count_nonblank(bytes_of(*data));                 }@@ -2247,6 +2318,8 @@     std::cout << "  undo         restore the previous operation view\n";     std::cout << "  op           operation log commands\n";     std::cout << "  fsck         verify repository integrity\n";+    std::cout << "  repack       rewrite packs into one delta-compressed pack; "+                 "alias: gc\n";     std::cout << "  self-test    run the format self-tests\n";     std::cout << "  version      print version information\n";     std::cout << "  bench-import compare lazy import metadata; requires git\n";@@ -2378,6 +2451,16 @@     std::cout << "  -v, -verbose              print verbose output\n"; } +void show_repack() {+    std::cout << "usage: vn repack [path] [-level:<n>] [-verbose]\n\n";+    std::cout << "rewrite all packs into one delta-compressed pack\n\n";+    std::cout << "arguments:\n";+    std::cout << "  [path]                    repository to rewrite (default: .)\n\n";+    std::cout << "options:\n";+    std::cout << "  -level:<n>                zstd level, 1-19 (default: 6)\n";+    std::cout << "  -v, -verbose              print the size change\n";+}+ void show_selftest() {     std::cout << "usage: vn self-test\n\n";     std::cout << "run the format self-tests\n";@@ -2594,6 +2677,8 @@         show_checkout();     else if (cmd == "fsck")         show_fsck();+    else if (cmd == "repack" || cmd == "gc")+        show_repack();     else if (cmd == "bmk")         show_bmk();     else if (cmd == "tag")@@ -2724,6 +2809,8 @@         return resolve_run(args);     if (cmd == "fsck")         return run_fsck(args);+    if (cmd == "repack" || cmd == "gc")+        return run_repack(args);     if (cmd == "self-test")         return run_self_test();     if (cmd == "version" || cmd == "-version") {--- a/xveins/src/store/store.cpp+++ b/xveins/src/store/store.cpp@@ -188,29 +188,75 @@     return std::nullopt; } -Result<std::vector<std::uint8_t>> Pack::get(std::size_t record_index) const {-    if (record_index >= records.size())+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);-    const PackRecord& rec = records[record_index];+    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 > data.size() || stored_len > data.size() - off)+    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>(data.begin() + static_cast<std::ptrdiff_t>(off),-                                         data.begin() +-                                             static_cast<std::ptrdiff_t>(off + stored_len));+        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(out.data(), raw_len, data.data() + off, stored_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; }@@ -262,7 +308,7 @@         const auto comp = r.u8();         if (!comp)             return unexpected(comp.error());-        if (*comp > 1)+        if (*comp > 2)             return fail(ErrorKind::InvalidValue, r.offset() - 1);         rec.compression = *comp;         const std::size_t at = r.offset();@@ -283,6 +329,13 @@         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());@@ -416,28 +469,414 @@ // Pack encoding // --------------------------------------------------------------------------- -static std::vector<std::uint8_t> zstd_compress(Bytes data) {+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(), 1);+    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; } -PackOutput encode_pack(const std::vector<RawObject>& objects) {+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) {+                    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;-    struct Pending {-        const RawObject* object = nullptr;-        Id id{};-        std::uint8_t compression = 0;-        std::vector<std::uint8_t> compressed;-    };-    std::vector<Pending> pending;+    std::vector<PendingObject> pending;     pending.reserve(objects.size());     for (const auto& object : objects) {         if (!type_valid(object.type))@@ -445,13 +884,16 @@         const Id id = object.id ? *object.id : object_id(object.type, bytes_of(object.body));         if (!seen.insert(id).second)             continue;-        pending.push_back(Pending{&object, id, 0, {}});+        PendingObject item;+        item.object = &object;+        item.id = id;+        pending.push_back(std::move(item));     } -    auto compress_one = [](Pending& item) {+    auto compress_one = [level](PendingObject& item) {         if (item.object->body.size() < 64)             return;-        item.compressed = zstd_compress(bytes_of(item.object->body));+        item.compressed = zstd_compress(bytes_of(item.object->body), level);         item.compression = item.compressed.empty() ? 0 : 1;     };     if (pending.size() > 1) {@@ -485,29 +927,47 @@             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) {-        estimate += 32 + 2 + 20 +-                    (item.compression == 1 ? item.compressed.size() : item.object->body.size());+        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 (const auto& item : pending) {+    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();-        const Bytes stored =-            item.compression == 1 ? bytes_of(item.compressed) : bytes_of(object.body);+        record_offsets[i] = offset;         ByteWriter rec(64);         rec.id(item.id);         rec.u8(object.type);-        rec.u8(item.compression);-        rec.varint(object.body.size());-        rec.varint(stored.size());-        rec.raw(stored);+        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()});     }@@ -529,8 +989,8 @@     return output; } -int write_pack(const fs::path& root, const std::vector<RawObject>& objects, std::uint64_t limit) {-    PackOutput output = encode_pack(objects);+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)@@ -548,6 +1008,89 @@     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;+    for (const auto& name : list_directory(source_dir)) {+        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));+        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;+}+ // --------------------------------------------------------------------------- // Store // ---------------------------------------------------------------------------@@ -730,8 +1273,9 @@         [](const StoreHandle& a, const StoreHandle& b) { return a.mtime_ns >= b.mtime_ns; }); } -static std::optional<Loc> read_record_loc(StoreHandle& handle, std::size_t pack_index,-                                          std::uint64_t offset, const Id& expected) {+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;@@ -743,9 +1287,9 @@     const auto stored_len = r.varint();     if (!id || !type || !compression || !raw_len || !stored_len)         return std::nullopt;-    if (std::memcmp(id->data(), expected.data(), ID_LEN) != 0)+    if (expected && std::memcmp(id->data(), expected->data(), ID_LEN) != 0)         return std::nullopt;-    if (!type_valid(*type) || *compression > 1 || *raw_len == 0)+    if (!type_valid(*type) || *compression > 2 || *raw_len == 0)         return std::nullopt;     if (*raw_len > pack_type_limit(*type))         return std::nullopt;@@ -762,6 +1306,11 @@     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];@@ -777,12 +1326,10 @@     return std::nullopt; } -Result<std::vector<std::uint8_t>> Store::get(const Loc& loc) {-    if (loc.pack_index >= handles_.size())-        return fail(ErrorKind::Corrupt, 0);-    auto& handle = handles_[loc.pack_index];-    if (loc.stored_len > std::numeric_limits<std::size_t>::max())-        return fail(ErrorKind::LimitExceeded, loc.data_offset);+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)@@ -790,13 +1337,46 @@     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(out.data(), raw_len, stored->data(), stored->size());+    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()) {--- a/xveins/src/store/store.h+++ b/xveins/src/store/store.h@@ -88,11 +88,13 @@     std::size_t count = 0; }; -PackOutput encode_pack(const std::vector<RawObject>& objects);+PackOutput encode_pack(const std::vector<RawObject>& objects, int level = 3); std::vector<std::uint8_t> encode_index(const std::vector<RecordMeta>& records,                                        const std::array<std::uint8_t, 32>& trailer); -int write_pack(const fs::path& root, const std::vector<RawObject>& objects, std::uint64_t limit);+int write_pack(const fs::path& root, const std::vector<RawObject>& objects, std::uint64_t limit,+               int level = 3);+int repack_repository(const fs::path& root, int level, bool verbose);  // --------------------------------------------------------------------------- // Store