Skip to main content

dag/
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
8//! # dag
9//!
10//! Combination of IdMap and IdDag.
11
12use std::collections::BTreeMap;
13use std::collections::HashMap;
14use std::collections::HashSet;
15use std::env::var;
16use std::fmt;
17use std::io;
18use std::ops::Deref;
19use std::sync::Arc;
20use std::sync::Mutex;
21use std::sync::RwLock;
22use std::sync::atomic::AtomicUsize;
23use std::sync::atomic::Ordering;
24
25use dag_types::FlatSegment;
26use futures::FutureExt;
27use futures::StreamExt;
28use futures::TryStreamExt;
29use futures::future::BoxFuture;
30use nonblocking::non_blocking_result;
31
32use crate::Error::NeedSlowPath;
33use crate::IdSet;
34use crate::IdSpan;
35use crate::Level;
36use crate::Result;
37use crate::VerLink;
38use crate::VertexListWithOptions;
39use crate::VertexOptions;
40use crate::clone::CloneData;
41use crate::default_impl;
42use crate::errors::DagError;
43use crate::errors::NotFoundError;
44use crate::errors::bug;
45use crate::errors::programming;
46use crate::id::Group;
47use crate::id::Id;
48use crate::id::Vertex;
49use crate::iddag::IdDag;
50use crate::iddag::IdDagAlgorithm;
51use crate::iddagstore::IdDagStore;
52use crate::idmap::CoreMemIdMap;
53use crate::idmap::IdMapAssignHead;
54use crate::idmap::IdMapWrite;
55use crate::lifecycle::LifecycleId;
56use crate::ops::CheckIntegrity;
57use crate::ops::DagAddHeads;
58use crate::ops::DagAlgorithm;
59use crate::ops::DagExportCloneData;
60use crate::ops::DagExportPullData;
61use crate::ops::DagImportCloneData;
62use crate::ops::DagImportPullData;
63use crate::ops::DagPersistent;
64use crate::ops::DagStrip;
65use crate::ops::IdConvert;
66use crate::ops::IdMapSnapshot;
67use crate::ops::Open;
68use crate::ops::Parents;
69use crate::ops::Persist;
70use crate::ops::PrefixLookup;
71use crate::ops::StorageVersion;
72use crate::ops::ToIdSet;
73use crate::ops::TryClone;
74use crate::protocol;
75use crate::protocol::AncestorPath;
76use crate::protocol::Process;
77use crate::protocol::RemoteIdConvertProtocol;
78use crate::protocol::is_remote_protocol_disabled;
79use crate::segment::PreparedFlatSegments;
80use crate::segment::SegmentFlags;
81use crate::set::Set;
82use crate::set::hints::Flags;
83use crate::set::hints::Hints;
84use crate::set::id_static::BasicIterationOrder;
85use crate::types_ext::PreparedFlatSegmentsExt;
86use crate::utils;
87
88mod builder;
89#[cfg(any(test, feature = "indexedlog-backend"))]
90mod indexedlog_dag;
91mod mem_dag;
92
93pub use builder::DagBuilder;
94#[cfg(any(test, feature = "indexedlog-backend"))]
95pub use indexedlog_dag::Dag;
96#[cfg(any(test, feature = "indexedlog-backend"))]
97pub use indexedlog_dag::IndexedLogDagPath;
98pub use mem_dag::MemDag;
99pub use mem_dag::MemDagPath;
100
101pub struct AbstractDag<I, M, P, S>
102where
103    I: Send + Sync,
104    M: Send + Sync,
105    P: Send + Sync,
106    S: Send + Sync,
107{
108    pub(crate) dag: I,
109    pub(crate) map: M,
110
111    /// A read-only snapshot of the `Dag`.
112    /// Lazily calculated.
113    snapshot: RwLock<Option<Arc<Self>>>,
114
115    /// Non-virtual heads added via `add_heads` that are not flushed yet.
116    /// They can be flushed by `flush()`.
117    pending_heads: VertexListWithOptions,
118
119    /// Path used to open this `Dag`.
120    path: P,
121
122    /// Extra state of the `Dag`.
123    state: S,
124
125    /// Identity of the dag. Derived from `path`.
126    id: String,
127
128    /// `Id`s that are persisted on disk. Used to answer `dirty()`.
129    persisted_id_set: IdSet,
130
131    /// Overlay IdMap. Used to store IdMap results resolved using remote
132    /// protocols.
133    overlay_map: Arc<RwLock<CoreMemIdMap>>,
134
135    /// `Id`s that are allowed in the `overlay_map`. A protection.
136    /// The `overlay_map` is shared (Arc) and its ID should not exceed the
137    /// existing maximum ID at `map` open time. The IDs from
138    /// 0..overlay_map_next_id are considered immutable, but lazy.
139    overlay_map_id_set: IdSet,
140
141    /// The source of `overlay_map`s. This avoids absolute Ids, and is
142    /// used to flush overlay_map content shall the IdMap change on
143    /// disk.
144    overlay_map_paths: Arc<Mutex<Vec<(AncestorPath, Vec<Vertex>)>>>,
145
146    /// How many vertexes from `overlay_map_paths` one flush may persist to
147    /// the on-disk IdMap. Bounds how much a command that resolves an unbounded
148    /// number of names, such as a scan of the whole history, can grow the
149    /// IdMap. 0 means no limit.
150    idmap_cache_flush_limit: usize,
151
152    /// Defines how to communicate with a remote service.
153    /// The actual logic probably involves networking like HTTP etc
154    /// and is intended to be implemented outside the `dag` crate.
155    remote_protocol: Arc<dyn RemoteIdConvertProtocol>,
156
157    /// If set, clear and insert to the VIRTUAL group after reloading.
158    managed_virtual_group: Option<Arc<(Box<dyn Parents>, VertexListWithOptions /* derived */)>>,
159
160    /// A negative cache. Vertexes that are looked up remotely, and the remote
161    /// confirmed the vertexes are outside the master group.
162    missing_vertexes_confirmed_by_remote: Arc<RwLock<HashSet<Vertex>>>,
163
164    /// Internal stats (for testing and debugging).
165    lifecycle_id: LifecycleId,
166    pub(crate) internal_stats: DagInternalStats,
167}
168
169/// Statistics of dag internals. Useful to check if fast paths are used.
170#[derive(Debug, Default)]
171pub struct DagInternalStats {
172    /// Bumps when sort(set) takes O(set) slow path.
173    pub sort_slow_path_count: AtomicUsize,
174}
175
176impl<D, M, P, S> AbstractDag<D, M, P, S>
177where
178    D: Send + Sync,
179    M: Send + Sync,
180    P: Send + Sync,
181    S: Send + Sync,
182{
183    /// Extract inner states. Useful for advanced use-cases.
184    pub fn into_idmap_dag(self) -> (M, D) {
185        (self.map, self.dag)
186    }
187
188    /// Extract inner states. Useful for advanced use-cases.
189    pub fn into_idmap_dag_path_state(self) -> (M, D, P, S) {
190        (self.map, self.dag, self.path, self.state)
191    }
192}
193
194impl<IS, M, P, S> AbstractDag<IdDag<IS>, M, P, S>
195where
196    IS: IdDagStore,
197    IdDag<IS>: TryClone,
198    M: Send + Sync + IdMapWrite + IdMapAssignHead + TryClone + 'static,
199    P: Send + Sync + TryClone + 'static,
200    S: Send + Sync + TryClone + 'static,
201{
202    /// Set the content of the VIRTUAL group that survives reloading.
203    ///
204    /// `items` is a list of vertexes and parents. The vertexes MUST be unique
205    /// and not already exist in non-VIRTUAL groups. This assumption is used
206    /// as an optimization to avoid remote lookups.
207    ///
208    /// Existing content of the VIRTUAL group will be cleared before inserting
209    /// `items`. So this API feels declarative. As a comparison, `add_heads`
210    /// is imperative.
211    ///
212    /// This function calls `maybe_recreate_virtual_group` immediately to clear
213    /// and update contents in the VIRTUAL group. `maybe_recreate_virtual_group`
214    /// will be called automatically after graph changing operations:
215    /// `add_heads_and_flush`, `strip`, `flush`, `import_pull_data`.
216    pub async fn set_managed_virtual_group(
217        &mut self,
218        items: Option<Vec<(Vertex, Vec<Vertex>)>>,
219    ) -> Result<()> {
220        tracing::debug!(target: "dag::set_managed_virtual_group", lifecycle_id=?self.lifecycle_id, ?items);
221        self.managed_virtual_group = items.map(|items| {
222            // Calculate `Parents` and `VertexListWithOptions` so they can be
223            // used in `maybe_recreate_virtual_group`.
224            let opts = VertexOptions {
225                reserve_size: 0,
226                desired_group: Group::VIRTUAL,
227            };
228            let heads: VertexListWithOptions = items
229                .iter()
230                .map(|(v, _p)| (v.clone(), opts.clone()))
231                .collect::<Vec<_>>()
232                .into();
233            let parents: HashMap<Vertex, Vec<Vertex>> = items.into_iter().collect();
234            let parents: Box<dyn Parents> = Box::new(parents);
235            Arc::new((parents, heads))
236        });
237        self.maybe_recreate_virtual_group().await
238    }
239
240    /// Clear vertexes in the VIRTUAL group.
241    pub(crate) async fn clear_virtual_group(&mut self) -> Result<()> {
242        let id_set = self.dag.all_ids_in_groups(&[Group::VIRTUAL])?;
243        if !id_set.is_empty() {
244            let removed = self.dag.strip(id_set)?;
245            for span in removed.iter_span_desc() {
246                self.map.remove_range(span.low, span.high).await?;
247            }
248        }
249        Ok(())
250    }
251
252    /// If `managed_virtual_group` is set, clear the VIRTUAL group and re-insert
253    /// based on `managed_virtual_group`.
254    async fn maybe_recreate_virtual_group(&mut self) -> Result<()> {
255        if let Some(maintained_virtual_group) = self.managed_virtual_group.as_ref() {
256            let maintained_virtual_group = maintained_virtual_group.clone();
257            self.clear_virtual_group().await?;
258            let parents = &maintained_virtual_group.0;
259            let head_opts = &maintained_virtual_group.1;
260            // With the assumption (see set_managed_virtual_group docstring) that VIRTUAL group
261            // only has unique vertexes, we can pre-populate the negative cache to avoid remote
262            // lookup.
263            {
264                let mut cache = self.missing_vertexes_confirmed_by_remote.write().unwrap();
265                for v in head_opts.vertexes() {
266                    cache.insert(v);
267                }
268            }
269            // Insert to the VIRTUAL group, using the a precalculated insertion order.
270            self.add_heads(parents.as_ref(), head_opts).await?;
271        }
272        Ok(())
273    }
274}
275
276#[async_trait::async_trait]
277impl<IS, M, P, S> DagPersistent for AbstractDag<IdDag<IS>, M, P, S>
278where
279    IS: IdDagStore + Persist + StorageVersion,
280    IdDag<IS>: TryClone + 'static,
281    M: TryClone + IdMapAssignHead + Persist + Send + Sync + 'static,
282    P: Open<OpenTarget = Self> + Send + Sync + 'static,
283    S: TryClone + StorageVersion + Persist + Send + Sync + 'static,
284{
285    // See docstring in ops.rs for details.
286    async fn add_heads_and_flush(
287        &mut self,
288        parents: &dyn Parents,
289        heads: &VertexListWithOptions,
290    ) -> Result<()> {
291        if !self.pending_heads.is_empty() {
292            return programming(format!(
293                "ProgrammingError: add_heads_and_flush called with pending heads ({:?})",
294                self.pending_heads.vertexes(),
295            ));
296        }
297        tracing::debug!(target: "dag::add_heads_and_flush", lifecycle_id=?self.lifecycle_id, ?heads);
298
299        // Clear the VIRTUAL group. Their parents might have changed in incompatible ways.
300        self.clear_virtual_group().await?;
301
302        // Take lock.
303        //
304        // Reload meta and logs. This drops in-memory changes, which is fine because we have
305        // checked there are no in-memory changes at the beginning.
306        //
307        // Also see comments in `DagState::lock()`.
308        let old_version = self.state.storage_version();
309        let lock = self.state.lock()?;
310        let map_lock = self.map.lock()?;
311        let dag_lock = self.dag.lock()?;
312        self.state.reload(&lock)?;
313        let new_version = self.state.storage_version();
314        if old_version != new_version {
315            self.invalidate_snapshot();
316            self.invalidate_missing_vertex_cache();
317            self.invalidate_overlay_map()?;
318        }
319
320        self.map.reload(&map_lock)?;
321        self.dag.reload(&dag_lock)?;
322
323        // Build.
324        self.build_with_lock(parents, heads, &map_lock).await?;
325
326        // Write to disk.
327        self.map.persist(&map_lock)?;
328        self.dag.persist(&dag_lock)?;
329        self.state.persist(&lock)?;
330        drop(dag_lock);
331        drop(map_lock);
332        drop(lock);
333
334        self.persisted_id_set = self.dag.all_ids_in_groups(&Group::PERSIST)?;
335        self.maybe_recreate_virtual_group().await?;
336
337        debug_assert_eq!(self.dirty().await?.count().await?, 0);
338
339        Ok(())
340    }
341
342    /// Write in-memory DAG to disk. This will also pick up changes to
343    /// the DAG by other processes.
344    ///
345    /// This function re-assigns ids for vertexes. That requires the
346    /// pending ids and vertexes to be non-lazy. If you're changing
347    /// internal structures (ex. dag and map) directly, or introducing
348    /// lazy vertexes, then avoid this function. Instead, lock and
349    /// flush directly (see `add_heads_and_flush`, `import_clone_data`).
350    ///
351    /// `heads` specify additional options for special vertexes. This
352    /// overrides the `VertexOptions` provided to `add_head`. If `heads`
353    /// is empty, then `VertexOptions` provided to `add_head` will be
354    /// used.
355    async fn flush(&mut self, heads: &VertexListWithOptions) -> Result<()> {
356        tracing::debug!(target: "dag::flush", lifecycle_id=?self.lifecycle_id, ?heads);
357        // Sanity check.
358        for result in self.vertex_id_batch(&heads.vertexes()).await? {
359            result?;
360        }
361        // Previous version of the API requires `master_heads: &[Vertex]`.
362        // Warn about possible misuses.
363        if heads.vertexes_by_group(Group::MASTER).len() != heads.len() {
364            return programming(format!(
365                "Dag::flush({heads:?}) is probably misused (group is not master)"
366            ));
367        }
368
369        // Write cached IdMap to disk.
370        self.flush_cached_idmap().await?;
371
372        // Constructs a new graph so we can copy pending data from the existing graph.
373        let mut new_name_dag: Self = self.path.open()?;
374
375        let parents: &(dyn DagAlgorithm + Send + Sync) = self;
376        let non_master_heads: VertexListWithOptions = self.pending_heads.clone();
377        new_name_dag.inherit_configurations_from(self);
378        let heads = heads.clone().chain(non_master_heads);
379        new_name_dag.add_heads_and_flush(&parents, &heads).await?;
380        new_name_dag.maybe_recreate_virtual_group().await?;
381
382        *self = new_name_dag;
383        Ok(())
384    }
385
386    /// Write in-memory IdMap paths to disk so the next time we don't need to
387    /// ask remote service for IdMap translation.
388    #[tracing::instrument(skip(self))]
389    async fn flush_cached_idmap(&self) -> Result<()> {
390        // The map might have changed on disk. We cannot use the ids in overlay_map
391        // directly. Instead, re-translate the paths.
392
393        // Prepare data to insert. Do not hold Mutex across async yield points.
394        let mut to_insert: Vec<(AncestorPath, Vec<Vertex>)> = Vec::new();
395        std::mem::swap(&mut to_insert, &mut *self.overlay_map_paths.lock().unwrap());
396        if to_insert.is_empty() {
397            return Ok(());
398        }
399
400        // Lock, reload from disk. Use a new state so the existing dag is not affected.
401        tracing::debug!(target: "dag::cache", "flushing cached idmap ({} items)", to_insert.len());
402        let mut new: Self = self.path.open()?;
403        let lock = new.state.lock()?;
404        let map_lock = new.map.lock()?;
405        let dag_lock = new.dag.lock()?;
406        new.state.reload(&lock)?;
407        new.map.reload(&map_lock)?;
408        new.dag.reload(&dag_lock)?;
409        new.inherit_configurations_from(self);
410        std::mem::swap(&mut to_insert, &mut *new.overlay_map_paths.lock().unwrap());
411        new.flush_cached_idmap_with_lock(&map_lock).await?;
412
413        new.state.persist(&lock)?;
414
415        Ok(())
416    }
417}
418
419impl<IS, M, P, S> AbstractDag<IdDag<IS>, M, P, S>
420where
421    IS: IdDagStore,
422    IdDag<IS>: TryClone + 'static,
423    M: TryClone + IdConvert + IdMapWrite + Persist + Send + Sync + 'static,
424    P: Send + Sync + 'static,
425    S: TryClone + Send + Sync + 'static,
426{
427    /// Implementation detail. Must be protected by a lock.
428    async fn flush_cached_idmap_with_lock(&mut self, map_lock: &M::Lock) -> Result<()> {
429        let mut to_insert: Vec<(AncestorPath, Vec<Vertex>)> = Vec::new();
430        std::mem::swap(&mut to_insert, &mut *self.overlay_map_paths.lock().unwrap());
431        if to_insert.is_empty() {
432            return Ok(());
433        }
434
435        // Persisting is only a cache. Keep the first `limit` names in the
436        // order they were resolved, and drop the paths past that before
437        // resolving them, so a scan of the whole history does not spend its
438        // exit resolving millions of x~n paths.
439        let limit = self.idmap_cache_flush_limit;
440        if limit > 0 {
441            let total: usize = to_insert.iter().map(|(_, names)| names.len()).sum();
442            if total > limit {
443                tracing::info!(
444                    target: "dag::cache",
445                    "caching {} of {} remotely resolved vertexes in IdMap (limit {})",
446                    limit,
447                    total,
448                    limit,
449                );
450                let mut kept = 0;
451                to_insert.retain(|(_, names)| {
452                    let keep = kept < limit;
453                    kept += names.len();
454                    keep
455                });
456            }
457        }
458
459        let mut id_names = calculate_id_name_from_paths(
460            &self.map,
461            &*self.dag,
462            &self.overlay_map_id_set,
463            &to_insert,
464        )
465        .await?;
466        if limit > 0 {
467            id_names.truncate(limit);
468        }
469
470        // For testing purpose, skip inserting certain vertexes.
471        let mut skip_vertexes: Option<HashSet<Vertex>> = None;
472        if crate::is_testing() {
473            if let Ok(s) = var("DAG_SKIP_FLUSH_VERTEXES") {
474                skip_vertexes = Some(
475                    s.split(',')
476                        .filter_map(|s| Vertex::from_hex(s.as_bytes()).ok())
477                        .collect(),
478                )
479            }
480        }
481
482        for (id, name) in id_names {
483            if let Some(skip) = &skip_vertexes {
484                if skip.contains(&name) {
485                    tracing::info!(
486                        target: "dag::cache",
487                        "skip flushing {:?}-{} to IdMap set by DAG_SKIP_FLUSH_VERTEXES",
488                        &name,
489                        id
490                    );
491                    continue;
492                }
493            }
494            tracing::debug!(target: "dag::cache", "insert {:?}-{} to IdMap", &name, id);
495            self.map.insert(id, name.as_ref()).await?;
496        }
497
498        self.map.persist(map_lock)?;
499        Ok(())
500    }
501}
502
503impl<IS, M, P, S> AbstractDag<IdDag<IS>, M, P, S>
504where
505    IS: Send + Sync + 'static,
506    IdDag<IS>: StorageVersion,
507    M: Send + Sync + 'static,
508    P: Send + Sync + 'static,
509    S: Send + Sync + 'static,
510{
511    /// Attempt to reuse caches from `other` if two `Dag`s are compatible.
512    /// Usually called when `self` is newly created.
513    fn maybe_reuse_caches_from(&mut self, other: &Self) {
514        // No need to check IdMap (or "state" which includes both IdDag and IdMap).
515        // If IdMap is changed (ex. by flush_cached_idmap), the cache states
516        // (missing_vertexes_confirmed_by_remote, overlay_map) are still reusable.
517        let dag_version_mismatch = self.dag.storage_version() != other.dag.storage_version();
518        let persisted_id_mismatch =
519            self.persisted_id_set.as_spans() != other.persisted_id_set.as_spans();
520        if dag_version_mismatch || persisted_id_mismatch {
521            tracing::debug!(target: "dag::cache", "cannot reuse cache");
522            return;
523        }
524        tracing::debug!(
525            target: "dag::cache", "reusing cache ({} missing)",
526            other.missing_vertexes_confirmed_by_remote.read().unwrap().len(),
527        );
528        self.missing_vertexes_confirmed_by_remote =
529            other.missing_vertexes_confirmed_by_remote.clone();
530        self.overlay_map = other.overlay_map.clone();
531        self.overlay_map_paths = other.overlay_map_paths.clone();
532    }
533
534    /// Set the remote protocol for converting between Id and Vertex remotely.
535    ///
536    /// This is usually used on "sparse" ("lazy") Dag where the IdMap is incomplete
537    /// for vertexes in the master groups.
538    pub fn set_remote_protocol(&mut self, protocol: Arc<dyn RemoteIdConvertProtocol>) {
539        self.remote_protocol = protocol;
540    }
541
542    /// Limit how many remotely resolved vertexes a single flush persists to
543    /// the on-disk IdMap. 0 means no limit.
544    pub fn set_idmap_cache_flush_limit(&mut self, limit: usize) {
545        self.idmap_cache_flush_limit = limit;
546    }
547
548    /// Inherit configurations like `managed_virtual_group` from `original`.
549    fn inherit_configurations_from(&mut self, original: &Self) {
550        let seg_size = original.dag.get_new_segment_size();
551        self.dag.set_new_segment_size(seg_size);
552        self.set_remote_protocol(original.remote_protocol.clone());
553        self.idmap_cache_flush_limit = original.idmap_cache_flush_limit;
554        self.managed_virtual_group = original.managed_virtual_group.clone();
555        self.maybe_reuse_caches_from(original)
556    }
557}
558
559#[async_trait::async_trait]
560impl<IS, M, P, S> DagAddHeads for AbstractDag<IdDag<IS>, M, P, S>
561where
562    IS: IdDagStore,
563    IdDag<IS>: TryClone,
564    M: TryClone + IdMapAssignHead + Send + Sync + 'static,
565    P: TryClone + Send + Sync + 'static,
566    S: TryClone + Send + Sync + 'static,
567{
568    // See docstring in ops.rs for details.
569    async fn add_heads(
570        &mut self,
571        parents: &dyn Parents,
572        heads: &VertexListWithOptions,
573    ) -> Result<bool> {
574        tracing::debug!(target: "dag::add_heads", lifecycle_id=?self.lifecycle_id, ?heads);
575        // Populate vertex negative cache to reduce round-trips doing remote lookups.
576        // Attention: this might have side effect recreating the snapshots!
577        // Skip this optimization for virtual group add_heads since the virtual set
578        // is usually small and related tracing logs can be noisy.
579        if heads.min_desired_group().unwrap_or(Group::VIRTUAL) < Group::VIRTUAL {
580            self.populate_missing_vertexes_for_add_heads(parents, &heads.vertexes())
581                .await?;
582        }
583
584        // When heads are not VIRTUAL, invalidate_snapshot() helps performance, is optional for
585        // correctness. invalidate_snapshot() decreases VerLink ref count so VerLink::bump() can
586        // use a fast path mutating in place. When heads are VIRTUAL, invalidate_snapshot() is
587        // necessary for correctness, since the versions (VerLinks) won't be bumped to avoid
588        // excessive cache invalidation.
589        self.invalidate_snapshot();
590
591        // This API takes `heads` with "desired_group"s. When a head already exists in a lower
592        // group than its "desired_group" we need to remove the higher-group id and re-assign
593        // the head and its ancestors to the lower group.
594        //
595        // For simplicity, add_heads is *append-only* and does not want to deal with the
596        // reassignment. So if you have code like:
597        //
598        //    let set1 = dag.range(x, y); // set1 is associated with the current dag, "dag v1".
599        //    dag.add_heads(...);
600        //    let set2 = dag.range(p, q); // set2 is associated with the updated dag, "dag v2".
601        //    let set3 = set2 & set1;
602        //
603        // The `set3` understands that the "dag v2" is a superset of "dag v1" (because add_heads
604        // does not strip ids), and can use fast paths - it can assume same ids in set2 and set3
605        // mean the same vertexes and ensure set3 is associated with "dag v2". If `add_heads`
606        // strips out commits, then the fast paths (note: not just for set3, also p and q) cannot
607        // be used.
608        //
609        // Practically, `heads` match one of these patterns:
610        // - (This use-case is going away): desired_group = MASTER for all heads. This is used by
611        //   old Mononoke server-side logic. The server only indexes the "main" branch. All vertexes
612        //   are in the MASTER group. To avoid misuse by the client-side, we check that there
613        //   is nothing outside the MASTER group.
614        // - desired_group = NON_MASTER for all heads. This is used by Sapling client.
615        //   It might use desired_group = MASTER on add_heads_and_flush, but not here.
616
617        // Performance-wise, add_heads + flush is slower than
618        // add_heads_and_flush.
619        //
620        // Practically, the callsite might want to use add_heads + flush
621        // instead of add_heads_and_flush, if:
622        // - The callsites cannot figure out "master_heads" at the same time
623        //   it does the graph change. For example, hg might know commits
624        //   before bookmark movements.
625        // - The callsite is trying some temporary graph changes, and does
626        //   not want to pollute the on-disk DAG. For example, calculating
627        //   a preview of a rebase.
628        // Update IdMap. Keep track of what heads are added.
629        let mut outcome = PreparedFlatSegments::default();
630        let mut covered = self.dag().all_ids_in_groups(&Group::ALL)?;
631        let mut reserved = calculate_initial_reserved(self, &covered, heads).await?;
632        for (head, opts) in heads.vertex_options() {
633            let need_assigning = match self.vertex_id_optional(&head).await? {
634                Some(id) => {
635                    if id.group() > opts.desired_group {
636                        return programming(format!(
637                            "add_heads: cannot re-assign {:?}:{:?} from {} to {} (desired), use add_heads_and_flush instead",
638                            head,
639                            id,
640                            id.group(),
641                            opts.desired_group
642                        ));
643                    } else {
644                        // In some cases (ex. old Mononoke use-case), the id exists in IdMap but
645                        // not IdDag. Still need to assign the id to IdDag.
646                        !self.dag.contains_id(id)?
647                    }
648                }
649                None => true,
650            };
651            if need_assigning {
652                let group = opts.desired_group;
653                // If any ancestors have incompatible group (ex. desired = MASTER, ancestor has
654                // NON_MASTER), then `assign_head` below will report an error.
655                let prepared_segments = self
656                    .assign_head(head.clone(), parents, group, &mut covered, &reserved)
657                    .await?;
658                outcome.merge(prepared_segments);
659                if opts.reserve_size > 0 {
660                    let low = self.map.vertex_id(head.clone()).await? + 1;
661                    update_reserved(&mut reserved, &covered, low, opts.reserve_size);
662                }
663                if group != Group::VIRTUAL {
664                    self.pending_heads.push((head, opts));
665                }
666            }
667        }
668
669        // Update high level segments from the flat segments just inserted.
670        self.dag
671            .build_segments_from_prepared_flat_segments(&outcome)?;
672
673        Ok(outcome.segment_count() > 0)
674    }
675}
676
677#[async_trait::async_trait]
678impl<IS, M, P, S> DagStrip for AbstractDag<IdDag<IS>, M, P, S>
679where
680    IS: IdDagStore + Persist,
681    IdDag<IS>: TryClone + StorageVersion,
682    M: TryClone + Persist + IdMapWrite + IdConvert + Send + Sync + 'static,
683    P: TryClone + Open<OpenTarget = Self> + Send + Sync + 'static,
684    S: TryClone + Persist + Send + Sync + 'static,
685{
686    async fn strip(&mut self, set: &Set) -> Result<()> {
687        if !self.pending_heads.is_empty() {
688            return programming(format!(
689                "strip does not support pending heads ({:?})",
690                self.pending_heads.vertexes(),
691            ));
692        }
693        tracing::debug!(target: "dag::strip", lifecycle_id=?self.lifecycle_id, ?set);
694
695        // Do strip with a lock to avoid cases where descendants are added to
696        // the stripped segments.
697        let mut new: Self = self.path.open()?;
698        let (lock, map_lock, dag_lock) = new.reload()?;
699        new.inherit_configurations_from(self);
700
701        new.strip_with_lock(set, &map_lock).await?;
702        new.persist(lock, map_lock, dag_lock)?;
703        new.maybe_recreate_virtual_group().await?;
704
705        *self = new;
706        Ok(())
707    }
708}
709
710impl<IS, M, P, S> AbstractDag<IdDag<IS>, M, P, S>
711where
712    IS: IdDagStore,
713    IdDag<IS>: TryClone,
714    M: TryClone + Persist + IdMapWrite + IdConvert + Send + Sync + 'static,
715    P: TryClone + Send + Sync + 'static,
716    S: TryClone + Send + Sync + 'static,
717{
718    /// Internal implementation of "strip".
719    async fn strip_with_lock(&mut self, set: &Set, map_lock: &M::Lock) -> Result<()> {
720        if !self.pending_heads.is_empty() {
721            return programming(format!(
722                "strip does not support pending heads ({:?})",
723                self.pending_heads.vertexes(),
724            ));
725        }
726
727        let id_set = self.to_id_set(set).await?;
728
729        // Heads in the master group must be known. Strip might "create" heads that are not
730        // currently known. Resolve them to ensure graph integrity.
731        let head_ids: Vec<Id> = {
732            // strip will include descendants.
733            let to_strip = self.dag.descendants(id_set.clone())?;
734            // only vertexes in the master group can be lazy.
735            let master_group = self.dag.master_group()?;
736            let master_group_after_strip = master_group.difference(&to_strip);
737            let heads_before_strip = self.dag.heads_ancestors(master_group)?;
738            let heads_after_strip = self.dag.heads_ancestors(master_group_after_strip)?;
739            let new_heads = heads_after_strip.difference(&heads_before_strip);
740            new_heads.iter_desc().collect()
741        };
742        let heads_after_strip = self.vertex_name_batch(&head_ids).await?;
743        tracing::debug!(target: "dag::strip", "heads after strip: {:?}", &heads_after_strip);
744        // Write IdMap cache first, they will become problematic to write
745        // after "remove" because the `VerLink`s might become incompatible.
746        self.flush_cached_idmap_with_lock(map_lock).await?;
747
748        let removed_id_set = self.dag.strip(id_set)?;
749        tracing::debug!(target: "dag::strip", "removed id set: {:?}", &removed_id_set);
750
751        let mut removed_vertexes = Vec::new();
752        for span in removed_id_set.iter_span_desc() {
753            let vertexes = self.map.remove_range(span.low, span.high).await?;
754            removed_vertexes.extend(vertexes);
755        }
756        tracing::debug!(target: "dag::strip", "removed vertexes: {:?}", &removed_vertexes);
757
758        // Add removed names to missing cache.
759        self.missing_vertexes_confirmed_by_remote
760            .write()
761            .unwrap()
762            .extend(removed_vertexes);
763
764        // Snapshot cannot be reused.
765        self.invalidate_snapshot();
766
767        Ok(())
768    }
769}
770
771#[async_trait::async_trait]
772impl<IS, M, P, S> IdMapWrite for AbstractDag<IdDag<IS>, M, P, S>
773where
774    IS: IdDagStore,
775    IdDag<IS>: TryClone,
776    M: TryClone + IdMapAssignHead + Send + Sync,
777    P: TryClone + Send + Sync,
778    S: TryClone + Send + Sync,
779{
780    async fn insert(&mut self, id: Id, name: &[u8]) -> Result<()> {
781        self.map.insert(id, name).await
782    }
783
784    async fn remove_range(&mut self, low: Id, high: Id) -> Result<Vec<Vertex>> {
785        self.map.remove_range(low, high).await
786    }
787}
788
789#[async_trait::async_trait]
790impl<IS, M, P, S> DagImportCloneData for AbstractDag<IdDag<IS>, M, P, S>
791where
792    IS: IdDagStore + Persist + 'static,
793    IdDag<IS>: TryClone,
794    M: TryClone + IdMapAssignHead + Persist + Send + Sync + 'static,
795    P: TryClone + Send + Sync + 'static,
796    S: TryClone + Persist + Send + Sync + 'static,
797{
798    async fn import_clone_data(&mut self, clone_data: CloneData<Vertex>) -> Result<()> {
799        // Write directly to disk. Bypassing "flush()" that re-assigns Ids
800        // using parent functions.
801        let (lock, map_lock, dag_lock) = self.reload()?;
802
803        if !self.dag.all()?.is_empty() {
804            return programming("Cannot import clone data for non-empty graph");
805        }
806        for (id, name) in clone_data.idmap {
807            tracing::debug!(target: "dag::clone", "insert IdMap: {:?}-{:?}", &name, id);
808            self.map.insert(id, name.as_ref()).await?;
809        }
810        self.dag
811            .build_segments_from_prepared_flat_segments(&clone_data.flat_segments)?;
812
813        self.verify_missing().await?;
814
815        self.persist(lock, map_lock, dag_lock)
816    }
817}
818
819impl<IS, M, P, S> AbstractDag<IdDag<IS>, M, P, S>
820where
821    IS: IdDagStore + Persist + 'static,
822    IdDag<IS>: TryClone,
823    M: TryClone + IdMapAssignHead + Persist + Send + Sync + 'static,
824    P: TryClone + Send + Sync + 'static,
825    S: TryClone + Persist + Send + Sync + 'static,
826{
827    /// Verify that universally known vertexes and heads are present in IdMap.
828    async fn verify_missing(&self) -> Result<()> {
829        let missing: Vec<Id> = self.check_universal_ids().await?;
830        if !missing.is_empty() {
831            let msg = format!(
832                concat!(
833                    "Clone data does not contain vertex for {:?}. ",
834                    "This is most likely a server-side bug."
835                ),
836                missing,
837            );
838            return programming(msg);
839        }
840
841        Ok(())
842    }
843
844    fn reload(&mut self) -> Result<(S::Lock, M::Lock, IS::Lock)> {
845        let lock = self.state.lock()?;
846        let map_lock = self.map.lock()?;
847        let dag_lock = self.dag.lock()?;
848        self.state.reload(&lock)?;
849        self.map.reload(&map_lock)?;
850        self.dag.reload(&dag_lock)?;
851
852        Ok((lock, map_lock, dag_lock))
853    }
854
855    fn persist(&mut self, lock: S::Lock, map_lock: M::Lock, dag_lock: IS::Lock) -> Result<()> {
856        self.map.persist(&map_lock)?;
857        self.dag.persist(&dag_lock)?;
858        self.state.persist(&lock)?;
859
860        self.invalidate_overlay_map()?;
861        self.persisted_id_set = self.dag.all_ids_in_groups(&Group::PERSIST)?;
862
863        Ok(())
864    }
865}
866
867#[async_trait::async_trait]
868impl<IS, M, P, S> DagImportPullData for AbstractDag<IdDag<IS>, M, P, S>
869where
870    IS: IdDagStore + Persist,
871    IdDag<IS>: TryClone + StorageVersion,
872    M: TryClone + IdMapAssignHead + Persist + Send + Sync + 'static,
873    P: Open<OpenTarget = Self> + TryClone + Send + Sync + 'static,
874    S: TryClone + Persist + Send + Sync + 'static,
875{
876    // See docstring in ops.rs for details.
877    async fn import_pull_data(
878        &mut self,
879        clone_data: CloneData<Vertex>,
880        heads: &VertexListWithOptions,
881    ) -> Result<()> {
882        if !self.pending_heads.is_empty() {
883            return programming(format!(
884                "import_pull_data called with pending heads ({:?})",
885                self.pending_heads.vertexes(),
886            ));
887        }
888        if let Some(group) = heads.max_desired_group() {
889            if group != Group::MASTER {
890                return programming(concat!(
891                    "import_pull_data should only take MASTER group heads. ",
892                    "Only MASTER group can contain lazy vertexes like what pull_data uses."
893                ));
894            }
895        }
896
897        for id in clone_data.flat_segments.parents_head_and_roots() {
898            if !clone_data.idmap.contains_key(&id) {
899                return programming(format!(
900                    "server does not provide name for id {id:?} in pull data"
901                ));
902            }
903        }
904
905        // Constructs a new graph so we don't expose a broken `self` state on error.
906        let mut new: Self = self.path.open()?;
907        let (lock, map_lock, dag_lock) = new.reload()?;
908        new.inherit_configurations_from(self);
909
910        // Parents that should exist in the local graph. Look them up in 1 round-trip
911        // and insert to the local graph.
912        // Also check that roots of the new segments do not overlap with the local graph.
913        // For example,
914        //
915        //      D          When the client has B (and A, C), and is pulling D,
916        //     /|\         the server provides D, E, F, with parents B and C,
917        //    F B E        and roots F and E.
918        //      |\|        The client must have B and C, and must not have F
919        //      A C        or E.
920        {
921            let mut root_ids: Vec<Id> = Vec::new();
922            let mut parent_ids: Vec<Id> = Vec::new();
923            let segments = &clone_data.flat_segments.segments;
924            let id_set = IdSet::from_spans(segments.iter().map(|s| s.low..=s.high));
925            for seg in segments {
926                let pids: Vec<Id> = seg.parents.to_vec();
927                // Parents that are not part of the pull vertexes should exist
928                // in the local graph.
929                let connected_pids: Vec<Id> = pids
930                    .iter()
931                    .copied()
932                    .filter(|&p| !id_set.contains(p))
933                    .collect();
934                if connected_pids.len() == pids.len() {
935                    // The "low" of the segment is a root (of vertexes to insert).
936                    // It needs an overlap check.
937                    root_ids.push(seg.low);
938                }
939                parent_ids.extend(connected_pids);
940            }
941
942            let to_names = |ids: &[Id], hint: &str| -> Result<Vec<Vertex>> {
943                let names = ids.iter().map(|i| match clone_data.idmap.get(i) {
944                    Some(v) => Ok(v.clone()),
945                    None => programming(format!("server does not provide name for {hint} {i:?}")),
946                });
947                names.collect()
948            };
949
950            let parent_names = to_names(&parent_ids, "parent")?;
951            let root_names = to_names(&root_ids, "root")?;
952            tracing::trace!(
953                "pull: connected parents: {:?}, roots: {:?}",
954                &parent_names,
955                &root_names
956            );
957
958            // Pre-lookup in one round-trip.
959            let mut names = parent_names
960                .iter()
961                .chain(root_names.iter())
962                .cloned()
963                .collect::<Vec<_>>();
964            names.sort_unstable();
965            names.dedup();
966            let resolved = new.vertex_id_batch(&names).await?;
967            assert_eq!(resolved.len(), names.len());
968            for (id, name) in resolved.into_iter().zip(names) {
969                if let Ok(id) = id {
970                    if !new.map.contains_vertex_name(&name).await? {
971                        tracing::debug!(target: "dag::pull", "insert IdMap: {:?}-{:?}", &name, id);
972                        new.map.insert(id, name.as_ref()).await?;
973                    }
974                }
975            }
976
977            for name in root_names {
978                if new.contains_vertex_name(&name).await? {
979                    let e = NeedSlowPath(format!("{name:?} exists in local graph"));
980                    return Err(e);
981                }
982            }
983
984            let client_parents = new.vertex_id_batch(&parent_names).await?;
985            client_parents.into_iter().collect::<Result<Vec<Id>>>()?;
986        }
987
988        // Prepare indexes and states used below.
989        /// Query server segments with some indexes.
990        struct ServerState<'a> {
991            seg_by_high: BTreeMap<Id, FlatSegment>,
992            idmap_by_name: BTreeMap<&'a Vertex, Id>,
993            idmap_by_id: &'a BTreeMap<Id, Vertex>,
994        }
995        let mut server = ServerState {
996            seg_by_high: clone_data
997                .flat_segments
998                .segments
999                .iter()
1000                .map(|s| (s.high, s.clone()))
1001                .collect(),
1002            idmap_by_name: clone_data
1003                .idmap
1004                .iter()
1005                .map(|(&id, name)| (name, id))
1006                .collect(),
1007            idmap_by_id: &clone_data.idmap,
1008        };
1009
1010        impl<'a> ServerState<'a> {
1011            /// Find the segment that contains the (server-side) Id.
1012            fn seg_containing_id(&self, server_id: Id) -> Result<&FlatSegment> {
1013                let seg = match self.seg_by_high.range(server_id..).next() {
1014                    Some((_high, seg)) => {
1015                        if seg.low <= server_id && seg.high >= server_id {
1016                            Some(seg)
1017                        } else {
1018                            None
1019                        }
1020                    }
1021                    None => None,
1022                };
1023                seg.ok_or_else(|| {
1024                    DagError::Programming(format!(
1025                        "server does not provide segment covering id {server_id}"
1026                    ))
1027                })
1028            }
1029
1030            /// Split a server segment from `[ low --  middle -- high ]` to
1031            /// `[ low -- middle ] [ middle + 1 -- high ]`.
1032            fn split_seg(&mut self, high: Id, middle: Id) {
1033                // This is useful when "middle" is a "parent" of another segment, like:
1034                //    seg 1 (server): 100 -- 115 -- 120
1035                //    seg 2 (server):                    121 -- 130, parents: [115]
1036                // While the task is to ensure seg 2's head H is present, we can split seg 1:
1037                //    seg 1a (server): 110 -- 115
1038                //    seg 1b (server):            116 -- 120, parents: [115]
1039                //    seg 2  (server):                       121 -- 130 (H), parents: [115]
1040                // Then remap and insert seg 1a and seg 2 first to complete the "H" goal:
1041                //    seg 1a (client): 10 -- 15
1042                //    seg 2  (client):          16 -- 20 (H), parents: [15]
1043                // The 10 ... 20 range is now continuous and friendly to merge to high-level
1044                // segments. The rest of seg 1, seg 1b (server) can be picked up later when
1045                // visiting from other heads.
1046                let seg = self
1047                    .seg_by_high
1048                    .remove(&high)
1049                    .expect("bug: invalid high passed to split_seg");
1050                assert!(seg.low <= middle);
1051                assert!(seg.high > middle);
1052                assert!(self.idmap_by_id.contains_key(&middle));
1053                let seg1 = FlatSegment {
1054                    low: seg.low,
1055                    high: middle,
1056                    parents: seg.parents,
1057                };
1058                let seg2 = FlatSegment {
1059                    low: middle + 1,
1060                    high: seg.high,
1061                    parents: vec![middle],
1062                };
1063                self.seg_by_high.insert(seg1.high, seg1);
1064                self.seg_by_high.insert(seg2.high, seg2);
1065            }
1066
1067            fn name_by_id(&self, id: Id) -> Vertex {
1068                self.idmap_by_id
1069                    .get(&id)
1070                    .expect("IdMap should contain the `id`. It should be checked before.")
1071                    .clone()
1072            }
1073
1074            fn id_by_name(&self, name: &Vertex) -> Option<Id> {
1075                self.idmap_by_name.get(name).copied()
1076            }
1077        }
1078
1079        // `taken` is the union of `covered` and `reserved`, mainly used by `find_free_span`.
1080        let mut taken = {
1081            // Normally we would want `calculate_initial_reserved` here. But we calculate head
1082            // reservation for all `heads` in order, instead of just considering heads in the
1083            // `clone_data`. So we're fine without the "initial reserved". In other words, the
1084            // `calculate_initial_reserved` logic is "inlined" into the `for ... in heads`
1085            // loop below.
1086            new.dag().all_ids_in_groups(&[Group::MASTER])?
1087        };
1088
1089        // Output. Remapped segments to insert.
1090        let mut prepared_client_segments = PreparedFlatSegments::default();
1091
1092        // Insert segments by visiting the heads following the `VertexOptions` order.
1093        //
1094        // If a segment is not ready to be inserted (ex. its parents are still missing),
1095        // their parents will be visited recursively. This has the nice effects
1096        // comparing to `import_clone_data` which blindly takes the input as-is:
1097        // - De-fragment `clone_data`: gaps or sub-optional segment order won't hurt.
1098        // - Respect the local `VertexOptions`: respect the order and reserve_size
1099        //   set locally if possible.
1100        // - Ignore "bogus" unrelated sub-graph: if the `clone_data` contains more
1101        //   segments then needed, they will be simply ignored.
1102        //
1103        // The implementation (of using a stack) is similar to `IdMap::assign_head`,
1104        // but insert a segment at a time, not a vertex at a time.
1105        //
1106        // Only the MASTER group supports laziness. So we only care about it.
1107        for (head, opts) in heads.vertex_options() {
1108            let mut stack: Vec<Id> = vec![];
1109            if let Some(head_server_id) = server.id_by_name(&head) {
1110                let _head_server_seg = server.seg_containing_id(head_server_id)?;
1111                stack.push(head_server_id);
1112            }
1113
1114            while let Some(server_high) = stack.pop() {
1115                let mut server_seg = server.seg_containing_id(server_high)?;
1116                if server_high < server_seg.high {
1117                    // Split the segment for more efficient high level segments.
1118                    let seg_high = server_seg.high;
1119                    server.split_seg(seg_high, server_high);
1120                    server_seg = server.seg_containing_id(server_high)?;
1121                    assert_eq!(server_high, server_seg.high);
1122                }
1123                let high_vertex = server.name_by_id(server_high);
1124                let client_high_id = new
1125                    .map
1126                    .vertex_id_with_max_group(&high_vertex, Group::MAX)
1127                    .await?;
1128                match client_high_id {
1129                    Some(id) if id.group() == Group::MASTER => {
1130                        // `server_seg` is present in MASTER group (previously inserted
1131                        // by this loop). No need to insert or visit parents.
1132                        continue;
1133                    }
1134                    Some(id) => {
1135                        // `id` in non-MASTER group. This should not really happen because we have
1136                        // checked all "roots" are missing in the local graph. See `NeedSlowPath`
1137                        // above.
1138                        let e = NeedSlowPath(format!(
1139                            "{high_vertex:?} exists in local graph as {id:?} - fast path requires MASTER group"
1140                        ));
1141                        return Err(e);
1142                    }
1143                    None => {}
1144                }
1145
1146                let parent_server_ids = &server_seg.parents;
1147                let parent_names: Vec<Vertex> = {
1148                    let iter = parent_server_ids.iter().map(|id| server.name_by_id(*id));
1149                    iter.collect()
1150                };
1151
1152                // The client parent ids in the MASTER group.
1153                let mut parent_client_ids = Vec::new();
1154                let mut missing_parent_server_ids = Vec::new();
1155
1156                // Calculate `parent_client_ids`, and `missing_parent_server_ids`.
1157                // Intentionally using `new.map` not `new` to bypass remote lookups.
1158                {
1159                    let client_id_res = new.map.vertex_id_batch(&parent_names).await?;
1160                    assert_eq!(client_id_res.len(), parent_server_ids.len());
1161                    for (res, &server_id) in client_id_res.into_iter().zip(parent_server_ids) {
1162                        match res {
1163                            Ok(id) if id.group() != Group::MASTER => {
1164                                return Err(NeedSlowPath(format!(
1165                                    "{parent_names:?} exists id in local graph as {id:?} - fast path requires MASTER group"
1166                                )));
1167                            }
1168                            Ok(id) => {
1169                                parent_client_ids.push(id);
1170                            }
1171                            Err(crate::Error::VertexNotFound(_)) => {
1172                                missing_parent_server_ids.push(server_id);
1173                            }
1174                            Err(e) => return Err(e),
1175                        }
1176                    }
1177                }
1178
1179                if !missing_parent_server_ids.is_empty() {
1180                    // Parents are not ready. Needs revisit this segment after inserting parents.
1181                    stack.push(server_high);
1182                    // Insert missing parents.
1183                    // First parent, first insertion.
1184                    for &server_id in missing_parent_server_ids.iter().rev() {
1185                        stack.push(server_id);
1186                    }
1187                    continue;
1188                }
1189
1190                // All parents are present. Time to insert this segment.
1191                // Find a suitable low..=high range.
1192                let candidate_id = match parent_client_ids.iter().max().copied() {
1193                    None => Group::MASTER.min_id(),
1194                    Some(id) => id + 1,
1195                };
1196                let size = server_seg.high.0 - server_seg.low.0 + 1;
1197                let span = find_free_span(&taken, candidate_id, size, false);
1198
1199                // Map the server_seg.low..=server_seg.high to client span.low..=span.high.
1200                // Insert to IdMap.
1201                for (&server_id, name) in server.idmap_by_id.range(server_seg.low..=server_seg.high)
1202                {
1203                    let client_id = server_id + span.low.0 - server_seg.low.0;
1204                    if client_id.group() != Group::MASTER {
1205                        return Err(crate::Error::IdOverflow(Group::MASTER));
1206                    }
1207                    new.map.insert(client_id, name.as_ref()).await?;
1208                }
1209
1210                // Prepare insertion to IdDag.
1211                prepared_client_segments.push_segment(span.low, span.high, &parent_client_ids);
1212
1213                // Mark the range as taken.
1214                taken.push(span);
1215            }
1216
1217            // Consider reservation for `head` by updating `taken`.
1218            if opts.reserve_size > 0 {
1219                let head_client_id = new.map.vertex_id(head).await?;
1220                let span = find_free_span(&taken, head_client_id + 1, opts.reserve_size as _, true);
1221                taken.push(span);
1222            }
1223        }
1224
1225        new.dag
1226            .build_segments_from_prepared_flat_segments(&prepared_client_segments)?;
1227
1228        // Some "missing" vertexes might be imported.
1229        new.invalidate_missing_vertex_cache();
1230
1231        if cfg!(debug_assertions) {
1232            new.verify_missing().await?;
1233        }
1234
1235        new.persist(lock, map_lock, dag_lock)?;
1236
1237        // Update maintained VIRTUAL group.
1238        new.maybe_recreate_virtual_group().await?;
1239
1240        *self = new;
1241        Ok(())
1242    }
1243}
1244
1245#[async_trait::async_trait]
1246impl<IS, M, P, S> DagExportCloneData for AbstractDag<IdDag<IS>, M, P, S>
1247where
1248    IS: IdDagStore,
1249    IdDag<IS>: TryClone,
1250    M: IdConvert + TryClone + Send + Sync + 'static,
1251    P: TryClone + Send + Sync + 'static,
1252    S: TryClone + Send + Sync + 'static,
1253{
1254    async fn export_clone_data(&self) -> Result<CloneData<Vertex>> {
1255        let idmap: BTreeMap<Id, Vertex> = {
1256            let ids: Vec<Id> = self.dag.universal_ids()?.into_iter().collect();
1257            tracing::debug!("export: {} universally known vertexes", ids.len());
1258            let names = {
1259                let fallible_names = self.vertex_name_batch(&ids).await?;
1260                let mut names = Vec::with_capacity(fallible_names.len());
1261                for name in fallible_names {
1262                    names.push(name?);
1263                }
1264                names
1265            };
1266            ids.into_iter().zip(names).collect()
1267        };
1268
1269        let flat_segments: PreparedFlatSegments = {
1270            let segments = self.dag.next_segments(Id::MIN, 0)?;
1271            let mut prepared = Vec::with_capacity(segments.len());
1272            for segment in segments {
1273                let span = segment.span()?;
1274                let parents = segment.parents()?;
1275                prepared.push(FlatSegment {
1276                    low: span.low,
1277                    high: span.high,
1278                    parents,
1279                });
1280            }
1281            PreparedFlatSegments {
1282                segments: prepared.into_iter().collect(),
1283            }
1284        };
1285
1286        let data = CloneData {
1287            flat_segments,
1288            idmap,
1289        };
1290        Ok(data)
1291    }
1292}
1293
1294#[async_trait::async_trait]
1295impl<IS, M, P, S> DagExportPullData for AbstractDag<IdDag<IS>, M, P, S>
1296where
1297    IS: IdDagStore,
1298    IdDag<IS>: TryClone,
1299    M: IdConvert + TryClone + Send + Sync + 'static,
1300    P: TryClone + Send + Sync + 'static,
1301    S: TryClone + Send + Sync + 'static,
1302{
1303    async fn export_pull_data(&self, set: &Set) -> Result<CloneData<Vertex>> {
1304        let id_set = self.to_id_set(set).await?;
1305
1306        let flat_segments = self.dag.idset_to_flat_segments(id_set)?;
1307        let ids: Vec<_> = flat_segments.parents_head_and_roots().into_iter().collect();
1308
1309        let idmap: BTreeMap<Id, Vertex> = {
1310            tracing::debug!("pull: {} vertexes in idmap", ids.len());
1311            let names = {
1312                let fallible_names = self.vertex_name_batch(&ids).await?;
1313                let mut names = Vec::with_capacity(fallible_names.len());
1314                for name in fallible_names {
1315                    names.push(name?);
1316                }
1317                names
1318            };
1319            assert_eq!(ids.len(), names.len());
1320            ids.into_iter().zip(names).collect()
1321        };
1322
1323        let data = CloneData {
1324            flat_segments,
1325            idmap,
1326        };
1327        Ok(data)
1328    }
1329}
1330
1331impl<IS, M, P, S> AbstractDag<IdDag<IS>, M, P, S>
1332where
1333    IS: IdDagStore,
1334    IdDag<IS>: TryClone,
1335    M: TryClone + Send + Sync,
1336    P: TryClone + Send + Sync,
1337    S: TryClone + Send + Sync,
1338{
1339    /// Invalidate cached content. Call this before changing the graph
1340    /// so `version` in `snapshot` is dropped, and `version.bump()` might
1341    /// have a faster path.
1342    ///
1343    /// Forgetting to call this function might hurt performance a bit, but does
1344    /// not affect correctness.
1345    fn invalidate_snapshot(&mut self) {
1346        *self.snapshot.write().unwrap() = None;
1347    }
1348
1349    fn invalidate_missing_vertex_cache(&mut self) {
1350        tracing::debug!(target: "dag::cache", "cleared missing cache");
1351        *self.missing_vertexes_confirmed_by_remote.write().unwrap() = Default::default();
1352    }
1353
1354    fn invalidate_overlay_map(&mut self) -> Result<()> {
1355        self.overlay_map = Default::default();
1356        self.update_overlay_map_id_set()?;
1357        tracing::debug!(target: "dag::cache", "cleared overlay map cache");
1358        Ok(())
1359    }
1360
1361    fn update_overlay_map_id_set(&mut self) -> Result<()> {
1362        self.overlay_map_id_set = self.dag.master_group()?;
1363        Ok(())
1364    }
1365
1366    /// Attempt to get a snapshot of this graph.
1367    pub(crate) fn try_snapshot(&self) -> Result<Arc<Self>> {
1368        if let Some(s) = self.snapshot.read().unwrap().deref() {
1369            if s.dag.version() == self.dag.version() {
1370                return Ok(Arc::clone(s));
1371            }
1372        }
1373
1374        let mut snapshot = self.snapshot.write().unwrap();
1375        match snapshot.deref() {
1376            Some(s) if s.dag.version() == self.dag.version() => Ok(s.clone()),
1377            _ => {
1378                let cloned = Self {
1379                    dag: self.dag.try_clone()?,
1380                    map: self.map.try_clone()?,
1381                    snapshot: Default::default(),
1382                    pending_heads: self.pending_heads.clone(),
1383                    persisted_id_set: self.persisted_id_set.clone(),
1384                    path: self.path.try_clone()?,
1385                    state: self.state.try_clone()?,
1386                    id: self.id.clone(),
1387                    // If we do deep clone here we can remove `overlay_map_next_id`
1388                    // protection. However that could be too expensive.
1389                    overlay_map: Arc::clone(&self.overlay_map),
1390                    overlay_map_id_set: self.overlay_map_id_set.clone(),
1391                    overlay_map_paths: Arc::clone(&self.overlay_map_paths),
1392                    idmap_cache_flush_limit: self.idmap_cache_flush_limit,
1393                    remote_protocol: self.remote_protocol.clone(),
1394                    managed_virtual_group: self.managed_virtual_group.clone(),
1395                    missing_vertexes_confirmed_by_remote: Arc::clone(
1396                        &self.missing_vertexes_confirmed_by_remote,
1397                    ),
1398                    lifecycle_id: self.lifecycle_id.clone(),
1399                    internal_stats: Default::default(),
1400                };
1401                let result = Arc::new(cloned);
1402                *snapshot = Some(Arc::clone(&result));
1403                Ok(result)
1404            }
1405        }
1406    }
1407
1408    pub fn dag(&self) -> &IdDag<IS> {
1409        &self.dag
1410    }
1411
1412    pub fn map(&self) -> &M {
1413        &self.map
1414    }
1415
1416    pub(crate) fn get_remote_protocol(&self) -> Arc<dyn RemoteIdConvertProtocol> {
1417        self.remote_protocol.clone()
1418    }
1419}
1420
1421impl<IS, M, P, S> AbstractDag<IdDag<IS>, M, P, S>
1422where
1423    IS: IdDagStore,
1424    IdDag<IS>: TryClone,
1425    M: TryClone + IdMapAssignHead + Send + Sync + 'static,
1426    P: TryClone + Send + Sync + 'static,
1427    S: TryClone + Send + Sync + 'static,
1428{
1429    async fn populate_missing_vertexes_for_add_heads(
1430        &mut self,
1431        parents: &dyn Parents,
1432        heads: &[Vertex],
1433    ) -> Result<()> {
1434        if self.is_vertex_lazy() {
1435            let unassigned = calculate_definitely_unassigned_vertexes(self, parents, heads).await?;
1436            let mut missing = self.missing_vertexes_confirmed_by_remote.write().unwrap();
1437            for v in unassigned {
1438                if missing.insert(v.clone()) {
1439                    tracing::trace!(target: "dag::cache", "cached missing {:?} (definitely missing)", &v);
1440                }
1441            }
1442        }
1443        Ok(())
1444    }
1445}
1446
1447/// Calculate vertexes that are definitely not assigned (not in the IdMap,
1448/// and not in the lazy part of the IdMap) according to
1449/// `hint_pending_subdag`. This does not report all unassigned vertexes.
1450/// But the reported vertexes are guaranteed not assigned.
1451///
1452/// If X is assigned, then X's parents must have been assigned.
1453/// If X is not assigned, then all X's descendants are not assigned.
1454///
1455/// This function visits the "roots" of "parents", and if they are not assigned,
1456/// then add their descendants to the "unassigned" result set.
1457async fn calculate_definitely_unassigned_vertexes<IS, M, P, S>(
1458    this: &AbstractDag<IdDag<IS>, M, P, S>,
1459    parents: &dyn Parents,
1460    heads: &[Vertex],
1461) -> Result<Vec<Vertex>>
1462where
1463    IS: IdDagStore,
1464    IdDag<IS>: TryClone,
1465    M: TryClone + IdMapAssignHead + Send + Sync + 'static,
1466    P: TryClone + Send + Sync + 'static,
1467    S: TryClone + Send + Sync + 'static,
1468{
1469    // subdag: vertexes to insert
1470    //
1471    // For example, when adding C---D to the graph A---B:
1472    //
1473    //      A---B
1474    //           \
1475    //            C---D
1476    //
1477    // The subdag is C---D (C does not have parent).
1478    //
1479    // Extra checks are needed because upon reload, the main graph
1480    // A---B might already contain part of the subdag to be added.
1481    let subdag = parents.hint_subdag_for_insertion(heads).await?;
1482
1483    let mut remaining = subdag.all().await?;
1484    let mut unassigned = Set::empty();
1485
1486    // For lazy graph, avoid some remote lookups by figuring out
1487    // some definitely unassigned (missing) vertexes. For example,
1488    //
1489    //      A---B---C
1490    //           \
1491    //            D---E
1492    //
1493    // When adding D---E (subdag, new vertex that might trigger remote
1494    // lookup) with parent B to the main graph (A--B--C),
1495    // 1. If B exists, and is not in the master group, then B and its
1496    //    descendants cannot be not lazy, and there is no need to lookup
1497    //    D remotely.
1498    // 2. If B exists, and is in the master group, and all its children
1499    //    except D (i.e. C) are known locally, and the vertex name of D
1500    //    does not match other children (C), we know that D cannot be
1501    //    in the lazy part of the main graph, and can skip the remote
1502    //    lookup.
1503    let mut unassigned_roots = Vec::new();
1504    if this.is_vertex_lazy() {
1505        let roots = subdag.roots(remaining.clone()).await?;
1506        let mut roots_iter = roots.iter().await?;
1507        while let Some(root) = roots_iter.next().await {
1508            let root = root?;
1509
1510            // Do a local "contains" check.
1511            if matches!(
1512                &this
1513                    .contains_vertex_name_locally(std::slice::from_ref(&root))
1514                    .await?[..],
1515                [true]
1516            ) {
1517                tracing::debug!(target: "dag::definitelymissing", "root {:?} is already known", &root);
1518                continue;
1519            }
1520
1521            let root_parents_id_set = {
1522                let root_parents = parents.parent_names(root.clone()).await?;
1523                let root_parents_set = match this.sort(&Set::from_static_names(root_parents)).await
1524                {
1525                    Ok(set) => set,
1526                    Err(_) => {
1527                        tracing::trace!(target: "dag::definitelymissing", "root {:?} is unclear (parents cannot be resolved)", &root);
1528                        continue;
1529                    }
1530                };
1531                this.to_id_set(&root_parents_set).await?
1532            };
1533
1534            // If there are no parents of `root`, we cannot confidently test
1535            // whether `root` is missing or not.
1536            if root_parents_id_set.is_empty() {
1537                tracing::trace!(target: "dag::definitelymissing", "root {:?} is unclear (no parents)", &root);
1538                continue;
1539            }
1540
1541            // All parents of `root` are non-lazy.
1542            // So `root` is non-lazy and the local "contains" check is the same
1543            // as a remote "contains" check.
1544            if root_parents_id_set
1545                .iter_desc()
1546                .all(|i| i.group() > Group::MASTER)
1547            {
1548                tracing::debug!(target: "dag::definitelymissing", "root {:?} is not assigned (non-lazy parent)", &root);
1549                unassigned_roots.push(root);
1550                continue;
1551            }
1552
1553            // All children of lazy parents of `root` are known locally.
1554            // So `root` cannot match an existing vertex in the lazy graph.
1555            let children_ids: Vec<Id> = this
1556                .dag
1557                .children(root_parents_id_set)?
1558                .iter_desc()
1559                .collect();
1560            if this
1561                .map
1562                .contains_vertex_id_locally(&children_ids)
1563                .await?
1564                .iter()
1565                .all(|b| *b)
1566            {
1567                tracing::debug!(target: "dag::definitelymissing", "root {:?} is not assigned (children of parents are known)", &root);
1568                unassigned_roots.push(root);
1569                continue;
1570            }
1571
1572            tracing::trace!(target: "dag::definitelymissing", "root {:?} is unclear", &root);
1573        }
1574
1575        if !unassigned_roots.is_empty() {
1576            unassigned = subdag
1577                .descendants(Set::from_static_names(unassigned_roots))
1578                .await?;
1579            remaining = remaining.difference(&unassigned);
1580        }
1581    }
1582
1583    // Figure out unassigned (missing) vertexes that do need to be inserted.
1584    // This is done via utils::filter_known.
1585    let filter_known = |sample: &[Vertex]| -> BoxFuture<Result<Vec<Vertex>>> {
1586        let sample = sample.to_vec();
1587        async {
1588            let known_bools: Vec<bool> = {
1589                let ids = this.vertex_id_batch(&sample).await?;
1590                ids.into_iter().map(|i| i.is_ok()).collect()
1591            };
1592            debug_assert_eq!(sample.len(), known_bools.len());
1593            let known = sample
1594                .into_iter()
1595                .zip(known_bools)
1596                .filter_map(|(v, b)| if b { Some(v) } else { None })
1597                .collect();
1598            Ok(known)
1599        }
1600        .boxed()
1601    };
1602    let assigned = utils::filter_known(remaining.clone(), &filter_known).await?;
1603    unassigned = unassigned.union(&remaining.difference(&assigned));
1604    tracing::debug!(target: "dag::definitelymissing", "unassigned (missing): {:?}", &unassigned);
1605
1606    let unassigned = unassigned.iter().await?.try_collect().await?;
1607    Ok(unassigned)
1608}
1609
1610// The "client" Dag. Using a remote protocol to fill lazy part of the vertexes.
1611impl<IS, M, P, S> AbstractDag<IdDag<IS>, M, P, S>
1612where
1613    IS: IdDagStore,
1614    IdDag<IS>: TryClone,
1615    M: IdConvert + TryClone + Send + Sync,
1616    P: TryClone + Send + Sync,
1617    S: TryClone + Send + Sync,
1618{
1619    /// Resolve vertexes remotely and cache the result in the overlay map.
1620    /// Return the resolved ids in the given order. Not all names are resolved.
1621    async fn resolve_vertexes_remotely(&self, names: &[Vertex]) -> Result<Vec<Option<Id>>> {
1622        if names.is_empty() {
1623            return Ok(Vec::new());
1624        }
1625        if is_remote_protocol_disabled() {
1626            return Err(io::Error::new(
1627                io::ErrorKind::WouldBlock,
1628                "resolving vertexes remotely disabled",
1629            )
1630            .into());
1631        }
1632        if names.len() < 30 {
1633            tracing::debug!(target: "dag::protocol", "resolve names {:?} remotely", &names);
1634        } else {
1635            tracing::debug!(target: "dag::protocol", "resolve names ({}) remotely", names.len());
1636        }
1637        crate::failpoint!("dag-resolve-vertexes-remotely");
1638        let request: protocol::RequestNameToLocation =
1639            (self.map(), self.dag()).process(names.to_vec()).await?;
1640        let path_names = self
1641            .remote_protocol
1642            .resolve_names_to_relative_paths(request.heads, request.names)
1643            .await?;
1644        self.insert_relative_paths(path_names).await?;
1645        let overlay = self.overlay_map.read().unwrap();
1646        let mut ids = Vec::with_capacity(names.len());
1647        let mut missing = self.missing_vertexes_confirmed_by_remote.write().unwrap();
1648        for name in names {
1649            if let Some(id) = overlay.lookup_vertex_id(name) {
1650                ids.push(Some(id));
1651            } else {
1652                tracing::trace!(target: "dag::cache", "cached missing {:?} (server confirmed)", &name);
1653                missing.insert(name.clone());
1654                ids.push(None);
1655            }
1656        }
1657        Ok(ids)
1658    }
1659
1660    /// Resolve ids remotely and cache the result in the overlay map.
1661    /// Return the resolved ids in the given order. All ids must be resolved.
1662    async fn resolve_ids_remotely(&self, ids: &[Id]) -> Result<Vec<Vertex>> {
1663        if ids.is_empty() {
1664            return Ok(Vec::new());
1665        }
1666        if is_remote_protocol_disabled() {
1667            return Err(io::Error::new(
1668                io::ErrorKind::WouldBlock,
1669                "resolving ids remotely disabled",
1670            )
1671            .into());
1672        }
1673        if ids.len() < 30 {
1674            tracing::debug!(target: "dag::protocol", "resolve ids {:?} remotely", &ids);
1675        } else {
1676            tracing::debug!(target: "dag::protocol", "resolve ids ({}) remotely", ids.len());
1677        }
1678        crate::failpoint!("dag-resolve-ids-remotely");
1679        let request: protocol::RequestLocationToName = (self.map(), self.dag())
1680            .process(IdSet::from_spans(ids.iter().copied()))
1681            .await?;
1682        let path_names = self
1683            .remote_protocol
1684            .resolve_relative_paths_to_names(request.paths)
1685            .await?;
1686        self.insert_relative_paths(path_names).await?;
1687        let overlay = self.overlay_map.read().unwrap();
1688        let mut names = Vec::with_capacity(ids.len());
1689        for &id in ids {
1690            if let Some(name) = overlay.lookup_vertex_name(id).cloned() {
1691                names.push(name);
1692            } else {
1693                return id.not_found();
1694            }
1695        }
1696        Ok(names)
1697    }
1698
1699    /// Insert `x~n` relative paths to the overlay IdMap.
1700    async fn insert_relative_paths(
1701        &self,
1702        path_names: Vec<(AncestorPath, Vec<Vertex>)>,
1703    ) -> Result<()> {
1704        if path_names.is_empty() {
1705            return Ok(());
1706        }
1707        let to_insert: Vec<(Id, Vertex)> = calculate_id_name_from_paths(
1708            self.map(),
1709            self.dag().deref(),
1710            &self.overlay_map_id_set,
1711            &path_names,
1712        )
1713        .await?;
1714
1715        let mut paths = self.overlay_map_paths.lock().unwrap();
1716        paths.extend(path_names);
1717        drop(paths);
1718
1719        let mut overlay = self.overlay_map.write().unwrap();
1720        for (id, name) in to_insert {
1721            tracing::trace!(target: "dag::cache", "cached mapping {:?} <=> {:?}", id, &name);
1722            overlay.insert_vertex_id_name(id, name);
1723        }
1724
1725        Ok(())
1726    }
1727}
1728
1729/// Calculate (id, name) pairs to insert from (path, [name]) pairs.
1730async fn calculate_id_name_from_paths(
1731    map: &dyn IdConvert,
1732    dag: &dyn IdDagAlgorithm,
1733    overlay_map_id_set: &IdSet,
1734    path_names: &[(AncestorPath, Vec<Vertex>)],
1735) -> Result<Vec<(Id, Vertex)>> {
1736    if path_names.is_empty() {
1737        return Ok(Vec::new());
1738    }
1739    let mut to_insert: Vec<(Id, Vertex)> =
1740        Vec::with_capacity(path_names.iter().map(|(_, ns)| ns.len()).sum());
1741    for (path, names) in path_names {
1742        if names.is_empty() {
1743            continue;
1744        }
1745        // Resolve x~n to id. x is "universally known" so it should exist locally.
1746        let x_id = map.vertex_id(path.x.clone()).await.map_err(|e| {
1747            let msg = format!(
1748                concat!(
1749                    "Cannot resolve x ({:?}) in x~n locally. The x is expected to be known ",
1750                    "locally and is populated at clone time. This x~n is used to convert ",
1751                    "{:?} to a location in the graph. (Check initial clone logic) ",
1752                    "(Error: {})",
1753                ),
1754                &path.x, &names[0], e
1755            );
1756            crate::Error::Programming(msg)
1757        })?;
1758        tracing::trace!(
1759            "resolve path {:?} names {:?} (x = {}) to overlay",
1760            &path,
1761            &names,
1762            x_id
1763        );
1764        if !overlay_map_id_set.contains(x_id) {
1765            crate::failpoint!("dag-error-x-n-overflow");
1766            let msg = format!(
1767                concat!(
1768                    "Server returned x~n (x = {:?} {}, n = {}). But x is out of range ",
1769                    "({:?}). This is not expected and indicates some ",
1770                    "logic error on the server side."
1771                ),
1772                &path.x, x_id, path.n, overlay_map_id_set
1773            );
1774            return programming(msg);
1775        }
1776        let mut id = match dag.first_ancestor_nth(x_id, path.n).map_err(|e| {
1777            let msg = format!(
1778                concat!(
1779                    "Cannot resolve x~n (x = {:?} {}, n = {}): {}. ",
1780                    "This indicates the client-side graph is somewhat incompatible from the ",
1781                    "server-side graph. Something (server-side or client-side) was probably ",
1782                    "seriously wrong before this error."
1783                ),
1784                &path.x, x_id, path.n, e
1785            );
1786            crate::Error::Programming(msg)
1787        }) {
1788            Err(e) => {
1789                crate::failpoint!("dag-error-x-n-unresolvable");
1790                return Err(e);
1791            }
1792            Ok(id) => id,
1793        };
1794        if names.len() < 30 {
1795            tracing::debug!("resolved {:?} => {} {:?}", &path, id, &names);
1796        } else {
1797            tracing::debug!("resolved {:?} => {} {:?} ...", &path, id, &names[0]);
1798        }
1799        for (i, name) in names.iter().enumerate() {
1800            if i > 0 {
1801                // Follow id's first parent.
1802                id = match dag.parent_ids(id)?.first().cloned() {
1803                    Some(id) => id,
1804                    None => {
1805                        let msg = format!(
1806                            concat!(
1807                                "Cannot resolve x~(n+i) (x = {:?} {}, n = {}, i = {}) locally. ",
1808                                "This indicates the client-side graph is somewhat incompatible ",
1809                                "from the server-side graph. Something (server-side or ",
1810                                "client-side) was probably seriously wrong before this error."
1811                            ),
1812                            &path.x, x_id, path.n, i
1813                        );
1814                        return programming(msg);
1815                    }
1816                }
1817            }
1818
1819            tracing::trace!(" resolved {:?} = {:?}", id, &name,);
1820            to_insert.push((id, name.clone()));
1821        }
1822    }
1823    Ok(to_insert)
1824}
1825
1826// The server Dag. IdMap is complete. Provide APIs for client Dag to resolve vertexes.
1827// Currently mainly used for testing purpose.
1828#[async_trait::async_trait]
1829impl<IS, M, P, S> RemoteIdConvertProtocol for AbstractDag<IdDag<IS>, M, P, S>
1830where
1831    IS: IdDagStore,
1832    IdDag<IS>: TryClone,
1833    M: IdConvert + TryClone + Send + Sync + 'static,
1834    P: TryClone + Send + Sync + 'static,
1835    S: TryClone + Send + Sync + 'static,
1836{
1837    async fn resolve_names_to_relative_paths(
1838        &self,
1839        heads: Vec<Vertex>,
1840        names: Vec<Vertex>,
1841    ) -> Result<Vec<(AncestorPath, Vec<Vertex>)>> {
1842        let request = protocol::RequestNameToLocation { names, heads };
1843        let id_map = self.id_map_snapshot()?;
1844        let response: protocol::ResponseIdNamePair = (&id_map, self.dag()).process(request).await?;
1845        Ok(response.path_names)
1846    }
1847
1848    async fn resolve_relative_paths_to_names(
1849        &self,
1850        paths: Vec<AncestorPath>,
1851    ) -> Result<Vec<(AncestorPath, Vec<Vertex>)>> {
1852        let request = protocol::RequestLocationToName { paths };
1853        let id_map = self.id_map_snapshot()?;
1854        let response: protocol::ResponseIdNamePair = (&id_map, self.dag()).process(request).await?;
1855        Ok(response.path_names)
1856    }
1857}
1858
1859// On "snapshot".
1860#[async_trait::async_trait]
1861impl<IS, M, P, S> RemoteIdConvertProtocol for Arc<AbstractDag<IdDag<IS>, M, P, S>>
1862where
1863    IS: IdDagStore,
1864    IdDag<IS>: TryClone,
1865    M: IdConvert + TryClone + Send + Sync + 'static,
1866    P: TryClone + Send + Sync + 'static,
1867    S: TryClone + Send + Sync + 'static,
1868{
1869    async fn resolve_names_to_relative_paths(
1870        &self,
1871        heads: Vec<Vertex>,
1872        names: Vec<Vertex>,
1873    ) -> Result<Vec<(AncestorPath, Vec<Vertex>)>> {
1874        self.deref()
1875            .resolve_names_to_relative_paths(heads, names)
1876            .await
1877    }
1878
1879    async fn resolve_relative_paths_to_names(
1880        &self,
1881        paths: Vec<AncestorPath>,
1882    ) -> Result<Vec<(AncestorPath, Vec<Vertex>)>> {
1883        self.deref().resolve_relative_paths_to_names(paths).await
1884    }
1885}
1886
1887// Dag operations. Those are just simple wrappers around [`IdDag`].
1888// See [`IdDag`] for the actual implementations of these algorithms.
1889
1890/// DAG related read-only algorithms.
1891#[async_trait::async_trait]
1892impl<IS, M, P, S> DagAlgorithm for AbstractDag<IdDag<IS>, M, P, S>
1893where
1894    IS: IdDagStore,
1895    IdDag<IS>: TryClone + 'static,
1896    M: TryClone + IdConvert + Sync + Send + 'static,
1897    P: TryClone + Sync + Send + 'static,
1898    S: TryClone + Sync + Send + 'static,
1899{
1900    /// Sort a `Set` topologically.
1901    async fn sort(&self, set: &Set) -> Result<Set> {
1902        let hints = set.hints();
1903        if hints.contains(Flags::TOPO_DESC)
1904            && matches!(hints.dag_version(), Some(v) if v <= self.dag_version())
1905            && matches!(hints.id_map_version(), Some(v) if v <= self.map_version())
1906        {
1907            tracing::debug!(target: "dag::algo::sort", "sort({:6?}) (fast path)", set);
1908            return Ok(set.clone());
1909        } else if let Some(flat_set) = set.specialized_flatten_id() {
1910            let dag_version = flat_set.dag.dag_version();
1911            if dag_version <= self.dag_version() {
1912                let mut flat_set = flat_set.into_owned();
1913                flat_set.set_iteration_order(BasicIterationOrder::Desc);
1914                flat_set.map = self.id_map_snapshot()?;
1915                flat_set.dag = self.dag_snapshot()?;
1916                tracing::debug!(target: "dag::algo::sort", "sort({:6?}) (fast path 2)", set);
1917                return Ok(Set::from_query(flat_set));
1918            } else {
1919                tracing::info!(target: "dag::algo::sort", "sort({:6?}) (cannot use fast path 2 due to mismatched version)", set);
1920            }
1921        }
1922        tracing::warn!(target: "dag::algo::sort", "sort({:6?}) (slow path)", set);
1923        self.internal_stats
1924            .sort_slow_path_count
1925            .fetch_add(1, Ordering::Release);
1926        let flags = extract_ancestor_flag_if_compatible(set.hints(), self.dag_version());
1927        let mut spans = IdSet::empty();
1928        let mut iter = set.iter().await?.chunks(1 << 17);
1929        while let Some(names) = iter.next().await {
1930            let names = names.into_iter().collect::<Result<Vec<_>>>()?;
1931            let ids = self.vertex_id_batch(&names).await?;
1932            for id in ids {
1933                spans.push(id?);
1934            }
1935        }
1936        let result = Set::from_id_set_dag(spans, self)?;
1937        result.hints().add_flags(flags);
1938        Ok(result)
1939    }
1940
1941    /// Get ordered parent vertexes.
1942    async fn parent_names(&self, name: Vertex) -> Result<Vec<Vertex>> {
1943        let id = self.vertex_id(name).await?;
1944        let parent_ids = self.dag().parent_ids(id)?;
1945        let mut result = Vec::with_capacity(parent_ids.len());
1946        for id in parent_ids {
1947            result.push(self.vertex_name(id).await?);
1948        }
1949        Ok(result)
1950    }
1951
1952    /// Returns a set that covers all vertexes tracked by this DAG.
1953    /// Excluding the virtual group.
1954    async fn all(&self) -> Result<Set> {
1955        let spans = self.dag().all()?;
1956        let result = Set::from_id_set_dag(spans, self)?;
1957        result.hints().add_flags(Flags::FULL);
1958        Ok(result)
1959    }
1960
1961    /// Returns a set that covers all vertexes in the master group.
1962    async fn master_group(&self) -> Result<Set> {
1963        let spans = self.dag().master_group()?;
1964        let result = Set::from_id_set_dag(spans, self)?;
1965        result.hints().add_flags(Flags::ANCESTORS);
1966        Ok(result)
1967    }
1968
1969    /// Returns a set that covers all vertexes in the virtual group.
1970    async fn virtual_group(&self) -> Result<Set> {
1971        let spans = self.dag().all_ids_in_groups(&[Group::VIRTUAL])?;
1972        let result = Set::from_id_set_dag(spans, self)?;
1973        Ok(result)
1974    }
1975
1976    /// Calculates all ancestors reachable from any name from the given set.
1977    async fn ancestors(&self, set: Set) -> Result<Set> {
1978        if set.hints().contains(Flags::ANCESTORS)
1979            && set.hints().dag_version() <= Some(self.dag_version())
1980        {
1981            return Ok(set);
1982        }
1983        let spans = self.to_id_set(&set).await?;
1984        let spans = self.dag().ancestors(spans)?;
1985        let result = Set::from_id_set_dag(spans, self)?;
1986        result.hints().add_flags(Flags::ANCESTORS);
1987        Ok(result)
1988    }
1989
1990    /// Like `ancestors` but follows only the first parents.
1991    async fn first_ancestors(&self, set: Set) -> Result<Set> {
1992        // If set == ancestors(set), then first_ancestors(set) == set.
1993        if set.hints().contains(Flags::ANCESTORS)
1994            && set.hints().dag_version() <= Some(self.dag_version())
1995        {
1996            return Ok(set);
1997        }
1998        let spans = self.to_id_set(&set).await?;
1999        let spans = self.dag().first_ancestors(spans)?;
2000        let result = Set::from_id_set_dag(spans, self)?;
2001        #[cfg(test)]
2002        {
2003            result.assert_eq(crate::default_impl::first_ancestors(self, set).await?);
2004        }
2005        Ok(result)
2006    }
2007
2008    /// Calculate merges within the given set.
2009    async fn merges(&self, set: Set) -> Result<Set> {
2010        let spans = self.to_id_set(&set).await?;
2011        let spans = self.dag().merges(spans)?;
2012        let result = Set::from_id_set_dag(spans, self)?;
2013        #[cfg(test)]
2014        {
2015            result.assert_eq(crate::default_impl::merges(self, set).await?);
2016        }
2017        Ok(result)
2018    }
2019
2020    /// Calculates parents of the given set.
2021    ///
2022    /// Note: Parent order is not preserved. Use [`Dag::parent_names`]
2023    /// to preserve order.
2024    async fn parents(&self, set: Set) -> Result<Set> {
2025        // Preserve ANCESTORS flag. If ancestors(x) == x, then ancestors(parents(x)) == parents(x).
2026        let flags = extract_ancestor_flag_if_compatible(set.hints(), self.dag_version());
2027        let spans = self.dag().parents(self.to_id_set(&set).await?)?;
2028        let result = Set::from_id_set_dag(spans, self)?;
2029        result.hints().add_flags(flags);
2030        #[cfg(test)]
2031        {
2032            result.assert_eq(crate::default_impl::parents(self, set).await?);
2033        }
2034        Ok(result)
2035    }
2036
2037    /// Calculates the n-th first ancestor.
2038    async fn first_ancestor_nth(&self, name: Vertex, n: u64) -> Result<Option<Vertex>> {
2039        #[cfg(test)]
2040        let name2 = name.clone();
2041        let id = self.vertex_id(name).await?;
2042        let id = self.dag().try_first_ancestor_nth(id, n)?;
2043        let result = match id {
2044            None => None,
2045            Some(id) => Some(self.vertex_name(id).await?),
2046        };
2047        #[cfg(test)]
2048        {
2049            let result2 = crate::default_impl::first_ancestor_nth(self, name2, n).await?;
2050            assert_eq!(result, result2);
2051        }
2052        Ok(result)
2053    }
2054
2055    /// Calculates heads of the given set.
2056    async fn heads(&self, set: Set) -> Result<Set> {
2057        if set.hints().contains(Flags::ANCESTORS)
2058            && set.hints().dag_version() <= Some(self.dag_version())
2059        {
2060            // heads_ancestors is faster.
2061            return self.heads_ancestors(set).await;
2062        }
2063        let spans = self.dag().heads(self.to_id_set(&set).await?)?;
2064        let result = Set::from_id_set_dag(spans, self)?;
2065        #[cfg(test)]
2066        {
2067            result.assert_eq(crate::default_impl::heads(self, set).await?);
2068        }
2069        Ok(result)
2070    }
2071
2072    /// Calculates children of the given set.
2073    async fn children(&self, set: Set) -> Result<Set> {
2074        let spans = self.dag().children(self.to_id_set(&set).await?)?;
2075        let result = Set::from_id_set_dag(spans, self)?;
2076        Ok(result)
2077    }
2078
2079    /// Calculates roots of the given set.
2080    async fn roots(&self, set: Set) -> Result<Set> {
2081        let flags = extract_ancestor_flag_if_compatible(set.hints(), self.dag_version());
2082        let spans = self.dag().roots(self.to_id_set(&set).await?)?;
2083        let result = Set::from_id_set_dag(spans, self)?;
2084        result.hints().add_flags(flags);
2085        #[cfg(test)]
2086        {
2087            result.assert_eq(crate::default_impl::roots(self, set).await?);
2088        }
2089        Ok(result)
2090    }
2091
2092    /// Calculates one "greatest common ancestor" of the given set.
2093    ///
2094    /// If there are no common ancestors, return None.
2095    /// If there are multiple greatest common ancestors, pick one arbitrarily.
2096    /// Use `gca_all` to get all of them.
2097    async fn gca_one(&self, set: Set) -> Result<Option<Vertex>> {
2098        let result: Option<Vertex> = match self.dag().gca_one(self.to_id_set(&set).await?)? {
2099            None => None,
2100            Some(id) => Some(self.vertex_name(id).await?),
2101        };
2102        #[cfg(test)]
2103        {
2104            assert_eq!(&result, &crate::default_impl::gca_one(self, set).await?);
2105        }
2106        Ok(result)
2107    }
2108
2109    /// Calculates all "greatest common ancestor"s of the given set.
2110    /// `gca_one` is faster if an arbitrary answer is ok.
2111    async fn gca_all(&self, set: Set) -> Result<Set> {
2112        let spans = self.dag().gca_all(self.to_id_set(&set).await?)?;
2113        let result = Set::from_id_set_dag(spans, self)?;
2114        #[cfg(test)]
2115        {
2116            result.assert_eq(crate::default_impl::gca_all(self, set).await?);
2117        }
2118        Ok(result)
2119    }
2120
2121    /// Calculates all common ancestors of the given set.
2122    async fn common_ancestors(&self, set: Set) -> Result<Set> {
2123        let spans = self.dag().common_ancestors(self.to_id_set(&set).await?)?;
2124        let result = Set::from_id_set_dag(spans, self)?;
2125        result.hints().add_flags(Flags::ANCESTORS);
2126        #[cfg(test)]
2127        {
2128            result.assert_eq(crate::default_impl::common_ancestors(self, set).await?);
2129        }
2130        Ok(result)
2131    }
2132
2133    /// Tests if `ancestor` is an ancestor of `descendant`.
2134    async fn is_ancestor(&self, ancestor: Vertex, descendant: Vertex) -> Result<bool> {
2135        #[cfg(test)]
2136        let result2 =
2137            crate::default_impl::is_ancestor(self, ancestor.clone(), descendant.clone()).await?;
2138        let ancestor_id = self.vertex_id(ancestor).await?;
2139        let descendant_id = self.vertex_id(descendant).await?;
2140        let result = self.dag().is_ancestor(ancestor_id, descendant_id)?;
2141        #[cfg(test)]
2142        {
2143            assert_eq!(&result, &result2);
2144        }
2145        Ok(result)
2146    }
2147
2148    /// Calculates "heads" of the ancestors of the given set. That is,
2149    /// Find Y, which is the smallest subset of set X, where `ancestors(Y)` is
2150    /// `ancestors(X)`.
2151    ///
2152    /// This is faster than calculating `heads(ancestors(set))`.
2153    ///
2154    /// This is different from `heads`. In case set contains X and Y, and Y is
2155    /// an ancestor of X, but not the immediate ancestor, `heads` will include
2156    /// Y while this function won't.
2157    async fn heads_ancestors(&self, set: Set) -> Result<Set> {
2158        let spans = self.dag().heads_ancestors(self.to_id_set(&set).await?)?;
2159        let result = Set::from_id_set_dag(spans, self)?;
2160        #[cfg(test)]
2161        {
2162            // default_impl::heads_ancestors calls `heads` if `Flags::ANCESTORS`
2163            // is set. Prevent infinite loop.
2164            if !set.hints().contains(Flags::ANCESTORS) {
2165                result.assert_eq(crate::default_impl::heads_ancestors(self, set).await?);
2166            }
2167        }
2168        Ok(result)
2169    }
2170
2171    /// Calculates the "dag range" - vertexes reachable from both sides.
2172    async fn range(&self, roots: Set, heads: Set) -> Result<Set> {
2173        let roots = self.to_id_set(&roots).await?;
2174        let heads = self.to_id_set(&heads).await?;
2175        let spans = self.dag().range(roots, heads)?;
2176        let result = Set::from_id_set_dag(spans, self)?;
2177        Ok(result)
2178    }
2179
2180    /// Calculates the descendants of the given set.
2181    async fn descendants(&self, set: Set) -> Result<Set> {
2182        let spans = self.dag().descendants(self.to_id_set(&set).await?)?;
2183        let result = Set::from_id_set_dag(spans, self)?;
2184        Ok(result)
2185    }
2186
2187    async fn suggest_bisect(
2188        &self,
2189        roots: Set,
2190        heads: Set,
2191        skip: Set,
2192    ) -> Result<(Option<Vertex>, Set, Set)> {
2193        default_impl::suggest_bisect(self, roots, heads, skip).await
2194    }
2195
2196    /// Vertexes buffered in memory, not yet written to disk.
2197    async fn dirty(&self) -> Result<Set> {
2198        let all = self.dag().all()?;
2199        let spans = all.difference(&self.persisted_id_set);
2200        let set = Set::from_id_set_dag(spans, self)?;
2201        Ok(set)
2202    }
2203
2204    fn is_vertex_lazy(&self) -> bool {
2205        !self.remote_protocol.is_local()
2206    }
2207
2208    /// Get a snapshot of the current graph.
2209    fn dag_snapshot(&self) -> Result<Arc<dyn DagAlgorithm + Send + Sync>> {
2210        Ok(self.try_snapshot()? as Arc<dyn DagAlgorithm + Send + Sync>)
2211    }
2212
2213    fn id_dag_snapshot(&self) -> Result<Arc<dyn IdDagAlgorithm + Send + Sync>> {
2214        let store = self.dag.try_clone()?.store;
2215        Ok(Arc::new(store))
2216    }
2217
2218    fn dag_id(&self) -> &str {
2219        &self.id
2220    }
2221
2222    fn dag_version(&self) -> &VerLink {
2223        self.dag.version()
2224    }
2225}
2226
2227/// Extract the ANCESTORS flag if the set with the `hints` is bound to a
2228/// compatible DAG.
2229fn extract_ancestor_flag_if_compatible(hints: &Hints, dag_version: &VerLink) -> Flags {
2230    if hints.dag_version() <= Some(dag_version) {
2231        hints.flags() & Flags::ANCESTORS
2232    } else {
2233        Flags::empty()
2234    }
2235}
2236
2237#[async_trait::async_trait]
2238impl<I, M, P, S> PrefixLookup for AbstractDag<I, M, P, S>
2239where
2240    I: Send + Sync,
2241    M: PrefixLookup + Send + Sync,
2242    P: Send + Sync,
2243    S: Send + Sync,
2244{
2245    async fn vertexes_by_hex_prefix(&self, hex_prefix: &[u8], limit: usize) -> Result<Vec<Vertex>> {
2246        let mut list = self.map.vertexes_by_hex_prefix(hex_prefix, limit).await?;
2247        let overlay_list = self
2248            .overlay_map
2249            .read()
2250            .unwrap()
2251            .lookup_vertexes_by_hex_prefix(hex_prefix, limit)?;
2252        list.extend(overlay_list);
2253        list.sort_unstable();
2254        list.dedup();
2255        list.truncate(limit);
2256        Ok(list)
2257    }
2258}
2259
2260#[async_trait::async_trait]
2261impl<IS, M, P, S> IdConvert for AbstractDag<IdDag<IS>, M, P, S>
2262where
2263    IS: IdDagStore,
2264    IdDag<IS>: TryClone,
2265    M: IdConvert + TryClone + Send + Sync + 'static,
2266    P: TryClone + Send + Sync + 'static,
2267    S: TryClone + Send + Sync + 'static,
2268{
2269    async fn vertex_id(&self, name: Vertex) -> Result<Id> {
2270        match self.map.vertex_id(name.clone()).await {
2271            Ok(id) => Ok(id),
2272            Err(crate::Error::VertexNotFound(_)) if self.is_vertex_lazy() => {
2273                if let Some(id) = self.overlay_map.read().unwrap().lookup_vertex_id(&name) {
2274                    return Ok(id);
2275                }
2276                if self
2277                    .missing_vertexes_confirmed_by_remote
2278                    .read()
2279                    .unwrap()
2280                    .contains(&name)
2281                {
2282                    return name.not_found();
2283                }
2284                let ids = self
2285                    .resolve_vertexes_remotely(std::slice::from_ref(&name))
2286                    .await?;
2287                if let Some(Some(id)) = ids.first() {
2288                    Ok(*id)
2289                } else {
2290                    // ids is empty.
2291                    name.not_found()
2292                }
2293            }
2294            Err(e) => Err(e),
2295        }
2296    }
2297
2298    async fn vertex_id_with_max_group(
2299        &self,
2300        name: &Vertex,
2301        max_group: Group,
2302    ) -> Result<Option<Id>> {
2303        match self.map.vertex_id_with_max_group(name, max_group).await {
2304            Ok(Some(id)) => Ok(Some(id)),
2305            Err(err) => Err(err),
2306            Ok(None) if self.is_vertex_lazy() => {
2307                // Not exist in max_group from local data.
2308                if let Some(id) = self.overlay_map.read().unwrap().lookup_vertex_id(name) {
2309                    return Ok(Some(id));
2310                }
2311                if self
2312                    .missing_vertexes_confirmed_by_remote
2313                    .read()
2314                    .unwrap()
2315                    .contains(name)
2316                {
2317                    return Ok(None);
2318                }
2319                if max_group != Group::MAX
2320                    && self
2321                        .map
2322                        .vertex_id_with_max_group(name, Group::MAX)
2323                        .await?
2324                        .is_some()
2325                {
2326                    // If the vertex exists in the non-master groups. Then it must be missing in the
2327                    // master group.
2328                    return Ok(None);
2329                }
2330                match self
2331                    .resolve_vertexes_remotely(std::slice::from_ref(name))
2332                    .await
2333                {
2334                    Ok(ids) => match ids.first() {
2335                        Some(Some(id)) => Ok(Some(*id)),
2336                        Some(None) | None => Ok(None),
2337                    },
2338                    Err(e) => Err(e),
2339                }
2340            }
2341            Ok(None) => Ok(None),
2342        }
2343    }
2344
2345    async fn vertex_name(&self, id: Id) -> Result<Vertex> {
2346        match self.map.vertex_name(id).await {
2347            Ok(name) => Ok(name),
2348            Err(crate::Error::IdNotFound(_)) if self.is_vertex_lazy() => {
2349                if let Some(name) = self
2350                    .overlay_map
2351                    .read()
2352                    .unwrap()
2353                    .lookup_vertex_name(id)
2354                    .cloned()
2355                {
2356                    return Ok(name);
2357                }
2358                // Only ids <= max(MASTER group) can be lazy.
2359                let max_master_id = self.dag.master_group()?.max();
2360                if Some(id) > max_master_id {
2361                    return id.not_found();
2362                }
2363                let names = self.resolve_ids_remotely(&[id]).await?;
2364                if let Some(name) = names.into_iter().next() {
2365                    Ok(name)
2366                } else {
2367                    id.not_found()
2368                }
2369            }
2370            Err(e) => Err(e),
2371        }
2372    }
2373
2374    async fn contains_vertex_name(&self, name: &Vertex) -> Result<bool> {
2375        match self.map.contains_vertex_name(name).await {
2376            Ok(true) => Ok(true),
2377            Ok(false) if self.is_vertex_lazy() => {
2378                if self
2379                    .overlay_map
2380                    .read()
2381                    .unwrap()
2382                    .lookup_vertex_id(name)
2383                    .is_some()
2384                {
2385                    return Ok(true);
2386                }
2387                if self
2388                    .missing_vertexes_confirmed_by_remote
2389                    .read()
2390                    .unwrap()
2391                    .contains(name)
2392                {
2393                    return Ok(false);
2394                }
2395                match self
2396                    .resolve_vertexes_remotely(std::slice::from_ref(name))
2397                    .await
2398                {
2399                    Ok(ids) => match ids.first() {
2400                        Some(Some(_)) => Ok(true),
2401                        Some(None) | None => Ok(false),
2402                    },
2403                    Err(e) => Err(e),
2404                }
2405            }
2406            Ok(false) => Ok(false),
2407            Err(e) => Err(e),
2408        }
2409    }
2410
2411    async fn contains_vertex_id_locally(&self, ids: &[Id]) -> Result<Vec<bool>> {
2412        let mut list = self.map.contains_vertex_id_locally(ids).await?;
2413        let map = self.overlay_map.read().unwrap();
2414        for (b, id) in list.iter_mut().zip(ids.iter().copied()) {
2415            if !*b {
2416                *b = *b || map.has_vertex_id(id);
2417            }
2418        }
2419        Ok(list)
2420    }
2421
2422    async fn contains_vertex_name_locally(&self, names: &[Vertex]) -> Result<Vec<bool>> {
2423        tracing::trace!("contains_vertex_name_locally names: {:?}", &names);
2424        let mut list = self.map.contains_vertex_name_locally(names).await?;
2425        tracing::trace!("contains_vertex_name_locally list (local): {:?}", &list);
2426        assert_eq!(list.len(), names.len());
2427        let map = self.overlay_map.read().unwrap();
2428        for (b, name) in list.iter_mut().zip(names.iter()) {
2429            if !*b && map.has_vertex_name(name) {
2430                tracing::trace!("contains_vertex_name_locally overlay has {:?}", &name);
2431                *b = true;
2432            }
2433        }
2434        Ok(list)
2435    }
2436
2437    async fn vertex_name_batch(&self, ids: &[Id]) -> Result<Vec<Result<Vertex>>> {
2438        let mut list = self.map.vertex_name_batch(ids).await?;
2439        if self.is_vertex_lazy() {
2440            // Read from overlay map cache.
2441            {
2442                let map = self.overlay_map.read().unwrap();
2443                for (r, id) in list.iter_mut().zip(ids) {
2444                    if let Some(name) = map.lookup_vertex_name(*id).cloned() {
2445                        *r = Ok(name);
2446                    }
2447                }
2448            }
2449            // Read from missing_vertexes_confirmed_by_remote cache.
2450            let missing_indexes: Vec<usize> = {
2451                let max_master_id = self.dag.master_group()?.max();
2452                list.iter()
2453                    .enumerate()
2454                    .filter_map(|(i, r)| match r {
2455                        // Only resolve ids that are <= max(master) remotely.
2456                        Err(_) if Some(ids[i]) <= max_master_id => Some(i),
2457                        Err(_) | Ok(_) => None,
2458                    })
2459                    .collect()
2460            };
2461            let missing_ids: Vec<Id> = missing_indexes.iter().map(|i| ids[*i]).collect();
2462            let resolved = self.resolve_ids_remotely(&missing_ids).await?;
2463            for (i, name) in missing_indexes.into_iter().zip(resolved) {
2464                list[i] = Ok(name);
2465            }
2466        }
2467        Ok(list)
2468    }
2469
2470    async fn vertex_id_batch(&self, names: &[Vertex]) -> Result<Vec<Result<Id>>> {
2471        let mut list = self.map.vertex_id_batch(names).await?;
2472        if self.is_vertex_lazy() {
2473            // Read from overlay map cache.
2474            {
2475                let map = self.overlay_map.read().unwrap();
2476                for (r, name) in list.iter_mut().zip(names) {
2477                    if let Some(id) = map.lookup_vertex_id(name) {
2478                        *r = Ok(id);
2479                    }
2480                }
2481            }
2482            // Read from missing_vertexes_confirmed_by_remote cache.
2483            let missing_indexes: Vec<usize> = {
2484                let known_missing = self.missing_vertexes_confirmed_by_remote.read().unwrap();
2485                list.iter()
2486                    .enumerate()
2487                    .filter_map(|(i, r)| {
2488                        if r.is_err() && !known_missing.contains(&names[i]) {
2489                            Some(i)
2490                        } else {
2491                            None
2492                        }
2493                    })
2494                    .collect()
2495            };
2496            if !missing_indexes.is_empty() {
2497                let missing_names: Vec<Vertex> =
2498                    missing_indexes.iter().map(|i| names[*i].clone()).collect();
2499                let resolved = self.resolve_vertexes_remotely(&missing_names).await?;
2500                for (i, id) in missing_indexes.into_iter().zip(resolved) {
2501                    if let Some(id) = id {
2502                        list[i] = Ok(id);
2503                    }
2504                }
2505            }
2506        }
2507        Ok(list)
2508    }
2509
2510    fn map_id(&self) -> &str {
2511        self.map.map_id()
2512    }
2513
2514    fn map_version(&self) -> &VerLink {
2515        self.map.map_version()
2516    }
2517}
2518
2519impl<IS, M, P, S> AbstractDag<IdDag<IS>, M, P, S>
2520where
2521    IS: IdDagStore,
2522    IdDag<IS>: TryClone + 'static,
2523    M: TryClone + Persist + IdMapWrite + IdConvert + Sync + Send + 'static,
2524    P: TryClone + Sync + Send + 'static,
2525    S: TryClone + Sync + Send + 'static,
2526{
2527    /// Build IdMap and Segments for the given heads.
2528    /// Update IdMap and IdDag to include the given heads and their ancestors.
2529    ///
2530    /// Handle "reassign" cases. For example, when adding P to the master group
2531    /// and one of its parent N2 is in the non-master group:
2532    ///
2533    /// ```plain,ignore
2534    ///     1--2--3             3---P
2535    ///         \                  /
2536    ///          N1-N2-N3        N2
2537    /// ```
2538    ///
2539    /// To maintain topological order, N2 need to be re-assigned to the master
2540    /// group. This is done by temporarily removing N1-N2-N3, re-insert N1-N2
2541    /// as 4-5 to be able to insert P, then re-insert N3 in the non-master
2542    /// group:
2543    ///
2544    /// ```plain,ignore
2545    ///     1--2--3 --6 (P)
2546    ///         \    /
2547    ///          4--5 --N1
2548    /// ```
2549    async fn build_with_lock(
2550        &mut self,
2551        parents: &dyn Parents,
2552        heads: &VertexListWithOptions,
2553        map_lock: &M::Lock,
2554    ) -> Result<()> {
2555        // `std::borrow::Cow` without `Clone` constraint.
2556        enum Input<'a> {
2557            Borrowed(&'a dyn Parents, &'a VertexListWithOptions),
2558            Owned(Box<dyn Parents>, VertexListWithOptions),
2559        }
2560
2561        // Manual recursion. async fn does not support recursion.
2562        let mut stack = vec![Input::Borrowed(parents, heads)];
2563
2564        // Avoid infinite loop (buggy logic).
2565        let mut loop_count = 0;
2566
2567        while let Some(input) = stack.pop() {
2568            loop_count += 1;
2569            if loop_count > 2 {
2570                return bug("should not loop > 2 times (1st insertion+strip, 2nd reinsert)");
2571            }
2572
2573            let (parents, heads) = match &input {
2574                Input::Borrowed(p, h) => (*p, *h),
2575                Input::Owned(p, h) => (p.as_ref(), h),
2576            };
2577
2578            // Populate vertex negative cache to reduce round-trips doing remote lookups.
2579            if self.is_vertex_lazy() {
2580                let heads: Vec<Vertex> = heads.vertexes();
2581                self.populate_missing_vertexes_for_add_heads(parents, &heads)
2582                    .await?;
2583            }
2584
2585            // Backup, then remove vertexes that need to be reassigned. Actual reassignment
2586            // happens in the next loop iteration.
2587            let to_reassign: Set = self.find_vertexes_to_reassign(parents, heads).await?;
2588            if !to_reassign.is_empty().await? {
2589                let reinsert_heads: VertexListWithOptions = {
2590                    let heads = self
2591                        .heads(
2592                            self.descendants(to_reassign.clone())
2593                                .await?
2594                                .difference(&to_reassign),
2595                        )
2596                        .await?;
2597                    tracing::debug!(target: "dag::reassign", "need to rebuild heads: {:?}", &heads);
2598                    let heads: Vec<Vertex> = heads.iter().await?.try_collect().await?;
2599                    VertexListWithOptions::from(heads)
2600                };
2601                let reinsert_parents: Box<dyn Parents> = Box::new(self.dag_snapshot()?);
2602                self.strip_with_lock(&to_reassign, map_lock).await?;
2603
2604                // Rebuild non-master ids and segments on the next iteration.
2605                stack.push(Input::Owned(reinsert_parents, reinsert_heads));
2606            };
2607
2608            // Update IdMap.
2609            let mut outcome = PreparedFlatSegments::default();
2610            let mut covered = self.dag().all_ids_in_groups(&Group::ALL)?;
2611            let mut reserved = calculate_initial_reserved(self, &covered, heads).await?;
2612            for group in Group::ALL {
2613                for (vertex, opts) in heads.vertex_options() {
2614                    if opts.desired_group != group {
2615                        continue;
2616                    }
2617                    // Important: do not call self.map.assign_head. It does not trigger
2618                    // remote protocol properly. Call self.assign_head instead.
2619                    let prepared_segments = self
2620                        .assign_head(vertex.clone(), parents, group, &mut covered, &reserved)
2621                        .await?;
2622                    outcome.merge(prepared_segments);
2623                    // Update reserved.
2624                    if opts.reserve_size > 0 {
2625                        let low = self.map.vertex_id(vertex).await? + 1;
2626                        update_reserved(&mut reserved, &covered, low, opts.reserve_size);
2627                    }
2628                }
2629            }
2630
2631            // Update segments.
2632            self.dag
2633                .build_segments_from_prepared_flat_segments(&outcome)?;
2634
2635            // The master group might have new vertexes inserted, which will
2636            // affect the `overlay_map_id_set`.
2637            self.update_overlay_map_id_set()?;
2638        }
2639
2640        Ok(())
2641    }
2642
2643    /// Find vertexes that need to be reassigned from the non-master group
2644    /// to the master group. That is,
2645    /// `ancestors(master_heads_to_insert) & existing_non_master_group`
2646    ///
2647    /// Assume pre-fetching (populate_missing_vertexes_for_add_heads)
2648    /// was done, so this function can just use naive DFS without worrying
2649    /// about excessive remote lookups.
2650    async fn find_vertexes_to_reassign(
2651        &self,
2652        parents: &dyn Parents,
2653        heads: &VertexListWithOptions,
2654    ) -> Result<Set> {
2655        // Heads that need to be inserted to the master group.
2656        let master_heads = heads.vertexes_by_group(Group::MASTER);
2657
2658        // Visit vertexes recursively.
2659        let mut id_set = IdSet::empty();
2660        let mut to_visit: Vec<Vertex> = master_heads;
2661        let mut visited = HashSet::new();
2662        while let Some(vertex) = to_visit.pop() {
2663            if !visited.insert(vertex.clone()) {
2664                continue;
2665            }
2666            let id = self.vertex_id_optional(&vertex).await?;
2667            // None: The vertex/id is not yet inserted to IdMap.
2668            if let Some(id) = id {
2669                if id.group() == Group::MASTER {
2670                    // Already exist in the master group. Stop visiting.
2671                    continue;
2672                } else {
2673                    // Need reassign. Need to continue visiting.
2674                    id_set.push(id);
2675                }
2676            }
2677            let parents = parents.parent_names(vertex).await?;
2678            to_visit.extend(parents);
2679        }
2680
2681        let set = Set::from_id_set_dag(id_set, self)?;
2682        tracing::debug!(target: "dag::reassign", "need to reassign: {:?}", &set);
2683        Ok(set)
2684    }
2685}
2686
2687/// Calculate the initial "reserved" set used before inserting new vertexes.
2688/// Only heads that have non-zero reserve_size and are presnet in the graph
2689/// take effect. In other words, heads that are known to be not present in
2690/// the local graph (ex. being added), or have zero reserve_size can be
2691/// skipped as an optimization.
2692async fn calculate_initial_reserved(
2693    map: &dyn IdConvert,
2694    covered: &IdSet,
2695    heads: &VertexListWithOptions,
2696) -> Result<IdSet> {
2697    let mut reserved = IdSet::empty();
2698    for (vertex, opts) in heads.vertex_options() {
2699        if opts.reserve_size == 0 {
2700            // Avoid potentially costly remote lookup.
2701            continue;
2702        }
2703        if let Some(id) = map
2704            .vertex_id_with_max_group(&vertex, opts.desired_group)
2705            .await?
2706        {
2707            update_reserved(&mut reserved, covered, id + 1, opts.reserve_size);
2708        }
2709    }
2710    Ok(reserved)
2711}
2712
2713fn update_reserved(reserved: &mut IdSet, covered: &IdSet, low: Id, reserve_size: u32) {
2714    if reserve_size == 0 {
2715        return;
2716    }
2717    let span = find_free_span(covered, low, reserve_size as _, true);
2718    reserved.push(span);
2719}
2720
2721/// Find a span with constraints:
2722/// - does not overlap with `covered`.
2723/// - `span.low` >= the given `low`.
2724/// - if `shrink_to_fit` is `false`, `span.high - span.low` must be `reserve_size`.
2725/// - if `shrink_to_fit` is `true`, the span can be smaller than `reserve_size` to
2726///   fill up existing gaps in `covered`.
2727///
2728/// `reserve_size` cannot be 0.
2729fn find_free_span(covered: &IdSet, low: Id, reserve_size: u64, shrink_to_fit: bool) -> IdSpan {
2730    assert!(reserve_size > 0);
2731    let original_low = low;
2732    let mut low = low;
2733    let mut high;
2734    let mut count = 0;
2735    loop {
2736        count += 1;
2737        // First, bump 'low' to not overlap with a conflicted `span`.
2738        //   [----covered_span----]
2739        //      ^                  ^
2740        //      original_low       bump to here
2741        if let Some(span) = covered.span_contains(low) {
2742            low = span.high + 1;
2743        }
2744        high = (low + reserve_size - 1).min(low.group().max_id());
2745        if reserve_size <= 1 && !covered.contains(low) {
2746            // No need to go through complex (maybe O(N)) logic below.
2747            break;
2748        }
2749        // Try to reserve id..=id+reserve_size-1
2750        let reserved = IdSet::from_single_span(IdSpan::new(low, high));
2751        let intersected = reserved.intersection(covered);
2752        if let Some(span) = intersected.iter_span_asc().next() {
2753            // Overlap with existing covered spans. Decrease `high` so it
2754            // no longer overlap.
2755            if span.low > low && shrink_to_fit {
2756                // Use the remaining part of the previous reservation.
2757                //   [----------reserved--------------]
2758                //             [--intersected--]
2759                //   ^                                ^
2760                //   low                              high
2761                //            ^
2762                //            last_free
2763                //   [reserved] <- remaining of the previous reservation
2764                //            ^
2765                //            high
2766                let last_free = span.low - 1;
2767                high = last_free;
2768            } else {
2769                // No space on the left side. Try the right side.
2770                //   [--------reserved-------]
2771                //   [--intersected--]
2772                //   ^                       ^
2773                //   low                     high
2774                //        try next -> [------reserved------]
2775                //  ^                 ^
2776                //  last_free         low (try next)
2777                low = span.high + 1;
2778                continue;
2779            }
2780        }
2781        break;
2782    }
2783    if count >= 4096 {
2784        tracing::warn!(
2785            target: "dag::perf",
2786            count=count,
2787            low=?original_low,
2788            reserve_size=reserve_size,
2789            covered=?covered,
2790            "PERF: find_free_span took too long",
2791        );
2792    }
2793    let span = IdSpan::new(low, high);
2794    if !shrink_to_fit {
2795        assert_eq!(span.count(), reserve_size);
2796    }
2797    span
2798}
2799
2800fn is_ok_some<T>(value: Result<Option<T>>) -> bool {
2801    match value {
2802        Ok(Some(_)) => true,
2803        _ => false,
2804    }
2805}
2806
2807impl<IS, M, P, S> IdMapSnapshot for AbstractDag<IdDag<IS>, M, P, S>
2808where
2809    IS: IdDagStore,
2810    IdDag<IS>: TryClone + 'static,
2811    M: TryClone + IdConvert + Send + Sync + 'static,
2812    P: TryClone + Send + Sync + 'static,
2813    S: TryClone + Send + Sync + 'static,
2814{
2815    fn id_map_snapshot(&self) -> Result<Arc<dyn IdConvert + Send + Sync>> {
2816        Ok(self.try_snapshot()? as Arc<dyn IdConvert + Send + Sync>)
2817    }
2818}
2819
2820impl<IS, M, P, S> fmt::Debug for AbstractDag<IdDag<IS>, M, P, S>
2821where
2822    IS: IdDagStore,
2823    M: IdConvert + Send + Sync,
2824    P: Send + Sync,
2825    S: Send + Sync,
2826{
2827    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2828        debug(&self.dag, &self.map, f)
2829    }
2830}
2831
2832pub(crate) fn debug_segments_by_level_group<S: IdDagStore>(
2833    iddag: &IdDag<S>,
2834    idmap: &dyn IdConvert,
2835    level: Level,
2836    group: Group,
2837) -> Vec<String> {
2838    let mut result = Vec::new();
2839    // Show Id, with optional hash.
2840    let show = |id: Id| DebugId {
2841        id,
2842        name: non_blocking_result(idmap.vertex_name(id)).ok(),
2843    };
2844    let show_flags = |flags: SegmentFlags| -> String {
2845        let mut result = Vec::new();
2846        if flags.contains(SegmentFlags::HAS_ROOT) {
2847            result.push("Root");
2848        }
2849        if flags.contains(SegmentFlags::ONLY_HEAD) {
2850            result.push("OnlyHead");
2851        }
2852        result.join(" ")
2853    };
2854
2855    if let Ok(segments) = iddag.next_segments(group.min_id(), level) {
2856        for segment in segments.into_iter().rev() {
2857            if let (Ok(span), Ok(parents), Ok(flags)) =
2858                (segment.span(), segment.parents(), segment.flags())
2859            {
2860                let mut line = format!(
2861                    "{:.12?} : {:.12?} {:.12?}",
2862                    show(span.low),
2863                    show(span.high),
2864                    parents.into_iter().map(show).collect::<Vec<_>>(),
2865                );
2866                let flags = show_flags(flags);
2867                if !flags.is_empty() {
2868                    line += &format!(" {flags}");
2869                }
2870                result.push(line);
2871            }
2872        }
2873    }
2874    result
2875}
2876
2877fn debug<S: IdDagStore>(
2878    iddag: &IdDag<S>,
2879    idmap: &dyn IdConvert,
2880    f: &mut fmt::Formatter,
2881) -> fmt::Result {
2882    if let Ok(max_level) = iddag.max_level() {
2883        writeln!(f, "Max Level: {max_level}")?;
2884        for lv in (0..=max_level).rev() {
2885            writeln!(f, " Level {lv}")?;
2886            for group in Group::ALL.iter().cloned() {
2887                writeln!(f, "  {group}:")?;
2888                if let Ok(segments) = iddag.next_segments(group.min_id(), lv) {
2889                    writeln!(f, "   Segments: {}", segments.len())?;
2890                    for line in debug_segments_by_level_group(iddag, idmap, lv, group) {
2891                        writeln!(f, "    {line}")?;
2892                    }
2893                }
2894            }
2895        }
2896    }
2897
2898    Ok(())
2899}
2900
2901struct DebugId {
2902    id: Id,
2903    name: Option<Vertex>,
2904}
2905
2906impl fmt::Debug for DebugId {
2907    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2908        if let Some(name) = &self.name {
2909            fmt::Debug::fmt(&name, f)?;
2910            f.write_str("+")?;
2911        }
2912        write!(f, "{:?}", self.id)?;
2913        Ok(())
2914    }
2915}
2916
2917#[cfg(test)]
2918mod tests {
2919    use super::*;
2920
2921    #[test]
2922    fn test_find_free_span_overflow() {
2923        let covered = IdSet::from(0..=6);
2924        let reserve_size = 2;
2925        for shrink_to_fit in [true, false] {
2926            let span = find_free_span(&covered, Id(0), reserve_size, shrink_to_fit);
2927            assert_eq!(span, IdSpan::from(7..=8));
2928        }
2929    }
2930}