interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-bench / src / fixture.rs

388 lines · 13233 bytes Raw Blame History
1//! Representative fixture handling: isolated clones of a pinned real repository,
2//! base tree listing, and bulk blob loading through a persistent `git cat-file --batch`.
3//!
4//! The original fixture repository is only ever read by `git clone --local`, which
5//! hardlinks or copies its object files into a new directory. Every measurement then
6//! runs against that private clone (or a clone of it).
7
8use crate::gitcmd::{git_line, git_ok};
9use crate::path_str;
10use std::io::{BufRead, BufReader, Read, Write};
11use std::path::Path;
12use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
13use std::sync::Arc;
14use synapse_core::FileMode;
15
16/// Directory prefix for files that the synthetic workloads add to the fixture.
17pub const BENCH_PATH_PREFIX: &str = "synapse-gate4-bench";
18
19/// Smallest and largest file sizes eligible for synthetic edits.
20pub const EDITABLE_MIN_BYTES: u64 = 256;
21pub const EDITABLE_MAX_BYTES: u64 = 64 * 1024;
22/// Minimum line count for an editable file.
23pub const EDITABLE_MIN_LINES: usize = 8;
24
25/// One file entry of the pinned base commit tree.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct BaseEntry {
28 pub path: String,
29 pub mode: FileMode,
30 pub git_oid_hex: String,
31 pub size_bytes: u64,
32}
33
34/// The pinned base commit and its file entries.
35#[derive(Debug, Clone)]
36pub struct BaseTree {
37 pub commit_hex: String,
38 pub tree_hex: String,
39 pub entries: Vec<BaseEntry>,
40 /// Entries skipped because their mode is not a regular file, executable, or symlink
41 /// (the same filter `SynapseService::import_base_tree_from_git_repo` applies).
42 pub skipped_entries: usize,
43}
44
45impl BaseTree {
46 pub fn total_bytes(&self) -> u64 {
47 self.entries.iter().map(|e| e.size_bytes).sum()
48 }
49}
50
51/// A text file from the base tree that synthetic proposals may modify or delete.
52#[derive(Debug, Clone)]
53pub struct EditableFile {
54 pub path: String,
55 pub content: Arc<Vec<u8>>,
56 pub line_count: usize,
57}
58
59/// `git clone --no-checkout --local --quiet <src> <dest>`.
60pub fn clone_no_checkout(src: &Path, dest: &Path) -> Result<(), String> {
61 let parent = dest
62 .parent()
63 .ok_or_else(|| format!("clone destination has no parent: {}", dest.display()))?;
64 std::fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?;
65 git_ok(
66 parent,
67 &[],
68 &[],
69 &[
70 "clone",
71 "--no-checkout",
72 "--local",
73 "--quiet",
74 path_str(src)?,
75 path_str(dest)?,
76 ],
77 None,
78 )?;
79 Ok(())
80}
81
82/// Repository-local settings applied to every benchmark clone. Automatic `gc` and
83/// maintenance are disabled so that no arm pays for (or skips) a background repack.
84pub const BENCH_CLONE_CONFIG: &[(&str, &str)] = &[
85 ("gc.auto", "0"),
86 ("maintenance.auto", "false"),
87 ("user.name", "Synapse Gate4 Bench"),
88 ("user.email", "gate4-bench@synapse.invalid"),
89 ("commit.gpgsign", "false"),
90];
91
92/// Apply [`BENCH_CLONE_CONFIG`] to `clone`.
93pub fn configure_bench_clone(clone: &Path) -> Result<(), String> {
94 for (k, v) in BENCH_CLONE_CONFIG {
95 git_ok(clone, &[], &[], &["config", k, v], None)?;
96 }
97 Ok(())
98}
99
100/// Resolve `rev` and list its tree (`git ls-tree -r -z -l`).
101pub fn list_base_tree(repo: &Path, rev: &str) -> Result<BaseTree, String> {
102 let commit_hex = git_line(
103 repo,
104 &["rev-parse", "--verify", &format!("{rev}^{{commit}}")],
105 )?;
106 let tree_hex = git_line(repo, &["rev-parse", "--verify", &format!("{rev}^{{tree}}")])?;
107 let out = git_ok(
108 repo,
109 &[],
110 &[],
111 &["ls-tree", "-r", "-z", "-l", &commit_hex],
112 None,
113 )?;
114 let mut entries = Vec::new();
115 let mut skipped = 0usize;
116 for record in out.split(|&b| b == 0) {
117 if record.is_empty() {
118 continue;
119 }
120 let text =
121 std::str::from_utf8(record).map_err(|e| format!("non-UTF-8 ls-tree record: {e}"))?;
122 let (meta, path) = text
123 .split_once('\t')
124 .ok_or_else(|| format!("malformed ls-tree record: {text}"))?;
125 let cols: Vec<&str> = meta.split_whitespace().collect();
126 if cols.len() < 4 {
127 return Err(format!("malformed ls-tree metadata: {meta}"));
128 }
129 let mode = match cols[0] {
130 "100644" => FileMode::Regular644,
131 "100755" => FileMode::Executable755,
132 "120000" => FileMode::Symlink120000,
133 _ => {
134 skipped += 1;
135 continue;
136 }
137 };
138 let size_bytes = cols[3]
139 .parse::<u64>()
140 .map_err(|e| format!("bad ls-tree size {}: {e}", cols[3]))?;
141 entries.push(BaseEntry {
142 path: path.to_string(),
143 mode,
144 git_oid_hex: cols[2].to_string(),
145 size_bytes,
146 });
147 }
148 Ok(BaseTree {
149 commit_hex,
150 tree_hex,
151 entries,
152 skipped_entries: skipped,
153 })
154}
155
156/// A persistent `git cat-file --batch` process (one spawn, many object reads).
157pub struct CatFileBatch {
158 child: Child,
159 stdin: Option<ChildStdin>,
160 stdout: BufReader<ChildStdout>,
161}
162
163impl CatFileBatch {
164 pub fn spawn(repo: &Path) -> Result<Self, String> {
165 let mut child = Command::new("git")
166 .arg("-C")
167 .arg(repo)
168 .args(["cat-file", "--batch"])
169 .stdin(Stdio::piped())
170 .stdout(Stdio::piped())
171 .stderr(Stdio::null())
172 .spawn()
173 .map_err(|e| format!("spawn git cat-file --batch: {e}"))?;
174 let stdin = child.stdin.take().ok_or("cat-file stdin unavailable")?;
175 let stdout = child.stdout.take().ok_or("cat-file stdout unavailable")?;
176 Ok(Self {
177 child,
178 stdin: Some(stdin),
179 stdout: BufReader::new(stdout),
180 })
181 }
182
183 /// Read one object named by `spec` (an OID or `<rev>:<path>`).
184 pub fn read(&mut self, spec: &str) -> Result<Vec<u8>, String> {
185 let stdin = self.stdin.as_mut().ok_or("cat-file stdin already closed")?;
186 stdin
187 .write_all(format!("{spec}\n").as_bytes())
188 .and_then(|_| stdin.flush())
189 .map_err(|e| format!("write cat-file request: {e}"))?;
190 let mut header = String::new();
191 self.stdout
192 .read_line(&mut header)
193 .map_err(|e| format!("read cat-file header: {e}"))?;
194 let header = header.trim_end();
195 if header.ends_with(" missing") || header.ends_with(" ambiguous") || header.is_empty() {
196 return Err(format!("cat-file could not resolve {spec}: {header}"));
197 }
198 let size: usize = header
199 .rsplit(' ')
200 .next()
201 .and_then(|s| s.parse().ok())
202 .ok_or_else(|| format!("malformed cat-file header: {header}"))?;
203 let mut buf = vec![0u8; size + 1];
204 self.stdout
205 .read_exact(&mut buf)
206 .map_err(|e| format!("read cat-file body for {spec}: {e}"))?;
207 buf.truncate(size);
208 Ok(buf)
209 }
210
211 /// Close stdin and wait for the process so its CPU time is counted in `RUSAGE_CHILDREN`.
212 pub fn finish(mut self) -> Result<(), String> {
213 drop(self.stdin.take());
214 let status = self
215 .child
216 .wait()
217 .map_err(|e| format!("wait cat-file: {e}"))?;
218 if status.success() {
219 Ok(())
220 } else {
221 Err(format!("git cat-file --batch exited with {status}"))
222 }
223 }
224}
225
226/// Load the bytes of `entries` (in order) through one `git cat-file --batch` process.
227pub fn load_blobs(repo: &Path, entries: &[&BaseEntry]) -> Result<Vec<Vec<u8>>, String> {
228 let mut batch = CatFileBatch::spawn(repo)?;
229 let mut out = Vec::with_capacity(entries.len());
230 for e in entries {
231 out.push(batch.read(&e.git_oid_hex)?);
232 }
233 batch.finish()?;
234 Ok(out)
235}
236
237/// Load every base entry as `(path, mode, bytes)` for `SynapseService::register_base_tree`.
238pub fn load_full_base(
239 repo: &Path,
240 base: &BaseTree,
241) -> Result<Vec<(String, FileMode, Vec<u8>)>, String> {
242 let refs: Vec<&BaseEntry> = base.entries.iter().collect();
243 let blobs = load_blobs(repo, &refs)?;
244 Ok(base
245 .entries
246 .iter()
247 .zip(blobs)
248 .map(|(e, b)| (e.path.clone(), e.mode, b))
249 .collect())
250}
251
252fn editable_from_bytes(path: &str, bytes: &[u8]) -> Option<EditableFile> {
253 if bytes.contains(&0) {
254 return None;
255 }
256 let text = std::str::from_utf8(bytes).ok()?;
257 let line_count = text.lines().count();
258 if line_count < EDITABLE_MIN_LINES {
259 return None;
260 }
261 Some(EditableFile {
262 path: path.to_string(),
263 content: Arc::new(bytes.to_vec()),
264 line_count,
265 })
266}
267
268fn is_editable_candidate(e: &BaseEntry) -> bool {
269 e.mode == FileMode::Regular644
270 && (EDITABLE_MIN_BYTES..=EDITABLE_MAX_BYTES).contains(&e.size_bytes)
271 && !e.path.starts_with(BENCH_PATH_PREFIX)
272}
273
274/// Select editable text files (sorted by path) by loading only size-eligible candidates.
275pub fn load_editable_files(repo: &Path, base: &BaseTree) -> Result<Vec<EditableFile>, String> {
276 let candidates: Vec<&BaseEntry> = base
277 .entries
278 .iter()
279 .filter(|e| is_editable_candidate(e))
280 .collect();
281 let blobs = load_blobs(repo, &candidates)?;
282 let mut files: Vec<EditableFile> = candidates
283 .iter()
284 .zip(blobs.iter())
285 .filter_map(|(e, b)| editable_from_bytes(&e.path, b))
286 .collect();
287 files.sort_by(|a, b| a.path.cmp(&b.path));
288 Ok(files)
289}
290
291/// Select editable files from an already loaded full base (same rule as [`load_editable_files`]).
292pub fn editable_from_full_base(
293 base: &BaseTree,
294 full: &[(String, FileMode, Vec<u8>)],
295) -> Vec<EditableFile> {
296 let mut files: Vec<EditableFile> = base
297 .entries
298 .iter()
299 .zip(full.iter())
300 .filter(|(e, _)| is_editable_candidate(e))
301 .filter_map(|(e, (_, _, bytes))| editable_from_bytes(&e.path, bytes))
302 .collect();
303 files.sort_by(|a, b| a.path.cmp(&b.path));
304 files
305}
306
307#[cfg(test)]
308pub mod test_support {
309 //! Small synthetic Git fixture for unit tests (no network, no external repository).
310 use super::*;
311
312 /// Create a repository with `n_files` text files of `lines` lines each plus a
313 /// nested directory and an executable script, committed on branch `main`.
314 pub fn make_fixture_repo(root: &Path, n_files: usize, lines: usize) -> String {
315 let repo = root.join("fixture");
316 std::fs::create_dir_all(repo.join("src/nested")).unwrap();
317 git_ok(&repo, &[], &[], &["init", "-q", "-b", "main"], None).unwrap();
318 configure_bench_clone(&repo).unwrap();
319 for i in 0..n_files {
320 let mut body = String::new();
321 for l in 0..lines {
322 body.push_str(&format!(
323 "fixture file {i} line {l} with some padding text\n"
324 ));
325 }
326 let path = if i % 3 == 0 {
327 repo.join(format!("src/nested/file{i:02}.txt"))
328 } else {
329 repo.join(format!("src/file{i:02}.txt"))
330 };
331 std::fs::write(path, body).unwrap();
332 }
333 std::fs::write(repo.join("run.sh"), "#!/bin/sh\necho fixture\n").unwrap();
334 let mut perm = std::fs::metadata(repo.join("run.sh"))
335 .unwrap()
336 .permissions();
337 std::os::unix::fs::PermissionsExt::set_mode(&mut perm, 0o755);
338 std::fs::set_permissions(repo.join("run.sh"), perm).unwrap();
339 git_ok(&repo, &[], &[], &["add", "-A"], None).unwrap();
340 git_ok(
341 &repo,
342 &[],
343 &[],
344 &["commit", "-q", "-m", "fixture base"],
345 None,
346 )
347 .unwrap();
348 git_line(&repo, &["rev-parse", "HEAD"]).unwrap()
349 }
350
351 pub fn temp_dir(label: &str) -> std::path::PathBuf {
352 let dir = std::env::temp_dir().join(format!(
353 "synapse-bench-test-{label}-{}-{}",
354 std::process::id(),
355 crate::unix_now_ms()
356 ));
357 let _ = std::fs::remove_dir_all(&dir);
358 std::fs::create_dir_all(&dir).unwrap();
359 dir
360 }
361}
362
363#[cfg(test)]
364mod tests {
365 use super::test_support::*;
366 use super::*;
367
368 #[test]
369 fn list_and_load_match_git_object_ids() {
370 let root = temp_dir("fixture");
371 let commit = make_fixture_repo(&root, 6, 20);
372 let repo = root.join("fixture");
373 let base = list_base_tree(&repo, &commit).unwrap();
374 assert_eq!(base.commit_hex, commit);
375 assert_eq!(base.entries.len(), 7);
376 let full = load_full_base(&repo, &base).unwrap();
377 for (entry, (_, _, bytes)) in base.entries.iter().zip(full.iter()) {
378 assert_eq!(
379 synapse_core::GitOid::compute_blob(bytes).to_hex(),
380 entry.git_oid_hex
381 );
382 }
383 let editable = load_editable_files(&repo, &base).unwrap();
384 assert_eq!(editable.len(), 6);
385 assert_eq!(editable_from_full_base(&base, &full).len(), 6);
386 let _ = std::fs::remove_dir_all(&root);
387 }
388}