Skip to main content

dag/tests/
test_dag.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8use std::collections::HashMap;
9use std::ops::Deref;
10use std::ops::DerefMut;
11use std::sync::Arc;
12use std::sync::Mutex;
13
14use futures::StreamExt;
15use futures::TryStreamExt;
16use nonblocking::non_blocking;
17use nonblocking::non_blocking_result;
18use tracing::debug;
19
20use crate::CloneData;
21use crate::Dag;
22use crate::Group;
23use crate::Level;
24use crate::Result;
25use crate::Set;
26use crate::Vertex;
27use crate::VertexListWithOptions;
28use crate::ops::CheckIntegrity;
29use crate::ops::DagAddHeads;
30use crate::ops::DagAlgorithm;
31use crate::ops::DagExportCloneData;
32use crate::ops::DagExportPullData;
33use crate::ops::DagImportCloneData;
34use crate::ops::DagImportPullData;
35use crate::ops::DagPersistent;
36use crate::ops::DagStrip;
37use crate::ops::IdConvert;
38use crate::protocol;
39use crate::protocol::RemoteIdConvertProtocol;
40#[cfg(feature = "render")]
41use crate::render::render_dag;
42use crate::tests::DrawDag;
43
44/// Dag structure for testing purpose.
45pub struct TestDag {
46    pub dag: Dag,
47    pub seg_size: usize,
48    pub dir: tempfile::TempDir,
49    pub output: Arc<Mutex<Vec<String>>>,
50}
51
52impl TestDag {
53    /// Creates a `TestDag` for testing.
54    /// Side effect of the `TestDag` will be removed on drop.
55    pub fn new() -> Self {
56        Self::new_with_segment_size(3)
57    }
58
59    /// Crates a `TestDag` using the given ASCII.
60    ///
61    /// This is just `new`, followed by `drawdag`, with an extra rule that
62    /// comments like "# master: M" at the end can be used to specify master
63    /// heads .
64    pub fn draw(text: &str) -> Self {
65        let mut dag = Self::new();
66        let mut split = text.split("# master:");
67        let text = split.next().unwrap_or("");
68        let master = match split.next() {
69            Some(t) => t.split_whitespace().collect::<Vec<_>>(),
70            None => Vec::new(),
71        };
72        dag.drawdag(text, &master);
73        dag
74    }
75
76    /// Similar to `draw` but creates a lazy client so all vertexes
77    /// in the master group are lazy.
78    pub async fn draw_client(text: &str) -> Self {
79        let server = Self::draw(text);
80        // clone data won't include non-master group.
81        let mut client = server.client_cloned_data().await;
82        tracing::debug!("CLIENT");
83        #[cfg(test)]
84        tracing::debug!("CLIENT: {}", client.dump_state().await);
85        let non_master_heads = {
86            let all = server.dag.all().await.unwrap();
87            let non_master = all.difference(&server.dag.master_group().await.unwrap());
88            let heads = server.dag.heads(non_master).await.unwrap();
89            let iter = heads.iter().await.unwrap();
90            iter.try_collect::<Vec<_>>().await.unwrap()
91        };
92        let heads =
93            VertexListWithOptions::from(non_master_heads).with_desired_group(Group::NON_MASTER);
94        client
95            .dag
96            .add_heads_and_flush(&server.dag.dag_snapshot().unwrap(), &heads)
97            .await
98            .unwrap();
99        client
100    }
101
102    /// Creates a `TestDag` with a specific segment size.
103    pub fn new_with_segment_size(seg_size: usize) -> Self {
104        let dir = tempfile::tempdir().unwrap();
105        let dag = Dag::open(dir.path().join("n")).unwrap();
106        Self {
107            dir,
108            dag,
109            seg_size,
110            output: Default::default(),
111        }
112    }
113
114    /// Reopen the dag. Drop in-memory state including caches.
115    pub fn reopen(&mut self) {
116        let mut dag = Dag::open(self.dir.path().join("n")).unwrap();
117        dag.set_remote_protocol(self.dag.get_remote_protocol());
118        self.dag = dag;
119    }
120
121    /// Add vertexes to the graph. Does not resolve vertexes remotely.
122    pub fn drawdag(&mut self, text: &str, master_heads: &[&str]) {
123        self.drawdag_with_limited_heads(text, master_heads, None);
124    }
125
126    /// Add vertexes to the graph. Async version that might resolve vertexes
127    /// remotely on demand.
128    pub async fn drawdag_async(&mut self, text: &str, master_heads: &[&str]) {
129        // Do not call self.validate to avoid fetching vertexes remotely.
130        self.drawdag_with_limited_heads_async(text, master_heads, None, false)
131            .await
132    }
133
134    /// Add vertexes to the graph.
135    ///
136    /// If `heads` is set, ignore part of the graph. Only consider specified
137    /// heads.
138    pub fn drawdag_with_limited_heads(
139        &mut self,
140        text: &str,
141        master_heads: &[&str],
142        heads: Option<&[&str]>,
143    ) {
144        non_blocking(self.drawdag_with_limited_heads_async(text, master_heads, heads, true))
145            .unwrap()
146    }
147
148    pub async fn drawdag_with_limited_heads_async(
149        &mut self,
150        text: &str,
151        master_heads: &[&str],
152        heads: Option<&[&str]>,
153        validate: bool,
154    ) {
155        let (all_heads, parent_func) = get_heads_and_parents_func_from_ascii(text);
156        let heads = match heads {
157            Some(heads) => heads
158                .iter()
159                .map(|s| Vertex::copy_from(s.as_bytes()))
160                .collect(),
161            None => all_heads,
162        };
163        self.dag.dag.set_new_segment_size(self.seg_size);
164        self.dag
165            .add_heads(&parent_func, &heads.into())
166            .await
167            .unwrap();
168        if validate {
169            self.validate().await;
170        }
171        let problems = self.dag.check_segments().await.unwrap();
172        assert!(problems.is_empty(), "problems after drawdag: {problems:?}");
173        let master_heads = master_heads
174            .iter()
175            .map(|s| Vertex::copy_from(s.as_bytes()))
176            .collect::<Vec<_>>();
177        let need_flush = !master_heads.is_empty();
178        if need_flush {
179            let heads = VertexListWithOptions::from(master_heads).with_desired_group(Group::MASTER);
180            self.dag.flush(&heads).await.unwrap();
181        }
182        if validate {
183            self.validate().await;
184        }
185        assert_eq!(self.dag.check_segments().await.unwrap(), [] as [String; 0]);
186    }
187
188    /// Add one vertex to the non-master group. `parents` is split by whitespaces.
189    pub async fn add_one_vertex(&mut self, name: &str, parents: &str) {
190        let name = Vertex::copy_from(name.as_bytes());
191        let parents: Vec<Vertex> = parents
192            .split_whitespace()
193            .map(|s| Vertex::copy_from(s.as_bytes()))
194            .collect();
195        let heads =
196            VertexListWithOptions::from(&[name.clone()][..]).with_desired_group(Group::NON_MASTER);
197        self.dag
198            .add_heads(
199                &std::iter::once((name, parents)).collect::<HashMap<Vertex, Vec<Vertex>>>(),
200                &heads,
201            )
202            .await
203            .unwrap();
204    }
205
206    /// Flush space-separated master heads.
207    pub async fn flush(&mut self, master_heads: &str) {
208        let heads: Vec<Vertex> = master_heads
209            .split_whitespace()
210            .map(|v| Vertex::copy_from(v.as_bytes()))
211            .collect();
212        let heads = VertexListWithOptions::from(heads).with_desired_group(Group::MASTER);
213        self.dag.flush(&heads).await.unwrap();
214    }
215
216    /// Replace ASCII with Ids in the graph.
217    pub fn annotate_ascii(&self, text: &str) -> String {
218        self.dag.map.replace(text)
219    }
220
221    /// Render the segments.
222    pub fn render_segments(&self) -> String {
223        format!("{:?}", self.dag.dag)
224    }
225
226    #[cfg(feature = "render")]
227    /// Render the graph.
228    pub fn render_graph(&self) -> String {
229        render_dag(&self.dag, |v| {
230            Some(
231                non_blocking_result(self.dag.vertex_id(v.clone()))
232                    .unwrap()
233                    .to_string(),
234            )
235        })
236        .unwrap()
237    }
238
239    /// Use this DAG as the "server", return the "client" Dag that has lazy Vertexes.
240    pub async fn client(&self) -> TestDag {
241        let mut client = TestDag::new();
242        client.set_remote(self);
243        client
244    }
245
246    /// Update remote protocol to use the (updated) server graph.
247    pub fn set_remote(&mut self, server_dag: &Self) {
248        let remote = server_dag.remote_protocol(self.output.clone());
249        self.dag.set_remote_protocol(remote);
250    }
251
252    /// Alternative syntax of `set_remote`.
253    pub fn with_remote(mut self, server_dag: &Self) -> Self {
254        self.set_remote(server_dag);
255        self
256    }
257
258    /// Similar to `client`, but also clone the Dag from the server.
259    pub async fn client_cloned_data(&self) -> TestDag {
260        let mut client = self.client().await;
261        let data = self.dag.export_clone_data().await.unwrap();
262        tracing::debug!("clone data: {:?}", &data);
263        client.dag.import_clone_data(data).await.unwrap();
264        client
265    }
266
267    /// Pull from the server Dag using the master fast forward fast path.
268    pub async fn pull_ff_master(
269        &mut self,
270        server: &Self,
271        old_master: impl Into<Set>,
272        new_master: impl Into<Set>,
273    ) -> Result<()> {
274        self.set_remote(server);
275        let old_master = old_master.into();
276        let new_master = new_master.into();
277        let pull_data = server
278            .export_pull_data(old_master.clone(), new_master.clone())
279            .await?;
280        let head_opts = to_head_opts(new_master);
281        self.import_pull_data(pull_data, head_opts).await?;
282        Ok(())
283    }
284
285    /// Generate the "pull data". This is intended to be called from a "server".
286    pub async fn export_pull_data(
287        &self,
288        common: impl Into<Set>,
289        heads: impl Into<Set>,
290    ) -> Result<CloneData<Vertex>> {
291        let missing = self.dag.only(heads.into(), common.into()).await?;
292        let data = self.dag.export_pull_data(&missing).await?;
293        debug!("export_pull_data: {:?}", &data);
294        Ok(data)
295    }
296
297    /// Imports the "pull data". This is intended to be called from a "client".
298    pub async fn import_pull_data(
299        &mut self,
300        pull_data: CloneData<Vertex>,
301        head_opts: impl Into<VertexListWithOptions>,
302    ) -> Result<()> {
303        let head_opts = head_opts.into();
304        self.dag.import_pull_data(pull_data, &head_opts).await?;
305        Ok(())
306    }
307
308    /// Strip space-separated vertexes.
309    pub async fn strip(&mut self, names: &'static str) {
310        let set = Set::from_static_names(names.split(' ').map(|s| s.into()));
311        self.dag.strip(&set).await.unwrap();
312        let problems = self.dag.check_segments().await.unwrap();
313        assert!(problems.is_empty(), "problems after strip: {problems:?}");
314    }
315
316    /// Remote protocol used to resolve Id <-> Vertex remotely using the test dag
317    /// as the "server".
318    ///
319    /// Logs of the remote access will be written to `output`.
320    pub fn remote_protocol(
321        &self,
322        output: Arc<Mutex<Vec<String>>>,
323    ) -> Arc<dyn RemoteIdConvertProtocol> {
324        let remote = ProtocolMonitor {
325            inner: Box::new(self.dag.try_snapshot().unwrap()),
326            output,
327        };
328        Arc::new(remote)
329    }
330
331    /// Describe segments at the given level and group as a string.
332    pub fn debug_segments(&self, level: Level, group: Group) -> String {
333        let lines =
334            crate::dag::debug_segments_by_level_group(&self.dag.dag, &self.dag.map, level, group);
335        lines
336            .iter()
337            .map(|l| format!("\n        {l}"))
338            .collect::<Vec<String>>()
339            .concat()
340    }
341
342    /// Output of remote protocols since the last call.
343    pub fn output(&self) -> Vec<String> {
344        let mut result = Vec::new();
345        let mut output = self.output.lock().unwrap();
346        std::mem::swap(&mut result, &mut *output);
347        result
348    }
349
350    /// Check that a vertex exists locally.
351    pub fn contains_vertex_locally(&self, name: impl Into<Vertex>) -> bool {
352        non_blocking_result(self.dag.contains_vertex_name_locally(&[name.into()])).unwrap()[0]
353    }
354
355    #[cfg(test)]
356    /// Dump Dag state as a string.
357    pub async fn dump_state(&self) -> String {
358        use crate::Id;
359        use crate::iddagstore::tests::dump_store_state;
360        let iddag = &self.dag.dag;
361        let all = iddag.all().unwrap();
362        let iddag_state = dump_store_state(&iddag.store, &all);
363        let all_str = format!("{:?}", self.dag.all().await.unwrap());
364        let idmap_state: String = {
365            let all: Vec<Id> = all.iter_asc().collect();
366            let contains = self.dag.contains_vertex_id_locally(&all).await.unwrap();
367            let local_ids: Vec<Id> = all
368                .into_iter()
369                .zip(contains)
370                .filter(|(_, c)| *c)
371                .map(|(i, _)| i)
372                .collect();
373            let local_vertexes = self
374                .dag
375                .vertex_name_batch(&local_ids)
376                .await
377                .unwrap()
378                .into_iter()
379                .collect::<Result<Vec<_>>>()
380                .unwrap();
381            local_ids
382                .into_iter()
383                .zip(local_vertexes)
384                .map(|(i, v)| format!("{i:?}->{v:?}"))
385                .collect::<Vec<_>>()
386                .join(" ")
387        };
388
389        format!("{all_str}{iddag_state}\n{idmap_state}")
390    }
391
392    #[cfg(test)]
393    /// Dump Dag segments as ASCII string.
394    pub fn dump_segments_ascii(&self) -> String {
395        use std::collections::HashSet;
396
397        use crate::Id;
398        use crate::IdSet;
399        use crate::IdSpan;
400
401        let span_iter = |span: IdSpan| IdSet::from_spans(vec![span]).into_iter().rev();
402        let iddag = &self.dag.dag;
403        let all_ids = iddag.all_ids_in_groups(&Group::ALL).unwrap();
404        let max_level = iddag.max_level().unwrap();
405        let mut output = String::new();
406        for level in 0..=max_level {
407            output = format!("{}\n        Lv{}:", output.trim_end(), level);
408            for span in all_ids.iter_span_asc() {
409                output += " |";
410                let segments = iddag.segments_in_span_ascending(*span, level).unwrap();
411                let segment_ids: HashSet<Id> = segments
412                    .iter()
413                    .flat_map(|s| span_iter(s.span().unwrap()))
414                    .collect();
415                let segment_highs: HashSet<Id> =
416                    segments.iter().map(|s| s.high().unwrap()).collect();
417                for id in span_iter(*span) {
418                    let id_str = format!("{id:?}");
419                    if segment_ids.contains(&id) {
420                        output += &id_str
421                    } else {
422                        let space = " ".repeat(id_str.len());
423                        output += &space;
424                    };
425                    output.push(
426                        if segment_highs.contains(&id)
427                            || (segment_ids.contains(&(id + 1)) && !segment_ids.contains(&id))
428                        {
429                            '|'
430                        } else {
431                            ' '
432                        },
433                    );
434                }
435            }
436        }
437        output.trim_end().to_string()
438    }
439
440    async fn validate(&self) {
441        // All vertexes should be accessible, and round-trip through IdMap.
442        let mut iter = self.dag.all().await.unwrap().iter().await.unwrap();
443        while let Some(v) = iter.next().await {
444            let v = v.unwrap();
445            let id = self.dag.vertex_id(v.clone()).await.unwrap();
446            let v2 = self.dag.vertex_name(id).await.unwrap();
447            assert_eq!(v, v2);
448        }
449    }
450}
451
452impl Deref for TestDag {
453    type Target = Dag;
454
455    fn deref(&self) -> &Self::Target {
456        &self.dag
457    }
458}
459
460impl DerefMut for TestDag {
461    fn deref_mut(&mut self) -> &mut Self::Target {
462        &mut self.dag
463    }
464}
465
466pub(crate) struct ProtocolMonitor {
467    pub(crate) inner: Box<dyn RemoteIdConvertProtocol>,
468    pub(crate) output: Arc<Mutex<Vec<String>>>,
469}
470
471#[async_trait::async_trait]
472impl RemoteIdConvertProtocol for ProtocolMonitor {
473    async fn resolve_names_to_relative_paths(
474        &self,
475        heads: Vec<Vertex>,
476        names: Vec<Vertex>,
477    ) -> Result<Vec<(protocol::AncestorPath, Vec<Vertex>)>> {
478        let msg = format!("resolve names: {names:?}, heads: {heads:?}");
479        self.output.lock().unwrap().push(msg);
480        self.inner
481            .resolve_names_to_relative_paths(heads, names)
482            .await
483    }
484
485    async fn resolve_relative_paths_to_names(
486        &self,
487        paths: Vec<protocol::AncestorPath>,
488    ) -> Result<Vec<(protocol::AncestorPath, Vec<Vertex>)>> {
489        let msg = format!("resolve paths: {paths:?}");
490        self.output.lock().unwrap().push(msg);
491        self.inner.resolve_relative_paths_to_names(paths).await
492    }
493}
494
495fn get_heads_and_parents_func_from_ascii(text: &str) -> (Vec<Vertex>, DrawDag) {
496    let dag = DrawDag::from(text);
497    let heads = dag.heads();
498    (heads, dag)
499}
500
501#[cfg(test)]
502impl From<&'static str> for VertexListWithOptions {
503    fn from(names: &str) -> Self {
504        let set = Set::from(names);
505        set.into()
506    }
507}
508
509#[cfg(test)]
510impl From<Set> for VertexListWithOptions {
511    fn from(names: Set) -> Self {
512        to_head_opts(names)
513    }
514}
515
516fn to_head_opts(set: Set) -> VertexListWithOptions {
517    use crate::set::SyncSetQuery;
518    let heads_vec = set.iter().unwrap().collect::<Result<Vec<_>>>().unwrap();
519    VertexListWithOptions::from(heads_vec).with_desired_group(Group::MASTER)
520}