Skip to main content

tilo_resource/
founding.rs

1//! The founding an app's record is derived from: what every holder makes of it alike.
2//!
3//! An app's record holds its content alone. Two devices that make the same record before they
4//! sync (a person's vault opened on a phone and a laptop at once) would each make the containers
5//! its fields keep their items in, and the items one of them adds first would land in a
6//! container the merge leaves behind. So the containers come first, in one change every holder
7//! derives from the record's workspace, kind and id alone ([`Scope`]): an actor derived from them
8//! makes it at time zero. The store admits that change only as the one it derives itself
9//! ([`structure`]); the app's own first values follow as any change of its.
10//!
11//! The workspace is part of every derivation. A record's id can be the same in every workspace
12//! (a workspace's own accounts record), and a change two workspaces both held would be one
13//! change in both: a host keeping both would refuse the second, and the hash would link records
14//! the workspaces keep apart.
15
16use automerge::transaction::{CommitOptions, Transactable as _};
17use automerge::{AutoCommit, Change, ChangeHash, ChangeMetadata, ObjType, ROOT};
18use tilo_actions::surface::{FieldType, Surface};
19use tilo_automerge::ApplyIncoming as _;
20
21pub mod split;
22
23/// The record a founding and its steps are derived for: the record `id` of `kind` in the
24/// workspace `workspace`. A record is always one workspace's, so two workspaces holding a record
25/// of the same kind and id still derive changes of their own, and the holders within one derive
26/// the same.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub struct Scope<'a> {
29    pub workspace: &'a str,
30    pub kind: &'a str,
31    pub id: &'a str,
32}
33
34impl Scope<'_> {
35    /// The actor the record's founding is made under ([`structure`]). It is salted apart from
36    /// the actor of the record's identity genesis, which is derived from the same id, kind and
37    /// workspace: two different changes under one actor and sequence number would not merge.
38    #[must_use]
39    pub fn founding_actor(self) -> automerge::ActorId {
40        crate::genesis::actor(
41            self.id,
42            self.kind,
43            &format!("founding in {}", self.workspace),
44        )
45    }
46}
47
48/// The containers at the root of `surface`'s record that its top-level fields keep their items
49/// in, by field name: a collection, map, set or outbox in a map, a list in a list, a record of
50/// its own in a map: what [`structure`] makes.
51///
52/// An outbox is one of them: it is a unit the kind declares, empty when the record is founded,
53/// and a record whose every field is read-only takes no write to make it. Built by its creator
54/// instead, it would be the one change such a kind could not take, from the app or anyone.
55#[must_use]
56pub fn containers(surface: &Surface) -> Vec<(String, ObjType)> {
57    let mut containers: Vec<(String, ObjType)> = surface
58        .fields
59        .iter()
60        .filter(|field| !field.path.contains('.'))
61        .filter_map(|field| {
62            let container = match &field.ty {
63                // A set is a map whose keys are its members, as the resource types keep one.
64                FieldType::Collection(_)
65                | FieldType::Map(_)
66                | FieldType::Set(_)
67                | FieldType::Outbox(_) => ObjType::Map,
68                FieldType::List(_) => ObjType::List,
69                FieldType::Named(_) if field.stored == "record" => ObjType::Map,
70                _ => return None,
71            };
72            Some((field.path.clone(), container))
73        })
74        .collect();
75    containers.sort_by(|a, b| a.0.cmp(&b.0));
76    containers.dedup_by(|a, b| a.0 == b.0);
77    containers
78}
79
80/// The containers a record of `surface`'s kind founds with: its own record's ([`containers`]),
81/// as the store reads the kind's type from the surface. A surface naming its record by its label
82/// declares no type of its kind, and an enum of its kind is no record: either founds with none.
83#[must_use]
84pub fn of_kind(surface: &Surface) -> Vec<(String, ObjType)> {
85    let named = |name: &str| surface.types.iter().find(|ty| ty.name == name);
86    let own = match named(&surface.kind) {
87        Some(ty) => !ty.is_enum(),
88        None => named(&surface.label).is_none(),
89    };
90    if own { containers(surface) } else { Vec::new() }
91}
92
93/// The derived founding of the record `scope` names, whose fields keep their items in the
94/// `containers` named at its root. A kind that keeps none founds with a change that holds nothing:
95/// every record has its founding as its first head, so a record nothing was written to yet is kept
96/// and read back like any other, and what follows the founding names it as its dependency.
97///
98/// # Errors
99/// When a container cannot be put at the root under its field's name (an empty name).
100pub fn structure(
101    scope: Scope<'_>,
102    containers: &[(String, ObjType)],
103) -> Result<automerge::Change, automerge::AutomergeError> {
104    let mut doc = AutoCommit::new().with_actor(scope.founding_actor());
105    for (field, container) in containers {
106        doc.put_object(ROOT, field.as_str(), *container)?;
107    }
108    let options = || {
109        CommitOptions::default()
110            .with_message(tilo_actions::FrameworkChange::Genesis.change_message())
111            .with_time(0)
112    };
113    // A kind keeping no container commits nothing, so its founding is an empty change.
114    let hash = match doc.commit_with(options()) {
115        Some(hash) => hash,
116        None => doc.empty_change(options()),
117    };
118    doc.get_change_by_hash(&hash)
119        .ok_or(automerge::AutomergeError::MissingHash(hash))
120}
121
122/// The derived founding of the record `scope` names ([`structure`]) followed by the steps that
123/// bring it to each version up to `version` ([`crate::evolution::step`]): the chain every
124/// holder of a record at `version` stands on. Each step follows the one before it, the first the
125/// founding, so two holders that wrote their own changes meanwhile still make it byte for byte
126/// alike.
127///
128/// # Errors
129/// When the founding or a step cannot be made ([`structure`]).
130pub fn chain(
131    scope: Scope<'_>,
132    version: u32,
133    containers: &[(String, ObjType)],
134) -> Result<Vec<automerge::Change>, automerge::AutomergeError> {
135    let founding = structure(scope, containers)?;
136    chain_on(&founding, scope, version)
137}
138
139/// The steps that bring `founding`, the founding a record `scope` names stands on, to `version`.
140/// Derived on the founding the record itself holds, so a record founded by an older type — its
141/// containers those its type then declared — steps to the same version on every holder of it, and
142/// the steps a newer type derives on top of a founding it no longer has are never applied over it.
143///
144/// # Errors
145/// When a step cannot be made.
146pub fn chain_on(
147    founding: &automerge::Change,
148    scope: Scope<'_>,
149    version: u32,
150) -> Result<Vec<automerge::Change>, automerge::AutomergeError> {
151    let mut doc = AutoCommit::new();
152    doc.apply_incoming([founding.clone()])?;
153    let mut chain = vec![founding.clone()];
154    for version in 1..=version {
155        let step = crate::evolution::step(scope, version, &doc)?;
156        doc.apply_incoming([step.clone()])?;
157        chain.push(step);
158    }
159    Ok(chain)
160}
161
162/// A document whose founding and steps a holder reads: a [`AutoCommit`] a record is written
163/// through, or the [`automerge::Automerge`] a store keeps.
164pub trait FoundingDoc {
165    /// The metadata of every change it holds.
166    fn change_metas(&mut self) -> Vec<ChangeMetadata<'_>>;
167
168    /// The change `hash` names.
169    fn change_by_hash(&mut self, hash: &ChangeHash) -> Option<Change>;
170}
171
172impl FoundingDoc for AutoCommit {
173    fn change_metas(&mut self) -> Vec<ChangeMetadata<'_>> {
174        self.get_changes_meta(&[])
175    }
176
177    fn change_by_hash(&mut self, hash: &ChangeHash) -> Option<Change> {
178        self.get_change_by_hash(hash)
179    }
180}
181
182impl FoundingDoc for automerge::Automerge {
183    fn change_metas(&mut self) -> Vec<ChangeMetadata<'_>> {
184        self.get_changes_meta(&[])
185    }
186
187    fn change_by_hash(&mut self, hash: &ChangeHash) -> Option<Change> {
188        automerge::ReadDoc::get_change_by_hash(self, hash)
189    }
190}
191
192/// The founding change `doc` holds for `scope`: the one the record's derived founding actor made,
193/// whatever containers its type declared then. `None` for a record founded before foundings were
194/// derived (its own devices' changes alone), which takes the one its type derives now ([`found`]).
195#[must_use]
196pub fn founding_of(doc: &mut impl FoundingDoc, scope: Scope<'_>) -> Option<automerge::Change> {
197    let actor = scope.founding_actor();
198    let hash = doc
199        .change_metas()
200        .into_iter()
201        .find(|change| change.actor.as_ref() == &actor && change.seq == 1)?
202        .hash;
203    doc.change_by_hash(&hash)
204}
205
206/// The step that brings the record `scope` names to `version`, derived on the founding the record
207/// `doc` holds (or the one its type derives, for a record founded before foundings were derived):
208/// [`migrate`], for a holder that has the record.
209///
210/// # Errors
211/// When the founding or the step cannot be made, or `version` is no version a record steps to (0).
212pub fn migrate_on(
213    doc: &mut impl FoundingDoc,
214    scope: Scope<'_>,
215    version: u32,
216    containers: &[(String, ObjType)],
217) -> Result<automerge::Change, automerge::AutomergeError> {
218    let founding = match founding_of(doc, scope) {
219        Some(founding) => founding,
220        None => structure(scope, containers)?,
221    };
222    chain_on(&founding, scope, version)?
223        .pop()
224        .filter(|_| version > 0)
225        .ok_or(automerge::AutomergeError::Fail)
226}
227
228/// The step that brings the record `scope` names to `version`, on the chain [`chain`] derives:
229/// the one change a store admits under the migration verb for that version, and the one every
230/// holder writes.
231///
232/// # Errors
233/// When the chain cannot be made ([`chain`]), or `version` is no version a record steps to (0).
234pub fn migrate(
235    scope: Scope<'_>,
236    version: u32,
237    containers: &[(String, ObjType)],
238) -> Result<automerge::Change, automerge::AutomergeError> {
239    chain(scope, version, containers)?
240        .pop()
241        .filter(|_| version > 0)
242        .ok_or(automerge::AutomergeError::Fail)
243}
244
245/// Bring the record `scope` names, the app `app`'s, to `version`, in the one way every holder
246/// does: a record made before its founding was derived (two devices' own root containers) takes
247/// the founding and has what its devices made apart brought together
248/// ([`split::merge_split_containers`]); then the chain of steps up to `version`
249/// ([`chain`]) is written where it is not yet, and last the app's own `rewrite` of its content
250/// from the version the record stood at ([`crate::evolution::rewrite`]). Whether this
251/// changed anything.
252///
253/// # Errors
254/// When the founding, a step or the merge cannot be made, or the app's rewrite fails; `doc` is
255/// left with what was written before it.
256pub fn bring_up(
257    (scope, app): (Scope<'_>, &str),
258    version: u32,
259    containers: &[(String, ObjType)],
260    rewrite: &dyn Fn(&mut AutoCommit, u32) -> Result<(), crate::ModelError>,
261    doc: &mut AutoCommit,
262) -> Result<bool, crate::ModelError> {
263    let from = crate::evolution::stored_version(doc);
264    let (found_changed, held) = found_holding((scope, app), containers, doc)?;
265    let mut changed = found_changed;
266    // The chain follows the founding this record stands on, the one `found_holding` answered.
267    let current = structure(scope, containers)?;
268    let chain = if held == current.hash() {
269        chain_on(&current, scope, version)?
270    } else {
271        let founding = doc
272            .get_change_by_hash(&held)
273            .ok_or(automerge::AutomergeError::Fail)?;
274        chain_on(&founding, scope, version)?
275    };
276    let missing: Vec<automerge::Change> = chain
277        .into_iter()
278        .filter(|link| doc.get_change_by_hash(&link.hash()).is_none())
279        .collect();
280    changed |= !missing.is_empty();
281    doc.apply_incoming(missing)?;
282    if from < version || crate::evolution::stored_version(doc) < version {
283        changed |= crate::evolution::rewrite((scope, version), from, rewrite, doc)?;
284    }
285    Ok(changed)
286}
287
288/// Give the record `scope` names, the app `app`'s, its derived founding when it was made without
289/// one (two devices' own root containers, before every holder derived it), and bring together
290/// what its devices made apart ([`split::merge_split_containers`]): once, the first part
291/// of [`bring_up`], and all a store that reads no type's version does on opening a record. It
292/// answers whether this changed anything, and the founding the record holds after it: the one
293/// its type derives now, or the older one it was founded by, which a holder keeps so that a
294/// reopen is one lookup of it.
295///
296/// # Errors
297/// When the founding or the merge cannot be made.
298pub fn found_holding(
299    (scope, app): (Scope<'_>, &str),
300    containers: &[(String, ObjType)],
301    doc: &mut AutoCommit,
302) -> Result<(bool, ChangeHash), automerge::AutomergeError> {
303    let founding = structure(scope, containers)?;
304    let current = founding.hash();
305    if doc.get_change_by_hash(&current).is_some() {
306        return Ok((false, current));
307    }
308    if let Some(held) = founding_of(doc, scope) {
309        return Ok((false, held.hash()));
310    }
311    doc.apply_incoming([founding])?;
312    split::merge_split_containers(doc, scope, containers, app)?;
313    Ok((true, current))
314}
315
316/// [`bring_up`] of the record `id` of the resource type `R` in `workspace`, by the containers and
317/// version its surface declares and its own migration (`#[resource(migrate = ..)]`).
318///
319/// # Errors
320/// As [`bring_up`].
321pub fn bring_up_resource<R: crate::Resource>(
322    workspace: &str,
323    id: &str,
324    doc: &mut AutoCommit,
325) -> Result<bool, crate::ModelError> {
326    let scope = Scope {
327        workspace,
328        kind: R::KIND,
329        id,
330    };
331    bring_up(
332        (scope, R::APP_ID),
333        R::VERSION,
334        &of_kind(&crate::surface::surface_of::<R>()),
335        &|doc: &mut AutoCommit, from: u32| R::migrate(doc, from),
336        doc,
337    )
338}
339
340/// A new record `id` of `R` in `workspace`: its derived founding and the steps to `R`'s version
341/// ([`chain`]), then `R`'s first values, left uncommitted for the caller to commit under its own
342/// message. Its version comes from the chain alone, as every holder of the record derives it.
343///
344/// # Errors
345/// When the chain cannot be made, or `R`'s initializer fails.
346pub fn new_record<R: crate::Resource>(
347    workspace: &str,
348    id: &str,
349) -> Result<AutoCommit, crate::ModelError> {
350    let mut doc = AutoCommit::new();
351    let containers = of_kind(&crate::surface::surface_of::<R>());
352    let scope = Scope {
353        workspace,
354        kind: R::KIND,
355        id,
356    };
357    doc.apply_incoming(chain(scope, R::VERSION, &containers)?)?;
358    R::initialize(&mut doc)?;
359    Ok(doc)
360}
361
362#[cfg(test)]
363mod tests {
364    #![allow(clippy::unwrap_used, reason = "tests")]
365
366    use crate::evolution::{VERSION_KEY, stored_version};
367    use automerge::transaction::Transactable as _;
368    use automerge::{AutoCommit, ObjType, ROOT, ReadDoc as _};
369    use tilo_automerge::ApplyIncoming as _;
370
371    const KIND: &str = "test.founding.chain";
372    const ID: &str = "groceries";
373    const APP: &str = "test.app";
374    const SCOPE: super::Scope<'static> = super::Scope {
375        workspace: "6f1c1b62-4f5e-4b8a-9b52-1f8a3f0f3a11",
376        kind: KIND,
377        id: ID,
378    };
379
380    fn containers() -> Vec<(String, ObjType)> {
381        vec![("items".to_owned(), ObjType::Map)]
382    }
383
384    /// A record founded at `version` on a device of its own, with `wrote` written under `key` of
385    /// its items as that device's change.
386    fn device(version: u32, actor: u8, key: &str, wrote: &str) -> AutoCommit {
387        let mut doc = AutoCommit::new().with_actor(automerge::ActorId::from([actor; 16]));
388        doc.apply_incoming(super::chain(SCOPE, version, &containers()).unwrap())
389            .unwrap();
390        let (_, items) = doc.get(ROOT, "items").unwrap().unwrap();
391        doc.put(&items, key, wrote).unwrap();
392        doc.commit();
393        doc
394    }
395
396    /// A type whose versions change nothing but the version itself.
397    fn unchanged() -> impl Fn(&mut AutoCommit, u32) -> Result<(), crate::ModelError> {
398        |_, _| Ok(())
399    }
400
401    fn items(doc: &AutoCommit) -> Vec<String> {
402        let (_, items) = doc.get(ROOT, "items").unwrap().unwrap();
403        doc.keys(&items).collect()
404    }
405
406    /// A kind's outbox is one of its containers, founded empty on every holder alike: a record
407    /// whose every field is read-only would take no change to make it, from the app or anyone.
408    #[test]
409    fn a_kinds_queue_is_founded_with_its_containers() {
410        let surface: crate::Surface = serde_json::from_value(serde_json::json!({
411            "kind": "terminal.session",
412            "label": "Terminal",
413            "version": 1,
414            "fields": [
415                {
416                    "path": "requests",
417                    "type": {"outbox": {"named": "CommandRequest"}},
418                    "readonly": true,
419                    "unit": true
420                }
421            ],
422            "verbs": [],
423            "types": []
424        }))
425        .unwrap();
426        assert_eq!(
427            super::containers(&surface),
428            vec![("requests".to_owned(), ObjType::Map)],
429            "the outbox is founded like a map the kind keeps its items in"
430        );
431        let founding = super::structure(SCOPE, &super::containers(&surface)).unwrap();
432        let mut doc = AutoCommit::new();
433        doc.apply_incoming([founding]).unwrap();
434        assert_eq!(
435            doc.get(ROOT, "requests").unwrap().map(|(value, _)| value),
436            Some(automerge::Value::Object(ObjType::Map)),
437            "founded, and empty"
438        );
439    }
440
441    #[test]
442    fn two_devices_with_their_own_writes_step_a_record_up_byte_for_byte_alike() {
443        let mut here = device(1, 1, "milk", "2 l");
444        let mut there = device(1, 2, "eggs", "6");
445        let (own_heads, peer_heads) = (here.get_heads(), there.get_heads());
446        assert!(super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here).unwrap());
447        assert!(super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut there).unwrap());
448        let bytes = |changes: Vec<automerge::Change>| -> Vec<Vec<u8>> {
449            changes
450                .into_iter()
451                .map(|change| change.raw_bytes().to_vec())
452                .collect()
453        };
454        let ours = bytes(here.get_changes(&own_heads));
455        let theirs = bytes(there.get_changes(&peer_heads));
456        // Each device wrote the steps to versions 2 and 3 and nothing else, and both wrote the
457        // same bytes: the derived ones, whatever each device's own writes were.
458        assert_eq!(ours, theirs);
459        assert_eq!(
460            ours,
461            bytes(super::chain(SCOPE, 3, &containers()).unwrap().split_off(2))
462        );
463        for (to, step) in (2..=3).zip(super::chain(SCOPE, 3, &containers()).unwrap().split_off(2)) {
464            assert_eq!(
465                super::migrate(SCOPE, to, &containers()).unwrap().hash(),
466                step.hash()
467            );
468        }
469        tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
470        assert_eq!(stored_version(&here), 3);
471        assert_eq!(items(&here), ["eggs", "milk"]);
472        // Brought up already: nothing more.
473        assert!(!super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here).unwrap());
474    }
475
476    #[test]
477    fn a_rewrite_two_devices_make_apart_keeps_one_default() {
478        // Version 2 adds the record's tags, and each device's rewrite fills the default in on its
479        // own history: the two rewrites make the same key once, and each device's items stay.
480        let mut here = device(1, 1, "milk", "2 l");
481        let mut there = here.fork().with_actor(automerge::ActorId::from([2; 16]));
482        let (_, kept) = there.get(ROOT, "items").unwrap().unwrap();
483        there.put(&kept, "eggs", "6").unwrap();
484        there.commit();
485        let add_tags = |doc: &mut AutoCommit, from: u32| {
486            assert_eq!(from, 1);
487            let tags = doc.put_object(ROOT, "tags", ObjType::Map)?;
488            doc.put(&tags, "default", "kept")?;
489            Ok(())
490        };
491        super::bring_up((SCOPE, APP), 2, &containers(), &add_tags, &mut here).unwrap();
492        super::bring_up((SCOPE, APP), 2, &containers(), &add_tags, &mut there).unwrap();
493        tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
494        let (_, tags) = here.get(ROOT, "tags").unwrap().unwrap();
495        assert_eq!(here.keys(&tags).collect::<Vec<_>>(), ["default"]);
496        assert_eq!(items(&here), ["eggs", "milk"]);
497        assert_eq!(stored_version(&here), 2);
498    }
499
500    #[test]
501    fn a_record_made_before_its_founding_was_derived_is_founded_once_and_brought_together() {
502        // Two devices each made the record's container of their own, and added to it.
503        let made = |actor: u8, key: &str| {
504            let mut doc = AutoCommit::new().with_actor(automerge::ActorId::from([actor; 16]));
505            let items = doc.put_object(ROOT, "items", ObjType::Map).unwrap();
506            doc.put(&items, key, "kept").unwrap();
507            doc.commit();
508            doc
509        };
510        let mut here = made(1, "milk");
511        let mut there = made(2, "eggs");
512        tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
513        let mut again = here.fork();
514        assert!(super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut here).unwrap());
515        assert!(super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut again).unwrap());
516        // Every holder converts it alike.
517        assert_eq!(here.get_heads(), again.get_heads());
518        let founding = super::structure(SCOPE, &containers()).unwrap();
519        assert!(here.get_change_by_hash(&founding.hash()).is_some());
520        let mut held = items(&here);
521        held.sort();
522        assert_eq!(held, ["eggs", "milk"]);
523        assert_eq!(stored_version(&here), 2);
524        assert!(here.get(ROOT, VERSION_KEY).unwrap().is_some());
525        assert!(!super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut here).unwrap());
526    }
527
528    #[test]
529    fn the_same_record_in_two_workspaces_shares_no_change() {
530        // A workspace's own records have the same id in every workspace; a host holding two
531        // workspaces keeps each one's apart, so neither the founding nor a step may be the same
532        // change in both.
533        let other = super::Scope {
534            workspace: "0b9d7a3e-2c41-4f6b-8e15-7a9c3d2e1f40",
535            ..SCOPE
536        };
537        let hashes = |scope| -> Vec<automerge::ChangeHash> {
538            super::chain(scope, 3, &containers())
539                .unwrap()
540                .iter()
541                .map(automerge::Change::hash)
542                .collect()
543        };
544        let (here, there) = (hashes(SCOPE), hashes(other));
545        assert_eq!(here.len(), 4);
546        assert!(here.iter().all(|hash| !there.contains(hash)));
547        assert_ne!(
548            super::structure(SCOPE, &containers()).unwrap().hash(),
549            super::structure(other, &containers()).unwrap().hash()
550        );
551        // Nor is its actor the one the record's identity genesis in its workspace is made under,
552        // which a record founded beside that genesis would hold two first changes of.
553        assert_ne!(
554            SCOPE.founding_actor(),
555            crate::genesis::actor(ID, KIND, SCOPE.workspace)
556        );
557        // Brought up from records each workspace's devices made apart, neither shares a change
558        // with the other either.
559        let mut here_doc = device(1, 1, "milk", "2 l");
560        let mut there_doc = AutoCommit::new().with_actor(automerge::ActorId::from([1; 16]));
561        there_doc
562            .apply_incoming(super::chain(other, 1, &containers()).unwrap())
563            .unwrap();
564        super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here_doc).unwrap();
565        super::bring_up((other, APP), 3, &containers(), &unchanged(), &mut there_doc).unwrap();
566        let held = |doc: &mut AutoCommit| -> Vec<automerge::ChangeHash> {
567            doc.get_changes(&[])
568                .iter()
569                .map(automerge::Change::hash)
570                .collect()
571        };
572        let there_held = held(&mut there_doc);
573        assert!(
574            held(&mut here_doc)
575                .iter()
576                .all(|hash| !there_held.contains(hash))
577        );
578    }
579}