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 / git_arm.rs

285 lines · 10707 bytes Raw Blame History
1//! Conventional Git workflow arms.
2//!
3//! * G1: a fresh `git worktree add -b` checkout per proposal (today's hive practice).
4//! * G2: one persistent worktree per agent; each proposal does `git checkout -B` back
5//! to the base, edits files, `git add`, and `git commit`.
6//! * G3: checkout-free plumbing with a per-agent temporary index (`GIT_INDEX_FILE`):
7//! copy the base index, `hash-object -w`, `update-index --index-info`, `write-tree`,
8//! `commit-tree`, `update-ref`.
9//! * G3F: G3 with `-c core.fsync=all -c core.fsyncMethod=fsync` on every command.
10//!
11//! Every arm keeps every proposal as a commit on its own branch (no deletes during timing).
12
13use crate::gitcmd::git_ok;
14use crate::path_str;
15use crate::workload::{EditOp, Proposal};
16use std::ffi::OsStr;
17use std::path::{Path, PathBuf};
18
19/// Extra config for the G3F arm (values from git-config(1), git 2.43).
20pub const FSYNC_ALL_CONFIG: &[(&str, &str)] =
21 &[("core.fsync", "all"), ("core.fsyncMethod", "fsync")];
22
23/// Branch name for one proposal.
24pub fn proposal_branch(agent: usize, index: usize) -> String {
25 format!("bench/a{agent:03}/p{index:05}")
26}
27
28fn commit_message(p: &Proposal) -> String {
29 format!("{}\n", p.summary)
30}
31
32/// Write the proposal's edits into a checked-out worktree and return the touched paths.
33pub fn apply_edits_to_worktree(wt: &Path, p: &Proposal) -> Result<Vec<String>, String> {
34 let mut paths = Vec::with_capacity(p.edits.len());
35 for e in &p.edits {
36 let target = wt.join(&e.path);
37 match &e.op {
38 EditOp::Upsert { content, .. } => {
39 if let Some(parent) = target.parent() {
40 std::fs::create_dir_all(parent)
41 .map_err(|err| format!("mkdir {}: {err}", parent.display()))?;
42 }
43 std::fs::write(&target, content.as_slice())
44 .map_err(|err| format!("write {}: {err}", target.display()))?;
45 }
46 EditOp::Delete => {
47 std::fs::remove_file(&target)
48 .map_err(|err| format!("remove {}: {err}", target.display()))?;
49 }
50 }
51 paths.push(e.path.clone());
52 }
53 Ok(paths)
54}
55
56fn add_and_commit(wt: &Path, p: &Proposal, paths: &[String]) -> Result<(), String> {
57 let mut args: Vec<&str> = vec!["add", "-A", "--"];
58 args.extend(paths.iter().map(|s| s.as_str()));
59 git_ok(wt, &[], &[], &args, None)?;
60 let msg = commit_message(p);
61 git_ok(wt, &[], &[], &["commit", "-q", "-m", &msg], None)?;
62 Ok(())
63}
64
65/// G1 operation: new worktree and branch at the base, edit, add, commit.
66pub fn g1_op(clone: &Path, base: &str, wt_root: &Path, p: &Proposal) -> Result<PathBuf, String> {
67 let wt = wt_root.join(format!("a{:03}-p{:05}", p.agent, p.index));
68 let branch = proposal_branch(p.agent, p.index);
69 git_ok(
70 clone,
71 &[],
72 &[],
73 &["worktree", "add", "-q", "-b", &branch, path_str(&wt)?, base],
74 None,
75 )?;
76 let paths = apply_edits_to_worktree(&wt, p)?;
77 add_and_commit(&wt, p, &paths)?;
78 Ok(wt)
79}
80
81/// G2 setup: one detached worktree per agent at the base (counted as setup, not per op).
82pub fn g2_setup_agent(
83 clone: &Path,
84 base: &str,
85 wt_root: &Path,
86 agent: usize,
87) -> Result<PathBuf, String> {
88 let wt = wt_root.join(format!("agent-{agent:03}"));
89 git_ok(
90 clone,
91 &[],
92 &[],
93 &["worktree", "add", "-q", "--detach", path_str(&wt)?, base],
94 None,
95 )?;
96 Ok(wt)
97}
98
99/// G2 operation: reset the agent's worktree to a new branch at the base, edit, add, commit.
100pub fn g2_op(wt: &Path, base: &str, p: &Proposal) -> Result<(), String> {
101 let branch = proposal_branch(p.agent, p.index);
102 git_ok(wt, &[], &[], &["checkout", "-q", "-B", &branch, base], None)?;
103 let paths = apply_edits_to_worktree(wt, p)?;
104 add_and_commit(wt, p, &paths)
105}
106
107/// Per-agent state for the plumbing arms.
108#[derive(Debug, Clone)]
109pub struct PlumbingAgent {
110 pub template_index: PathBuf,
111 pub work_index: PathBuf,
112 pub scratch_dir: PathBuf,
113}
114
115/// G3/G3F setup: build the agent's base index once with `git read-tree`.
116pub fn g3_setup_agent(
117 clone: &Path,
118 base: &str,
119 agent_root: &Path,
120 agent: usize,
121 config: &[(&str, &str)],
122) -> Result<PlumbingAgent, String> {
123 let dir = agent_root.join(format!("agent-{agent:03}"));
124 let scratch_dir = dir.join("scratch");
125 std::fs::create_dir_all(&scratch_dir)
126 .map_err(|e| format!("mkdir {}: {e}", scratch_dir.display()))?;
127 let template_index = dir.join("base.index");
128 let env: [(&str, &OsStr); 1] = [("GIT_INDEX_FILE", template_index.as_os_str())];
129 git_ok(clone, config, &env, &["read-tree", base], None)?;
130 Ok(PlumbingAgent {
131 template_index,
132 work_index: dir.join("work.index"),
133 scratch_dir,
134 })
135}
136
137/// G3/G3F operation: build a commit for `p` without any working-tree checkout.
138/// Returns the new commit OID (hex).
139pub fn g3_op(
140 clone: &Path,
141 base: &str,
142 agent: &PlumbingAgent,
143 p: &Proposal,
144 config: &[(&str, &str)],
145) -> Result<String, String> {
146 std::fs::copy(&agent.template_index, &agent.work_index)
147 .map_err(|e| format!("copy base index: {e}"))?;
148 let env: [(&str, &OsStr); 1] = [("GIT_INDEX_FILE", agent.work_index.as_os_str())];
149
150 let mut scratch_paths = String::new();
151 let mut upsert_meta: Vec<(&str, &str)> = Vec::new();
152 for (n, e) in p.edits.iter().enumerate() {
153 if let EditOp::Upsert { mode, content } = &e.op {
154 let f = agent.scratch_dir.join(format!("blob-{n}"));
155 std::fs::write(&f, content.as_slice())
156 .map_err(|err| format!("write scratch {}: {err}", f.display()))?;
157 scratch_paths.push_str(path_str(&f)?);
158 scratch_paths.push('\n');
159 upsert_meta.push((mode.git_octal_str(), e.path.as_str()));
160 }
161 }
162 let oids: Vec<String> = if upsert_meta.is_empty() {
163 Vec::new()
164 } else {
165 let out = git_ok(
166 clone,
167 config,
168 &[],
169 &["hash-object", "-w", "--no-filters", "--stdin-paths"],
170 Some(scratch_paths.into_bytes()),
171 )?;
172 String::from_utf8_lossy(&out)
173 .lines()
174 .map(|l| l.trim().to_string())
175 .collect()
176 };
177 if oids.len() != upsert_meta.len() {
178 return Err(format!(
179 "hash-object returned {} ids for {} blobs",
180 oids.len(),
181 upsert_meta.len()
182 ));
183 }
184
185 let mut index_info = String::new();
186 let mut oid_iter = oids.iter();
187 let mut meta_iter = upsert_meta.iter();
188 for e in &p.edits {
189 match &e.op {
190 EditOp::Upsert { .. } => {
191 let (mode, path) = meta_iter.next().ok_or("upsert metadata underflow")?;
192 let oid = oid_iter.next().ok_or("hash-object id underflow")?;
193 index_info.push_str(&format!("{mode} {oid}\t{path}\n"));
194 }
195 EditOp::Delete => {
196 index_info.push_str(&format!(
197 "0 0000000000000000000000000000000000000000\t{}\n",
198 e.path
199 ));
200 }
201 }
202 }
203 git_ok(
204 clone,
205 config,
206 &env,
207 &["update-index", "--index-info"],
208 Some(index_info.into_bytes()),
209 )?;
210 let tree = git_ok(clone, config, &env, &["write-tree"], None)?;
211 let tree = String::from_utf8_lossy(&tree).trim().to_string();
212 let msg = commit_message(p);
213 let commit = git_ok(
214 clone,
215 config,
216 &[],
217 &["commit-tree", &tree, "-p", base, "-m", &msg],
218 None,
219 )?;
220 let commit = String::from_utf8_lossy(&commit).trim().to_string();
221 let refname = format!("refs/heads/{}", proposal_branch(p.agent, p.index));
222 git_ok(clone, config, &[], &["update-ref", &refname, &commit], None)?;
223 Ok(commit)
224}
225
226/// Remove every worktree directory under `wt_root` and prune their registrations.
227pub fn remove_worktrees(clone: &Path, wt_root: &Path) -> Result<(), String> {
228 if wt_root.exists() {
229 std::fs::remove_dir_all(wt_root)
230 .map_err(|e| format!("remove {}: {e}", wt_root.display()))?;
231 }
232 git_ok(clone, &[], &[], &["worktree", "prune"], None)?;
233 Ok(())
234}
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239 use crate::fixture::test_support::{make_fixture_repo, temp_dir};
240 use crate::fixture::{
241 clone_no_checkout, configure_bench_clone, list_base_tree, load_editable_files,
242 };
243 use crate::gitcmd::git_line;
244 use crate::workload::generate_write_workload;
245
246 #[test]
247 fn all_git_arms_produce_identical_trees_for_the_same_proposal() {
248 let root = temp_dir("git-arms");
249 let commit = make_fixture_repo(&root, 10, 24);
250 let clone = root.join("clone");
251 clone_no_checkout(&root.join("fixture"), &clone).unwrap();
252 configure_bench_clone(&clone).unwrap();
253 let base = list_base_tree(&clone, &commit).unwrap();
254 let files = load_editable_files(&clone, &base).unwrap();
255 let work = generate_write_workload(11, 0, 1, 6, &files);
256
257 let wt_root = root.join("g1");
258 let agent_root = root.join("g3");
259 let g2_wt = g2_setup_agent(&clone, &commit, &root.join("g2"), 0).unwrap();
260 let plumbing = g3_setup_agent(&clone, &commit, &agent_root, 0, &[]).unwrap();
261 let plumbing_f = g3_setup_agent(&clone, &commit, &agent_root, 1, FSYNC_ALL_CONFIG).unwrap();
262
263 for p in &work[0] {
264 let g1_wt = g1_op(&clone, &commit, &wt_root, p).unwrap();
265 let g1_tree = git_line(&g1_wt, &["rev-parse", "HEAD^{tree}"]).unwrap();
266 remove_worktrees(&clone, &wt_root).unwrap();
267 g2_op(&g2_wt, &commit, p).unwrap();
268 let g2_tree = git_line(&g2_wt, &["rev-parse", "HEAD^{tree}"]).unwrap();
269 let g3_commit = g3_op(&clone, &commit, &plumbing, p, &[]).unwrap();
270 let g3_tree =
271 git_line(&clone, &["rev-parse", &format!("{g3_commit}^{{tree}}")]).unwrap();
272 let g3f_commit = g3_op(&clone, &commit, &plumbing_f, p, FSYNC_ALL_CONFIG).unwrap();
273 let g3f_tree =
274 git_line(&clone, &["rev-parse", &format!("{g3f_commit}^{{tree}}")]).unwrap();
275 assert_eq!(g1_tree, g2_tree);
276 assert_eq!(g2_tree, g3_tree);
277 assert_eq!(g3_tree, g3f_tree);
278 }
279 remove_worktrees(&clone, &wt_root).unwrap();
280 remove_worktrees(&clone, &root.join("g2")).unwrap();
281 let listed = git_line(&clone, &["worktree", "list"]).unwrap();
282 assert_eq!(listed.lines().count(), 1);
283 let _ = std::fs::remove_dir_all(&root);
284 }
285}