git_internal/internal/pack/encode/parallel.rs
1//! Parallel (non-delta) pack encoding path.
2//!
3//! When `window_size == 0`, entries are independently zlib-compressed in parallel via Rayon.
4//! Input is read in bounded batches to balance memory usage and parallelism.
5//!
6//! This path is not compatible with delta compression — use the delta path in
7//! [`super::inner_encode`] for windowed encoding.
8
9use rayon::prelude::*;
10use tokio::sync::mpsc;
11
12use super::header::{encode_header, encode_one_object};
13use crate::{
14 errors::GitError,
15 internal::{
16 metadata::{EntryMeta, MetaAttached},
17 pack::{entry::Entry, index_entry::IndexEntry},
18 },
19 time_it,
20};
21
22impl super::PackEncoder {
23 /// Encode independent objects in parallel without delta compression.
24 ///
25 /// Input is read in bounded batches, and Rayon performs each object's header construction and
26 /// zlib compression concurrently. Rayon collection preserves input order, after which chunks
27 /// are written serially so pack offsets and the running checksum remain correct.
28 ///
29 /// This path is valid only when `window_size == 0`.
30 pub async fn parallel_encode(
31 &mut self,
32 mut entry_rx: mpsc::Receiver<MetaAttached<Entry, EntryMeta>>,
33 ) -> Result<(), GitError> {
34 if self.window_size != 0 {
35 return Err(GitError::PackEncodeError(
36 "parallel encode only works when window_size == 0".to_string(),
37 ));
38 }
39
40 // As in the delta path, the trailer checksum covers the header and all entries.
41 let head = encode_header(self.object_number);
42 self.inner_hash.update(&head);
43 self.send_data(head).await;
44
45 // Reusing the same encoder would corrupt its running offset and checksum state.
46 if self.start_encoding {
47 return Err(GitError::PackEncodeError(
48 "encoding operation is already in progress".to_string(),
49 ));
50 }
51
52 let mut idx_entries = Vec::with_capacity(self.object_number);
53 // Batching bounds temporary memory while giving Rayon enough work to distribute.
54 let batch_size = usize::max(1000, entry_rx.max_capacity() / 10); // Temporary heuristic.
55 tracing::info!("encode with batch size: {}", batch_size);
56 loop {
57 let mut batch_entries = Vec::with_capacity(batch_size);
58 time_it!("parallel encode: receive batch", {
59 for _ in 0..batch_size {
60 match entry_rx.recv().await {
61 Some(entry) => {
62 if entry.inner.obj_type.is_ai_object() {
63 return Err(GitError::PackEncodeError(format!(
64 "AI object type `{}` cannot be encoded in a pack file",
65 entry.inner.obj_type
66 )));
67 }
68 self.check_entry_kind(&entry.inner)?;
69 batch_entries.push(entry.inner);
70 self.process_index += 1;
71 }
72 None => break,
73 }
74 }
75 });
76
77 if batch_entries.is_empty() {
78 break;
79 }
80
81 // Indexed parallel collection retains batch order even though compression finishes on
82 // different Rayon workers.
83 let batch_result: Vec<Result<(Vec<u8>, IndexEntry), GitError>> =
84 time_it!("parallel encode: encode batch", {
85 batch_entries
86 .par_iter()
87 .map(|entry| {
88 encode_one_object(entry, None)
89 .map(|encoded| (encoded, IndexEntry::new(entry, 0)))
90 })
91 .collect()
92 });
93
94 time_it!("parallel encode: write batch", {
95 for obj_data in batch_result {
96 let (encoded_bytes, mut idx_entry) = obj_data?;
97 idx_entry.offset = self.inner_offset as u64;
98 // idx v2 CRC32 covers the encoded pack entry (what the decoders verify),
99 // not the decompressed content the placeholder entry was built from.
100 idx_entry.crc32 = crc32fast::hash(&encoded_bytes);
101 self.write_owned_and_update(encoded_bytes).await;
102 idx_entries.push(idx_entry);
103 }
104 });
105 }
106
107 tracing::debug!("parallel encode idx entries: {:?}", idx_entries.len());
108 if self.process_index != self.object_number {
109 panic!(
110 "not all objects are encoded, process:{}, total:{}",
111 self.process_index, self.object_number
112 );
113 }
114
115 // Append the checksum trailer only after every encoded entry has updated the running hash.
116 // The checksum kind comes from the hasher chosen at encoder construction, never
117 // from the checksum length or the (possibly foreign) thread-local `HashKind` of the
118 // async worker that runs this task: a 32-byte digest may be SHA-256 or BLAKE3.
119 let final_hash = self.inner_hash.clone().finalize_object_hash();
120 self.final_hash = Some(final_hash);
121 self.send_data(final_hash.to_data()).await;
122 self.drop_sender();
123
124 self.idx_entries = Some(idx_entries);
125 Ok(())
126 }
127}