git_internal/internal/pack/encode/mod.rs
1//! Streaming Git pack encoder.
2//!
3//! The encoder has two modes:
4//!
5//! - `window_size == 0`: encode objects independently with zlib. Object compression is
6//! parallelized with Rayon and input order is preserved.
7//! - `window_size > 0`: group and sort objects, search a sliding window for a suitable delta
8//! base, encode the target as an offset delta when profitable, then zlib-compress the payload.
9//!
10//! Rabin fingerprinting is the default delta engine. Building without `diff_rabin` falls back to
11//! Myers (`diff_mydrs`) or Patience when neither diff feature is enabled.
12//!
13//! Pack bytes are sent through an async channel instead of being written directly. This keeps
14//! object preparation, CPU-heavy compression, and file or network output decoupled. When an index
15//! sender is configured, the encoder also records each object's hash, CRC32, and pack offset so an
16//! `.idx` v2 file can be generated after the pack is complete.
17
18mod delta_search;
19mod header;
20mod parallel;
21mod sort;
22
23pub mod output;
24pub use output::encode_and_output_to_files;
25
26#[cfg(test)]
27mod tests;
28
29use header::encode_header;
30use rayon::prelude::*;
31use sort::magic_sort;
32use tokio::{sync::mpsc, task::JoinHandle};
33
34use crate::{
35 errors::GitError,
36 hash::{HashKind, ObjectHash, get_hash_kind},
37 internal::{
38 metadata::{EntryMeta, MetaAttached},
39 object::types::ObjectType,
40 pack::{entry::Entry, index_entry::IndexEntry, pack_index::IdxBuilder},
41 },
42 utils::HashAlgorithm,
43};
44
45/// Stateful encoder for one Git pack stream.
46///
47/// A `PackEncoder` is single-use. It tracks the current pack offset and checksum while encoded
48/// chunks are sent to `pack_sender`. If `idx_sender` is present, index records are accumulated and
49/// can be emitted with [`PackEncoder::encode_idx_file`] after pack encoding finishes.
50pub struct PackEncoder {
51 /// Object count written into the 12-byte pack header.
52 object_number: usize,
53 /// Number of objects consumed by the no-delta path.
54 process_index: usize,
55 /// Zero selects independent encoding; a non-zero value enables delta search.
56 window_size: usize,
57 /// Destination for pack byte chunks. Dropping it signals end-of-stream to the consumer.
58 pack_sender: Option<mpsc::Sender<Vec<u8>>>,
59 /// Optional destination for `.idx` byte chunks.
60 idx_sender: Option<mpsc::Sender<Vec<u8>>>,
61 /// Index metadata collected while pack entries are written.
62 idx_entries: Option<Vec<IndexEntry>>,
63 /// Absolute byte offset where the next pack entry will begin.
64 inner_offset: usize,
65 /// Repository hash kind: drives the pack checksum, the width of every ref-delta base
66 /// ID and the idx object names. Explicit so encoding on a foreign worker thread stays
67 /// correct.
68 hash_kind: HashKind,
69 /// Running checksum of the pack, excluding the checksum trailer itself.
70 inner_hash: HashAlgorithm,
71 /// Final pack checksum, available only after all entries have been encoded.
72 final_hash: Option<ObjectHash>,
73 /// Guards against starting a second encoding operation on the same instance.
74 start_encoding: bool,
75 /// Skip the cheap similarity pre-filter and score every otherwise valid window candidate.
76 ///
77 /// This can improve compression at the cost of more delta computation. The default Rabin path
78 /// disables the pre-filter to follow Git's candidate-search behavior.
79 pub disable_prefilter: bool,
80}
81
82impl PackEncoder {
83 /// Create an encoder that streams pack bytes but does not build an index, using the
84 /// thread-local [`HashKind`] (compatibility wrapper around
85 /// [`PackEncoder::new_with_hash_kind`]).
86 pub fn new(object_number: usize, window_size: usize, sender: mpsc::Sender<Vec<u8>>) -> Self {
87 Self::new_with_hash_kind(get_hash_kind(), object_number, window_size, sender)
88 }
89
90 /// Create an encoder for an explicit repository `hash_kind` that streams pack bytes but
91 /// does not build an index.
92 pub fn new_with_hash_kind(
93 hash_kind: HashKind,
94 object_number: usize,
95 window_size: usize,
96 sender: mpsc::Sender<Vec<u8>>,
97 ) -> Self {
98 PackEncoder {
99 object_number,
100 window_size,
101 process_index: 0,
102 pack_sender: Some(sender),
103 idx_sender: None,
104 idx_entries: None,
105 inner_offset: 12, // The first entry begins immediately after the pack header.
106 hash_kind,
107 inner_hash: HashAlgorithm::new_for_kind(hash_kind),
108 final_hash: None,
109 start_encoding: false,
110 disable_prefilter: false,
111 }
112 }
113
114 /// Create an encoder that streams pack bytes and retains metadata for a later `.idx`
115 /// stream, using the thread-local [`HashKind`] (compatibility wrapper around
116 /// [`PackEncoder::new_with_idx_and_hash_kind`]).
117 pub fn new_with_idx(
118 object_number: usize,
119 window_size: usize,
120 pack_sender: mpsc::Sender<Vec<u8>>,
121 idx_sender: mpsc::Sender<Vec<u8>>,
122 ) -> Self {
123 Self::new_with_idx_and_hash_kind(
124 get_hash_kind(),
125 object_number,
126 window_size,
127 pack_sender,
128 idx_sender,
129 )
130 }
131
132 /// Create an encoder for an explicit repository `hash_kind` that streams pack bytes and
133 /// retains metadata for a later `.idx` stream.
134 pub fn new_with_idx_and_hash_kind(
135 hash_kind: HashKind,
136 object_number: usize,
137 window_size: usize,
138 pack_sender: mpsc::Sender<Vec<u8>>,
139 idx_sender: mpsc::Sender<Vec<u8>>,
140 ) -> Self {
141 PackEncoder {
142 object_number,
143 window_size,
144 process_index: 0,
145 pack_sender: Some(pack_sender),
146 idx_sender: Some(idx_sender),
147 idx_entries: None,
148 inner_offset: 12, // The first entry begins immediately after the pack header.
149 hash_kind,
150 inner_hash: HashAlgorithm::new_for_kind(hash_kind),
151 final_hash: None,
152 start_encoding: false,
153 disable_prefilter: false,
154 }
155 }
156
157 /// Repository hash kind this encoder writes (pack checksum, ref-delta base IDs, idx names).
158 pub fn hash_kind(&self) -> HashKind {
159 self.hash_kind
160 }
161
162 /// Reject an entry whose object ID belongs to another hash kind: a pack (and its idx)
163 /// carries exactly one repository kind.
164 fn check_entry_kind(&self, entry: &Entry) -> Result<(), GitError> {
165 entry.hash.ensure_kind(self.hash_kind).map_err(|e| {
166 GitError::PackEncodeError(format!(
167 "entry {} cannot be encoded into a {} pack: {e}",
168 entry.hash, self.hash_kind
169 ))
170 })
171 }
172
173 /// Close the pack output stream by dropping the encoder's final sender.
174 pub fn drop_sender(&mut self) {
175 self.pack_sender.take();
176 }
177
178 /// Send one already-encoded byte chunk to the pack consumer.
179 pub async fn send_data(&mut self, data: Vec<u8>) {
180 if let Some(sender) = &self.pack_sender {
181 sender.send(data).await.unwrap();
182 }
183 }
184
185 /// Return the pack checksum after encoding has completed.
186 pub fn get_hash(&self) -> Option<ObjectHash> {
187 self.final_hash
188 }
189
190 /// Consume an entry stream and emit one complete pack stream.
191 ///
192 /// With `window_size == 0`, entries are independently zlib-compressed in parallel. With a
193 /// non-zero window, entries are collected, sorted for delta locality, and passed through
194 /// sliding-window base selection.
195 ///
196 /// When `diff_rabin` is enabled, the default delta engine is Rabin and all otherwise valid
197 /// candidates are scored. Without that feature, the Myers/Patience engine is used after the
198 /// configured similarity pre-filter.
199 pub async fn encode(
200 &mut self,
201 entry_rx: mpsc::Receiver<MetaAttached<Entry, EntryMeta>>,
202 ) -> Result<(), GitError> {
203 if self.window_size == 0 {
204 self.parallel_encode(entry_rx).await
205 } else {
206 #[cfg(feature = "diff_rabin")]
207 {
208 self.inner_encode(entry_rx, false, true, true).await
209 }
210 #[cfg(not(feature = "diff_rabin"))]
211 {
212 self.inner_encode(entry_rx, false, false, self.disable_prefilter)
213 .await
214 }
215 }
216 }
217
218 /// Encode with zstdelta payloads while retaining the same sorting and base-selection pipeline.
219 pub async fn encode_with_zstdelta(
220 &mut self,
221 entry_rx: mpsc::Receiver<MetaAttached<Entry, EntryMeta>>,
222 ) -> Result<(), GitError> {
223 self.inner_encode(entry_rx, true, false, self.disable_prefilter)
224 .await
225 }
226
227 /// Collect, order, delta-search, and write entries for the windowed encoding path.
228 ///
229 /// This method deliberately separates CPU-heavy delta discovery from ordered pack output:
230 ///
231 /// 1. Drain the input channel and partition entries by Git object type.
232 /// 2. Sort each type so likely-related objects are close enough to share a delta window.
233 /// 3. Search for delta bases on blocking worker threads.
234 /// 4. Restore deterministic chunk order and write encoded entries serially, assigning their
235 /// absolute pack offsets.
236 /// 5. Append the pack checksum and close the output channel.
237 ///
238 /// Candidate-selection rules are based on Git's pack heuristics:
239 /// <https://github.com/git/git/blob/master/Documentation/technical/pack-heuristics.adoc>.
240 async fn inner_encode(
241 &mut self,
242 mut entry_rx: mpsc::Receiver<MetaAttached<Entry, EntryMeta>>,
243 enable_zstdelta: bool,
244 enable_rabin: bool,
245 disable_prefilter: bool,
246 ) -> Result<(), GitError> {
247 // The trailer checksum covers the header and every encoded entry, but not the trailer.
248 let head = encode_header(self.object_number);
249 self.send_data(head.clone()).await;
250 self.inner_hash.update(&head);
251
252 // Reusing the same encoder would corrupt its running offset and checksum state.
253 if self.start_encoding {
254 return Err(GitError::PackEncodeError(
255 "encoding operation is already in progress".to_string(),
256 ));
257 }
258
259 // Delta bases must have the same object type. Keeping types separate makes that invariant
260 // explicit and prevents unrelated types from occupying one another's search windows.
261 let mut commits: Vec<MetaAttached<Entry, EntryMeta>> = Vec::new();
262 let mut trees: Vec<MetaAttached<Entry, EntryMeta>> = Vec::new();
263 let mut blobs: Vec<MetaAttached<Entry, EntryMeta>> = Vec::new();
264 let mut tags: Vec<MetaAttached<Entry, EntryMeta>> = Vec::new();
265 while let Some(entry) = entry_rx.recv().await {
266 self.check_entry_kind(&entry.inner)?;
267 match entry.inner.obj_type {
268 ObjectType::Commit => {
269 commits.push(entry);
270 }
271 ObjectType::Tree => {
272 trees.push(entry);
273 }
274 ObjectType::Blob => {
275 blobs.push(entry);
276 }
277 ObjectType::Tag => {
278 tags.push(entry);
279 }
280 _ => {
281 return Err(GitError::PackEncodeError(format!(
282 "object type `{}` is not supported by delta-window pack encoding",
283 entry.inner.obj_type
284 )));
285 }
286 }
287 }
288
289 // Sorting is the compression heuristic: nearby entries become eligible delta bases.
290 commits.sort_by(magic_sort);
291 trees.sort_by(magic_sort);
292 blobs.sort_by(magic_sort);
293 tags.sort_by(magic_sort);
294 tracing::info!(
295 "numbers : commits: {:?} trees: {:?} blobs:{:?} tag :{:?}",
296 commits.len(),
297 trees.len(),
298 blobs.len(),
299 tags.len()
300 );
301
302 // Delta search is CPU-bound, so it must not run on Tokio's async executor threads.
303 // All entries (commits, trees, tags, and contiguous blob chunks) are processed in a
304 // single Rayon batch inside one spawn_blocking task. Rayon's work-stealing balances
305 // load across heterogeneous work items without the manual-queue and mixed-thread-pool
306 // machinery used previously.
307
308 // Paths are needed only for sorting. Delta generation works on the underlying entries.
309 let commit_entries: Vec<Entry> = commits.into_iter().map(|e| e.inner).collect();
310 let tree_entries: Vec<Entry> = trees.into_iter().map(|e| e.inner).collect();
311 let tag_entries: Vec<Entry> = tags.into_iter().map(|e| e.inner).collect();
312 let mut blob_entries: Vec<Entry> = blobs.into_iter().map(|e| e.inner).collect();
313
314 // ── Build the work-item list ──────────────────────────────────────────
315 // Each item holds a contiguous segment of sorted entries. The `order` field
316 // determines final pack layout: commits → trees → blob chunks → tags.
317 struct WorkItem {
318 order: usize,
319 entries: Vec<Entry>,
320 }
321
322 let mut work_items: Vec<WorkItem> = Vec::new();
323 work_items.push(WorkItem {
324 order: 0,
325 entries: commit_entries,
326 });
327 work_items.push(WorkItem {
328 order: 1,
329 entries: tree_entries,
330 });
331
332 // Preserve contiguous portions of the sorted blob list: splitting objects
333 // arbitrarily would destroy the locality created by magic_sort and reduce
334 // delta quality. Creating many chunks exposes enough parallelism for
335 // Rayon's work-stealing scheduler.
336 let total_blob_entries = blob_entries.len();
337 let num_threads = rayon::current_num_threads();
338 let chunks_per_thread: usize = 20;
339 let mut blob_chunk_count = if num_threads > 1 && total_blob_entries > (num_threads * 20) {
340 num_threads * chunks_per_thread
341 } else {
342 1
343 };
344 let mut entries_per_chunk = total_blob_entries.div_ceil(blob_chunk_count);
345
346 // Prevent over-fragmentation on high-core-count machines: each chunk must
347 // contain enough entries for the sliding window to find meaningful delta
348 // bases. Without this guard, a 128-core grading server would split objects
349 // into 2560 tiny chunks (~29 entries each), destroying cross-chunk delta
350 // locality and inflating pack size by 3+% compared to a typical laptop.
351 let min_entries_per_chunk = (self.window_size * 10).max(50);
352 if entries_per_chunk < min_entries_per_chunk {
353 blob_chunk_count = (total_blob_entries / min_entries_per_chunk).max(1);
354 entries_per_chunk = total_blob_entries.div_ceil(blob_chunk_count);
355 }
356
357 // split_off removes from the end in O(1). Reverse afterward to recover
358 // global sort order.
359 let mut blob_chunks: Vec<Vec<Entry>> = Vec::with_capacity(blob_chunk_count);
360 for _ in 0..blob_chunk_count {
361 let take = entries_per_chunk.min(blob_entries.len());
362 if take == 0 {
363 break;
364 }
365 let chunk = blob_entries.split_off(blob_entries.len() - take);
366 blob_chunks.push(chunk);
367 }
368 blob_chunks.reverse();
369
370 let actual_blob_chunks = blob_chunks.len();
371 let blob_base_order = 2usize;
372 for (i, chunk) in blob_chunks.into_iter().enumerate() {
373 work_items.push(WorkItem {
374 order: blob_base_order + i,
375 entries: chunk,
376 });
377 }
378
379 let tag_order = blob_base_order + actual_blob_chunks;
380 work_items.push(WorkItem {
381 order: tag_order,
382 entries: tag_entries,
383 });
384
385 tracing::info!(
386 total_work_items = work_items.len(),
387 blob_chunks = actual_blob_chunks,
388 threads = num_threads,
389 "dispatching delta search to Rayon"
390 );
391
392 // Offload all delta search to Rayon inside a single spawn_blocking task.
393 // This keeps CPU work off the async runtime while Rayon's work-stealing
394 // balances load across the heterogeneous work items.
395 type ChunkResult = (usize, Result<Vec<(Vec<u8>, IndexEntry)>, GitError>);
396
397 let ez = enable_zstdelta;
398 let er = enable_rabin;
399 let dp = disable_prefilter;
400
401 let run_delta_search = move || -> Vec<ChunkResult> {
402 work_items
403 .into_par_iter()
404 .map(|item| {
405 (
406 item.order,
407 Self::try_as_offset_delta(item.entries, 10, ez, er, dp),
408 )
409 })
410 .collect()
411 };
412
413 let mut chunk_results: Vec<ChunkResult> =
414 // When PACK_THREADS is set, build a dedicated Rayon pool with the
415 // requested thread count and run the delta search on it. Otherwise
416 // use the global Rayon pool (which respects RAYON_NUM_THREADS).
417 if let Some(n) = std::env::var("PACK_THREADS")
418 .ok()
419 .and_then(|s| s.parse::<usize>().ok())
420 {
421 let pool = rayon::ThreadPoolBuilder::new()
422 .num_threads(n)
423 .build()
424 .map_err(|e| GitError::PackEncodeError(format!(
425 "failed to build Rayon thread pool: {e}"
426 )))?;
427 tokio::task::spawn_blocking(move || pool.install(run_delta_search))
428 .await
429 .map_err(|e| GitError::PackEncodeError(format!(
430 "delta search task panicked: {e}"
431 )))?
432 } else {
433 tokio::task::spawn_blocking(run_delta_search)
434 .await
435 .map_err(|e| GitError::PackEncodeError(format!(
436 "delta search task panicked: {e}"
437 )))?
438 };
439
440 // Parallel search may finish out of order; restore the chosen pack order.
441 chunk_results.sort_by_key(|(order, _)| *order);
442
443 let mut all_res: Vec<Vec<(Vec<u8>, IndexEntry)>> = Vec::with_capacity(chunk_results.len());
444 for (_order, res) in chunk_results {
445 all_res.push(res?);
446 }
447
448 // Writing is serialized so offsets, the running pack hash, and index records all describe
449 // exactly the same byte order.
450 let total_entries = all_res.iter().map(Vec::len).sum();
451 let mut idx_entries = Vec::with_capacity(total_entries);
452 for res in &mut all_res {
453 for (encoded_bytes, mut idx_entry) in res.drain(..) {
454 idx_entry.offset = self.inner_offset as u64;
455 // idx v2 CRC32 covers the object's *encoded* pack bytes (header, base
456 // reference and compressed payload) — exactly what the idx-backed decoders
457 // verify — not the decompressed content the placeholder entry was built from.
458 idx_entry.crc32 = crc32fast::hash(&encoded_bytes);
459 self.write_owned_and_update(encoded_bytes).await;
460 idx_entries.push(idx_entry);
461 }
462 }
463
464 self.idx_entries = Some(idx_entries);
465
466 // The checksum is both the pack trailer and the identifier used in pack-<hash>.pack.
467 // The checksum kind comes from the hasher chosen at encoder construction, never
468 // from the checksum length or the (possibly foreign) thread-local `HashKind` of the
469 // async worker that runs this task: a 32-byte digest may be SHA-256 or BLAKE3.
470 let final_hash = self.inner_hash.clone().finalize_object_hash();
471 self.final_hash = Some(final_hash);
472 self.send_data(final_hash.to_data()).await;
473
474 self.drop_sender();
475 Ok(())
476 }
477
478 /// Account for an encoded chunk, then forward it to the pack consumer.
479 ///
480 /// The caller must invoke this in final pack order because both `inner_offset` and `inner_hash`
481 /// are order-sensitive.
482 async fn write_owned_and_update(&mut self, data: Vec<u8>) {
483 self.inner_hash.update(&data);
484 self.inner_offset += data.len();
485 self.send_data(data).await;
486 }
487
488 /// Build the `.idx` stream from metadata captured during pack encoding.
489 async fn generate_idx_file(&mut self) -> Result<(), GitError> {
490 let final_hash = self.final_hash.ok_or(GitError::PackEncodeError(
491 "final_hash is missing,The pack file must be generated before the index file is produced."
492 .into(),
493 ))?;
494 let idx_entries = self.idx_entries.clone().ok_or(GitError::PackEncodeError(
495 "The pack file must be generated before the index file is produced.".into(),
496 ))?;
497 let mut idx_builder = IdxBuilder::new(
498 self.object_number,
499 self.idx_sender.clone().unwrap(),
500 final_hash,
501 );
502 idx_builder.write_idx(idx_entries).await?;
503 Ok(())
504 }
505
506 /// Spawn pack encoding as a Tokio task and return its join handle.
507 ///
508 /// This consumes the encoder so the spawned task owns all channel senders and state. The task
509 /// chooses the same zero-window versus delta-window path as [`PackEncoder::encode`].
510 ///
511 /// Encoding errors currently panic inside the spawned task and are therefore reported as a
512 /// `JoinError` when the returned handle is awaited.
513 pub async fn encode_async(
514 mut self,
515 rx: mpsc::Receiver<MetaAttached<Entry, EntryMeta>>,
516 ) -> Result<JoinHandle<()>, GitError> {
517 Ok(tokio::spawn(async move {
518 if self.window_size == 0 {
519 self.parallel_encode(rx).await.unwrap()
520 } else {
521 self.encode(rx).await.unwrap()
522 }
523 }))
524 }
525
526 /// Spawn zstdelta pack encoding as a Tokio task.
527 ///
528 /// zstdelta always uses the windowed path because independent encoding has no base from which
529 /// to produce a delta.
530 pub async fn encode_async_with_zstdelta(
531 mut self,
532 rx: mpsc::Receiver<MetaAttached<Entry, EntryMeta>>,
533 ) -> Result<JoinHandle<()>, GitError> {
534 Ok(tokio::spawn(async move {
535 self.encode_with_zstdelta(rx).await.unwrap()
536 }))
537 }
538
539 /// Emit the `.idx` stream after the pack has been finalized.
540 ///
541 /// Pack encoding must run first because the index trailer contains the pack checksum and each
542 /// record needs its final absolute pack offset.
543 pub async fn encode_idx_file(&mut self) -> Result<(), GitError> {
544 if self.idx_sender.is_none() {
545 return Err(GitError::PackEncodeError(String::from(
546 "idx sender is none",
547 )));
548 }
549 self.generate_idx_file().await?;
550 // Closing the final sender tells the index writer that no more chunks are coming.
551 self.idx_sender.take();
552 Ok(())
553 }
554}