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

495 lines · 16663 bytes Raw Blame History
1//! Deterministic synthetic proposal workloads on top of a real base tree.
2//!
3//! Edit content is synthetic (inserted comment-style lines, new small text files,
4//! deletions of existing files); the base tree it applies to is real. Every arm in a
5//! given (tier, repetition) cell receives exactly the same proposals.
6
7use crate::fixture::{EditableFile, BENCH_PATH_PREFIX};
8use crate::rng::SplitMix64;
9use serde::{Deserialize, Serialize};
10use std::sync::Arc;
11use synapse_core::FileMode;
12
13/// Mutation applied to one path.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum EditOp {
16 Upsert {
17 mode: FileMode,
18 content: Arc<Vec<u8>>,
19 },
20 Delete,
21}
22
23/// One path-level edit inside a proposal.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct FileEdit {
26 pub path: String,
27 pub op: EditOp,
28}
29
30/// One agent proposal against the pinned base commit. `edits` are sorted by path
31/// (byte order) and unique, as `ChangesetEnvelope::validate` requires.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct Proposal {
34 pub agent: usize,
35 pub index: usize,
36 pub summary: String,
37 pub edits: Vec<FileEdit>,
38}
39
40impl Proposal {
41 /// Sum of upserted content bytes.
42 pub fn content_bytes(&self) -> u64 {
43 self.edits
44 .iter()
45 .map(|e| match &e.op {
46 EditOp::Upsert { content, .. } => content.len() as u64,
47 EditOp::Delete => 0,
48 })
49 .sum()
50 }
51}
52
53fn synthetic_lines(rng: &mut SplitMix64, tag: &str, count: usize) -> String {
54 let mut s = String::new();
55 for i in 0..count {
56 s.push_str(&format!(
57 "// synapse-gate4 {tag} line {i} {}\n",
58 rng.hex16()
59 ));
60 }
61 s
62}
63
64/// Insert a synthetic hunk of 3..=12 lines at a random line boundary.
65fn insert_hunk(rng: &mut SplitMix64, original: &[u8], tag: &str) -> Vec<u8> {
66 let text = String::from_utf8_lossy(original);
67 let lines: Vec<&str> = text.split_inclusive('\n').collect();
68 let at = rng.below(lines.len() + 1);
69 let count = rng.range(3, 12);
70 let hunk = synthetic_lines(rng, tag, count);
71 let mut out = String::with_capacity(original.len() + hunk.len() + 1);
72 for (i, line) in lines.iter().enumerate() {
73 if i == at {
74 out.push_str(&hunk);
75 }
76 out.push_str(line);
77 }
78 if at == lines.len() {
79 if !out.is_empty() && !out.ends_with('\n') {
80 out.push('\n');
81 }
82 out.push_str(&hunk);
83 }
84 out.into_bytes()
85}
86
87fn finalize(agent: usize, index: usize, mut edits: Vec<FileEdit>) -> Proposal {
88 edits.sort_by(|a, b| a.path.cmp(&b.path));
89 edits.dedup_by(|a, b| a.path == b.path);
90 Proposal {
91 agent,
92 index,
93 summary: format!("gate4 synthetic proposal agent {agent} index {index}"),
94 edits,
95 }
96}
97
98/// Generate proposal `index` for `agent`. Mix per proposal: 1 edit (50%), 2 (35%),
99/// or 3 (15%); each edit modifies an existing file (70%), adds a new file under
100/// [`BENCH_PATH_PREFIX`] (20%), or deletes an existing file (10%).
101pub fn generate_proposal(
102 seed: u64,
103 stream: &[u64],
104 agent: usize,
105 index: usize,
106 files: &[EditableFile],
107) -> Proposal {
108 let mut labels = stream.to_vec();
109 labels.extend_from_slice(&[agent as u64, index as u64]);
110 let mut rng = SplitMix64::derive(seed, &labels);
111 let roll = rng.below(100);
112 let n_edits = if roll < 50 {
113 1
114 } else if roll < 85 {
115 2
116 } else {
117 3
118 };
119 let mut edits: Vec<FileEdit> = Vec::new();
120 for j in 0..n_edits {
121 let kind = if files.is_empty() { 75 } else { rng.below(100) };
122 if !(70..90).contains(&kind) {
123 // Modify or delete an existing file not yet touched by this proposal.
124 let mut chosen = None;
125 for _ in 0..4 {
126 let f = &files[rng.below(files.len())];
127 if !edits.iter().any(|e| e.path == f.path) {
128 chosen = Some(f);
129 break;
130 }
131 }
132 let Some(f) = chosen else { continue };
133 let op = if kind < 70 {
134 let tag = format!("a{agent} p{index} e{j}");
135 EditOp::Upsert {
136 mode: FileMode::Regular644,
137 content: Arc::new(insert_hunk(&mut rng, &f.content, &tag)),
138 }
139 } else {
140 EditOp::Delete
141 };
142 edits.push(FileEdit {
143 path: f.path.clone(),
144 op,
145 });
146 } else {
147 let path = format!("{BENCH_PATH_PREFIX}/a{agent:03}/p{index:05}-e{j}.txt");
148 let lines = rng.range(4, 40);
149 let tag = format!("new a{agent} p{index} e{j}");
150 edits.push(FileEdit {
151 path,
152 op: EditOp::Upsert {
153 mode: FileMode::Regular644,
154 content: Arc::new(synthetic_lines(&mut rng, &tag, lines).into_bytes()),
155 },
156 });
157 }
158 }
159 if edits.is_empty() {
160 let path = format!("{BENCH_PATH_PREFIX}/a{agent:03}/p{index:05}-fallback.txt");
161 let tag = format!("fallback a{agent} p{index}");
162 edits.push(FileEdit {
163 path,
164 op: EditOp::Upsert {
165 mode: FileMode::Regular644,
166 content: Arc::new(synthetic_lines(&mut rng, &tag, 6).into_bytes()),
167 },
168 });
169 }
170 finalize(agent, index, edits)
171}
172
173/// Generate `ops_per_agent` proposals for each of `agents` agents. The stream labels
174/// are `[rep, agents]`, so all arms in one (tier, rep) cell get identical proposals and
175/// a shorter run (for example the capped G1 arm) receives a prefix of each agent's list.
176pub fn generate_write_workload(
177 seed: u64,
178 rep: usize,
179 agents: usize,
180 ops_per_agent: usize,
181 files: &[EditableFile],
182) -> Vec<Vec<Proposal>> {
183 (0..agents)
184 .map(|a| {
185 (0..ops_per_agent)
186 .map(|k| generate_proposal(seed, &[rep as u64, agents as u64], a, k, files))
187 .collect()
188 })
189 .collect()
190}
191
192/// Role a proposal plays in the conflict-correctness scenario.
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
194pub enum ScenarioGroup {
195 /// Whole-file rewrite of the shared hotspot file.
196 Hotspot,
197 /// Single-line change in a distinct region of the shared mergeable file.
198 DisjointHunk,
199 /// Adds a file at `<dir>/node`.
200 FileSide,
201 /// Adds a file below `<dir>/node/`.
202 DirectorySide,
203 /// Modifies the shared modify/delete file.
204 ModifySide,
205 /// Deletes the shared modify/delete file.
206 DeleteSide,
207 /// Adds the shared identical new file (byte-identical content).
208 IdenticalAdd,
209 /// Deletes the shared identically deleted file.
210 IdenticalDelete,
211 /// Edits only its own file.
212 Distinct,
213}
214
215/// Ground-truth relation between two scenario proposals.
216#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
217pub enum PairClass {
218 HotspotRewrite,
219 DisjointHunksSameFile,
220 FileDirectoryCollision,
221 ModifyDelete,
222 IdenticalChange,
223 DistinctPaths,
224}
225
226impl PairClass {
227 /// Expected under Synapse's documented path-level rule: same path with a different
228 /// operation, or a file/directory prefix collision between two upserts.
229 pub fn path_level_conflict_expected(self) -> bool {
230 matches!(
231 self,
232 Self::HotspotRewrite
233 | Self::DisjointHunksSameFile
234 | Self::FileDirectoryCollision
235 | Self::ModifyDelete
236 )
237 }
238
239 /// Expected outcome of a Git three-way merge (`git merge-tree --write-tree`).
240 pub fn git_conflict_expected(self) -> bool {
241 matches!(
242 self,
243 Self::HotspotRewrite | Self::FileDirectoryCollision | Self::ModifyDelete
244 )
245 }
246}
247
248/// Classify a pair purely from the declared generator roles (not from paths).
249pub fn classify_pair(a: ScenarioGroup, b: ScenarioGroup) -> PairClass {
250 use ScenarioGroup as G;
251 match (a, b) {
252 (G::Hotspot, G::Hotspot) => PairClass::HotspotRewrite,
253 (G::DisjointHunk, G::DisjointHunk) => PairClass::DisjointHunksSameFile,
254 (G::FileSide, G::DirectorySide) | (G::DirectorySide, G::FileSide) => {
255 PairClass::FileDirectoryCollision
256 }
257 (G::ModifySide, G::DeleteSide) | (G::DeleteSide, G::ModifySide) => PairClass::ModifyDelete,
258 (G::IdenticalAdd, G::IdenticalAdd) | (G::IdenticalDelete, G::IdenticalDelete) => {
259 PairClass::IdenticalChange
260 }
261 _ => PairClass::DistinctPaths,
262 }
263}
264
265/// A scenario proposal plus its declared role.
266#[derive(Debug, Clone)]
267pub struct ScenarioProposal {
268 pub proposal: Proposal,
269 pub group: ScenarioGroup,
270}
271
272fn replace_line(original: &[u8], line_idx: usize, new_line: &str) -> Vec<u8> {
273 let text = String::from_utf8_lossy(original);
274 let mut out = String::with_capacity(original.len() + new_line.len());
275 for (i, line) in text.split_inclusive('\n').enumerate() {
276 if i == line_idx {
277 out.push_str(new_line);
278 out.push('\n');
279 } else {
280 out.push_str(line);
281 }
282 }
283 out.into_bytes()
284}
285
286/// Minimum line count of the file used for disjoint-hunk edits.
287pub const MERGEABLE_MIN_LINES: usize = 60;
288
289/// Build the conflict-correctness scenario: 4 hotspot rewrites, 3 disjoint single-line
290/// edits of one file, a file/directory collision pair, a modify/delete pair, two
291/// identical adds (the second also edits its own file), two identical deletes, and 8
292/// proposals that each edit a distinct file. Needs at least 14 editable files, one of
293/// them with [`MERGEABLE_MIN_LINES`] or more lines.
294pub fn build_conflict_scenario(
295 seed: u64,
296 files: &[EditableFile],
297) -> Result<Vec<ScenarioProposal>, String> {
298 let mut rng = SplitMix64::derive(seed, &[0x0C0F_11C7]);
299 let mut order: Vec<usize> = (0..files.len()).collect();
300 rng.shuffle(&mut order);
301 let mergeable_pos = order
302 .iter()
303 .position(|&i| files[i].line_count >= MERGEABLE_MIN_LINES)
304 .ok_or("no editable file with enough lines for disjoint-hunk edits")?;
305 let mergeable = &files[order.remove(mergeable_pos)];
306 if order.len() < 13 {
307 return Err(format!(
308 "conflict scenario needs 14 editable files, found {}",
309 order.len() + 1
310 ));
311 }
312 let hotspot = &files[order[0]];
313 let moddel = &files[order[1]];
314 let iddel = &files[order[2]];
315 let distinct: Vec<&EditableFile> = order[3..12].iter().map(|&i| &files[i]).collect();
316
317 let mut out: Vec<ScenarioProposal> = Vec::new();
318 let mut push = |group: ScenarioGroup, edits: Vec<FileEdit>| {
319 let idx = out.len();
320 out.push(ScenarioProposal {
321 proposal: finalize(1000 + idx, idx, edits),
322 group,
323 });
324 };
325 let upsert = |path: &str, bytes: Vec<u8>| FileEdit {
326 path: path.to_string(),
327 op: EditOp::Upsert {
328 mode: FileMode::Regular644,
329 content: Arc::new(bytes),
330 },
331 };
332
333 for h in 0..4 {
334 let lines = rng.range(20, 40);
335 let body = synthetic_lines(&mut rng, &format!("hotspot rewrite {h}"), lines);
336 push(
337 ScenarioGroup::Hotspot,
338 vec![upsert(&hotspot.path, body.into_bytes())],
339 );
340 }
341 let n = mergeable.line_count;
342 for (k, line_idx) in [1usize, n / 2, n - 2].into_iter().enumerate() {
343 let new_line = format!("// synapse-gate4 disjoint hunk {k} {}", rng.hex16());
344 push(
345 ScenarioGroup::DisjointHunk,
346 vec![upsert(
347 &mergeable.path,
348 replace_line(&mergeable.content, line_idx, &new_line),
349 )],
350 );
351 }
352 let fd_file = format!("{BENCH_PATH_PREFIX}/fd/node");
353 let fd_child = format!("{BENCH_PATH_PREFIX}/fd/node/child.txt");
354 push(
355 ScenarioGroup::FileSide,
356 vec![upsert(&fd_file, b"file side\n".to_vec())],
357 );
358 push(
359 ScenarioGroup::DirectorySide,
360 vec![upsert(&fd_child, b"directory side\n".to_vec())],
361 );
362 push(
363 ScenarioGroup::ModifySide,
364 vec![upsert(
365 &moddel.path,
366 insert_hunk(&mut rng, &moddel.content, "modify side"),
367 )],
368 );
369 push(
370 ScenarioGroup::DeleteSide,
371 vec![FileEdit {
372 path: moddel.path.clone(),
373 op: EditOp::Delete,
374 }],
375 );
376 let shared_path = format!("{BENCH_PATH_PREFIX}/identical/shared.txt");
377 let shared_body = synthetic_lines(&mut rng, "identical add", 8).into_bytes();
378 push(
379 ScenarioGroup::IdenticalAdd,
380 vec![upsert(&shared_path, shared_body.clone())],
381 );
382 push(
383 ScenarioGroup::IdenticalAdd,
384 vec![
385 upsert(&shared_path, shared_body),
386 upsert(
387 &distinct[8].path,
388 insert_hunk(&mut rng, &distinct[8].content, "identical add extra"),
389 ),
390 ],
391 );
392 for _ in 0..2 {
393 push(
394 ScenarioGroup::IdenticalDelete,
395 vec![FileEdit {
396 path: iddel.path.clone(),
397 op: EditOp::Delete,
398 }],
399 );
400 }
401 for (d, f) in distinct.iter().take(8).enumerate() {
402 push(
403 ScenarioGroup::Distinct,
404 vec![upsert(
405 &f.path,
406 insert_hunk(&mut rng, &f.content, &format!("distinct {d}")),
407 )],
408 );
409 }
410 Ok(out)
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416
417 fn files(n: usize, lines: usize) -> Vec<EditableFile> {
418 (0..n)
419 .map(|i| {
420 let body: String = (0..lines).map(|l| format!("file {i} line {l}\n")).collect();
421 EditableFile {
422 path: format!("src/f{i:03}.rs"),
423 content: Arc::new(body.into_bytes()),
424 line_count: lines,
425 }
426 })
427 .collect()
428 }
429
430 #[test]
431 fn write_workload_is_deterministic_sorted_and_unique() {
432 let f = files(30, 20);
433 let a = generate_write_workload(9, 0, 3, 20, &f);
434 let b = generate_write_workload(9, 0, 3, 20, &f);
435 assert_eq!(a, b);
436 let c = generate_write_workload(9, 1, 3, 20, &f);
437 assert_ne!(a, c);
438 for agent in &a {
439 assert_eq!(agent.len(), 20);
440 for p in agent {
441 assert!(!p.edits.is_empty() && p.edits.len() <= 3);
442 for w in p.edits.windows(2) {
443 assert!(w[0].path < w[1].path, "edits must be strictly sorted");
444 }
445 }
446 }
447 // A shorter run is a prefix of the longer run for every agent.
448 let short = generate_write_workload(9, 0, 3, 5, &f);
449 for (s, l) in short.iter().zip(a.iter()) {
450 assert_eq!(s.as_slice(), &l[..5]);
451 }
452 }
453
454 #[test]
455 fn hunk_insertion_preserves_original_lines() {
456 let mut rng = SplitMix64::new(3);
457 let original = b"a\nb\nc\n";
458 let edited = insert_hunk(&mut rng, original, "t");
459 let text = String::from_utf8(edited).unwrap();
460 let kept: Vec<&str> = text
461 .lines()
462 .filter(|l| !l.starts_with("// synapse-gate4"))
463 .collect();
464 assert_eq!(kept, vec!["a", "b", "c"]);
465 }
466
467 #[test]
468 fn scenario_has_expected_shape_and_classes() {
469 let mut f = files(20, 30);
470 f[5] = EditableFile {
471 line_count: 80,
472 content: Arc::new(
473 (0..80)
474 .map(|l| format!("long {l}\n"))
475 .collect::<String>()
476 .into_bytes(),
477 ),
478 ..f[5].clone()
479 };
480 let s = build_conflict_scenario(5, &f).unwrap();
481 assert_eq!(s.len(), 23);
482 let count = |g: ScenarioGroup| s.iter().filter(|p| p.group == g).count();
483 assert_eq!(count(ScenarioGroup::Hotspot), 4);
484 assert_eq!(count(ScenarioGroup::DisjointHunk), 3);
485 assert_eq!(count(ScenarioGroup::Distinct), 8);
486 assert_eq!(
487 classify_pair(ScenarioGroup::FileSide, ScenarioGroup::DirectorySide),
488 PairClass::FileDirectoryCollision
489 );
490 assert!(PairClass::DisjointHunksSameFile.path_level_conflict_expected());
491 assert!(!PairClass::DisjointHunksSameFile.git_conflict_expected());
492 assert!(!PairClass::IdenticalChange.path_level_conflict_expected());
493 assert!(build_conflict_scenario(5, &files(20, 10)).is_err());
494 }
495}