Debian Codegraph @

cli/tests/test_concurrent_operations.rs

raw
1 // Copyright 2022 The Jujutsu Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use itertools::Itertools as _;
16 use testutils::TestResult;
17
18 use crate::common::CommandOutput;
19 use crate::common::TestEnvironment;
20 use crate::common::TestWorkDir;
21
22 #[test]
23 fn test_concurrent_operation_divergence() -> TestResult {
24 let test_env = TestEnvironment::default();
25 test_env.run_jj_in(".", ["git", "init", "repo"]).success();
26 let work_dir = test_env.work_dir("repo");
27
28 work_dir.run_jj(["describe", "-m", "message 1"]).success();
29 work_dir
30 .run_jj(["describe", "-m", "message 2", "--at-op", "@-"])
31 .success();
32
33 // "--at-op=@" disables op heads merging, and prints head operation ids.
34 let output = work_dir.run_jj(["op", "log", "--at-op=@"]);
35 insta::assert_snapshot!(output, @r#"
36 ------- stderr -------
37 Error: The "@" expression resolved to more than one operation
38 Hint: Try specifying one of the operations by ID: ea7c53a69ce3, 4633795cf208
39 [EOF]
40 [exit status: 1]
41 "#);
42
43 // "op log --at-op" should work without merging the head operations
44 let output = work_dir.run_jj(["op", "log", "--at-op=4633795cf208"]);
45 insta::assert_snapshot!(output, @"
46 @ 4633795cf208 [email protected] default@ 2001-02-03 04:05:09.000 +07:00 - 2001-02-03 04:05:09.000 +07:00
47 │ describe commit e8849ae12c709f2321908879bc724fdb2ab8a781
48 │ args: jj describe -m 'message 2' --at-op @-
49 ○ f63ee16f9553 [email protected] 2001-02-03 04:05:07.000 +07:00 - 2001-02-03 04:05:07.000 +07:00
50 │ add workspace 'default'
51 ○ 000000000000 root()
52 [EOF]
53 ");
54
55 // We should be informed about the concurrent modification
56 let output = get_log_output(&work_dir);
57 insta::assert_snapshot!(output, @"
58 @ message 1
59 │ ○ message 2
60 ├─╯
61 ◆
62 [EOF]
63 ------- stderr -------
64 Concurrent modification detected, resolving automatically.
65 [EOF]
66 ");
67 Ok(())
68 }
69
70 #[test]
71 fn test_concurrent_operations_auto_rebase() {
72 let test_env = TestEnvironment::default();
73 test_env.run_jj_in(".", ["git", "init", "repo"]).success();
74 let work_dir = test_env.work_dir("repo");
75
76 work_dir.write_file("file", "contents");
77 work_dir.run_jj(["describe", "-m", "initial"]).success();
78 work_dir.run_jj(["describe", "-m", "rewritten"]).success();
79 work_dir
80 .run_jj(["new", "--at-op=@-", "-m", "new child"])
81 .success();
82
83 // We should be informed about the concurrent modification
84 let output = get_log_output(&work_dir);
85 insta::assert_snapshot!(output, @r"
86 ○ new child
87 @ rewritten
88 ◆
89 [EOF]
90 ------- stderr -------
91 Concurrent modification detected, resolving automatically.
92 Rebased 1 descendant commits onto commits rewritten by other operation.
93 [EOF]
94 ");
95 }
96
97 #[test]
98 fn test_concurrent_operations_wc_modified() {
99 let test_env = TestEnvironment::default();
100 test_env.run_jj_in(".", ["git", "init", "repo"]).success();
101 let work_dir = test_env.work_dir("repo");
102
103 work_dir.write_file("file", "contents\n");
104 work_dir.run_jj(["describe", "-m", "initial"]).success();
105 work_dir.run_jj(["new", "-m", "new child1"]).success();
106 work_dir
107 .run_jj(["new", "--at-op=@-", "-m", "new child2"])
108 .success();
109 work_dir.write_file("file", "modified\n");
110
111 // We should be informed about the concurrent modification
112 let output = get_log_output(&work_dir);
113 insta::assert_snapshot!(output, @"
114 @ new child1
115 │ ○ new child2
116 ├─╯
117 ○ initial
118 ◆
119 [EOF]
120 ------- stderr -------
121 Concurrent modification detected, resolving automatically.
122 [EOF]
123 ");
124 let output = work_dir.run_jj(["diff", "--git"]);
125 insta::assert_snapshot!(output, @"
126 diff --git a/file b/file
127 index 12f00e90b6..2e0996000b 100644
128 --- a/file
129 +++ b/file
130 @@ -1,1 +1,1 @@
131 -contents
132 +modified
133 [EOF]
134 ");
135
136 // The working copy should be committed after merging the operations
137 let output = work_dir.run_jj(["op", "log", "-Tdescription"]);
138 insta::assert_snapshot!(output, @"
139 @ snapshot working copy
140 ○ reconcile divergent operations
141 ├─╮
142 ○ │ new empty commit
143 │ ○ new empty commit
144 ├─╯
145 ○ describe commit 9a462e35578a347e6a3951bf7a58ad7146959a8b
146 ○ snapshot working copy
147 ○ add workspace 'default'
148 ○
149 [EOF]
150 ");
151 }
152
153 #[test]
154 fn test_concurrent_snapshot_wc_reloadable() -> TestResult {
155 let test_env = TestEnvironment::default();
156 test_env.run_jj_in(".", ["git", "init", "repo"]).success();
157 let work_dir = test_env.work_dir("repo");
158 let op_heads_dir = work_dir
159 .root()
160 .join(".jj")
161 .join("repo")
162 .join("op_heads")
163 .join("heads");
164
165 work_dir.write_file("base", "");
166 work_dir.run_jj(["commit", "-m", "initial"]).success();
167
168 // Create new commit and checkout it.
169 work_dir.write_file("child1", "");
170 work_dir.run_jj(["commit", "-m", "new child1"]).success();
171
172 let template = r#"id.short() ++ "\n" ++ description ++ "\n" ++ attributes"#;
173 let output = work_dir.run_jj(["op", "log", "-T", template]);
174 insta::assert_snapshot!(output, @"
175 @ 19e98b8a85da
176 │ commit c91a0909a9d3f3d8392ba9fab88f4b40fc0810ee
177 │ args: jj commit -m 'new child1'
178 ○ 55121d9434d0
179 │ snapshot working copy
180 │ args: jj commit -m 'new child1'
181 ○ 9f9c49403b99
182 │ commit 9af4c151edead0304de97ce3a0b414552921a425
183 │ args: jj commit -m initial
184 ○ 42ddf0a4e4f1
185 │ snapshot working copy
186 │ args: jj commit -m initial
187 ○ f63ee16f9553
188 │ add workspace 'default'
189 ○ 000000000000
190
191 [EOF]
192 ");
193 let template = r#"id ++ "\n""#;
194 let output = work_dir.run_jj(["op", "log", "--no-graph", "-T", template]);
195 let [op_id_after_snapshot, _, op_id_before_snapshot] =
196 output.stdout.raw().lines().next_array().unwrap();
197 insta::assert_snapshot!(op_id_after_snapshot[..12], @"19e98b8a85da");
198 insta::assert_snapshot!(op_id_before_snapshot[..12], @"9f9c49403b99");
199
200 // Simulate a concurrent operation that began from the "initial" operation
201 // (before the "child1" snapshot) but finished after the "child1"
202 // snapshot and commit.
203 std::fs::rename(
204 op_heads_dir.join(op_id_after_snapshot),
205 op_heads_dir.join(op_id_before_snapshot),
206 )?;
207 work_dir.write_file("child2", "");
208 let output = work_dir.run_jj(["describe", "-m", "new child2"]);
209 insta::assert_snapshot!(output, @"
210 ------- stderr -------
211 Working copy (@) now at: kkmpptxz 493da83e new child2
212 Parent commit (@-) : rlvkpnrz 15bd889d new child1
213 [EOF]
214 ");
215
216 // Since the repo can be reloaded before snapshotting, "child2" should be
217 // a child of "child1", not of "initial".
218 let output = work_dir.run_jj(["log", "-T", "description", "-s"]);
219 insta::assert_snapshot!(output, @"
220 @ new child2
221 │ A child2
222 ○ new child1
223 │ A child1
224 ○ initial
225 │ A base
226 ◆
227 [EOF]
228 ");
229 Ok(())
230 }
231
232 #[test]
233 fn test_git_head_race_condition() -> TestResult {
234 // Test for race condition where concurrent jj processes create divergent
235 // operations when importing/exporting Git HEAD. This test spawns two
236 // processes in parallel: one running `jj debug snapshot` repeatedly
237 // (which imports Git HEAD) and another running `jj next/prev` repeatedly
238 // (which exports Git HEAD). Without the fix, this would create divergent
239 // operations.
240
241 let test_env = TestEnvironment::default();
242 test_env
243 .run_jj_in(".", ["git", "init", "--colocate", "repo"])
244 .success();
245 let work_dir = test_env.work_dir("repo");
246
247 // Create a large initial working copy to make snapshotting slower
248 for j in 0..200 {
249 let filename = format!("file_{j}");
250 let content = format!("content for file {j}\n").repeat(100);
251 work_dir.write_file(&filename, &content);
252 }
253 work_dir.run_jj(["commit", "-m", "initial"]).success();
254
255 // Remember the initial commit for later verification
256 let initial_commit = work_dir
257 .run_jj(["log", "--no-graph", "-T=commit_id", "-r=@-"])
258 .success()
259 .stdout
260 .into_raw();
261 let initial_commit = initial_commit.trim().to_owned();
262
263 // Create additional commits to iterate through with jj next/prev
264 for i in 0..10 {
265 for j in 0..50 {
266 let filename = format!("file_{i}_{j}");
267 let content = format!("content for commit {i} file {j}\n").repeat(100);
268 work_dir.write_file(&filename, &content);
269 }
270 work_dir
271 .run_jj(["commit", "-m", &format!("commit {i}")])
272 .success();
273 }
274
275 // Extract environment from TestEnvironment to use in spawned processes
276 let base_cmd = test_env.new_jj_cmd();
277 let jj_bin = base_cmd.get_program().to_owned();
278 let base_env: Vec<_> = base_cmd
279 .get_envs()
280 .filter_map(|(k, v)| v.map(|v| (k.to_owned(), v.to_owned())))
281 // Filter out timestamp and randomness seed so each command gets different values
282 .filter(|(k, _)| k != "JJ_TIMESTAMP" && k != "JJ_OP_TIMESTAMP" && k != "JJ_RANDOMNESS_SEED")
283 .collect();
284
285 let repo_path = work_dir.root();
286 let duration = std::time::Duration::from_secs(5);
287 let start = std::time::Instant::now();
288
289 std::thread::scope(|s| {
290 s.spawn(|| {
291 while start.elapsed() < duration {
292 // Snapshot repeatedly without delay
293 let mut cmd = std::process::Command::new(&jj_bin);
294 cmd.current_dir(repo_path);
295 cmd.args(["debug", "snapshot"]);
296 for (key, value) in &base_env {
297 cmd.env(key, value);
298 }
299 let output = cmd.output().expect("Failed to spawn jj");
300 assert!(output.status.success(), "jj debug snapshot failed");
301 }
302 });
303
304 s.spawn(|| {
305 let mut count = 0;
306 while start.elapsed() < duration {
307 // Go through commit history back and forth
308 let direction = if count % 20 < 10 { "prev" } else { "next" };
309 let mut cmd = std::process::Command::new(&jj_bin);
310 cmd.current_dir(repo_path);
311 cmd.arg(direction);
312 for (key, value) in &base_env {
313 cmd.env(key, value);
314 }
315 let output = cmd.output().expect("Failed to spawn jj");
316 assert!(output.status.success(), "jj {direction} failed");
317 count += 1;
318 }
319 });
320 });
321
322 const IMPORT_GIT_HEAD: &str = "import git head";
323
324 // Check for concurrent operations
325 let output = work_dir.run_jj(["op", "log", "-T", "description", "--ignore-working-copy"]);
326 let concurrent_count = output
327 .stdout
328 .raw()
329 .lines()
330 .filter(|line| line.contains(IMPORT_GIT_HEAD))
331 .count();
332
333 if concurrent_count > 0 {
334 eprintln!("Found {concurrent_count} concurrent operations:");
335 eprintln!("{}", output.stdout.raw());
336 panic!("Race condition detected: {concurrent_count} concurrent operations found");
337 }
338
339 // Verify the operation description for importing Git HEAD hasn't changed
340 // First ensure we're not already on the initial commit (prev/next loop may have
341 // ended there)
342 work_dir.run_jj(["new"]).success();
343 // Use git to checkout the initial commit, then trigger import
344 std::process::Command::new("git")
345 .current_dir(work_dir.root())
346 .args(["checkout", "-q", &initial_commit])
347 .status()?;
348
349 let last_op = work_dir
350 .run_jj(["op", "log", "-T", "description", "--limit=1"])
351 .success()
352 .stdout
353 .into_raw();
354
355 assert!(
356 last_op.contains(IMPORT_GIT_HEAD),
357 "Expected last operation to contain '{IMPORT_GIT_HEAD}', got: {last_op:?}"
358 );
359 Ok(())
360 }
361
362 #[must_use]
363 fn get_log_output(work_dir: &TestWorkDir) -> CommandOutput {
364 work_dir.run_jj(["log", "-T", "description"])
365 }