Skip to main content

nibkeep_node/library/
behind.rs

1//! Purging what a move leaves behind ([technical design: spaces and moves]): the mover's replica purges, in
2//! the old space, what its member's role lets it purge there, once the new entity counts and
3//! another device holds it; a mark asks the old space's admins for the rest, and an admin's
4//! replica lists those requests where the new entity counts with the same values.
5//!
6//! [technical design: spaces and moves]: ../../../../docs/Technical-design.md#131-spaces-and-moves
7
8use std::collections::{BTreeMap, BTreeSet};
9use std::path::PathBuf;
10
11use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
12use nibkeep_crypto::VerifyingKey;
13use nibkeep_crypto::rand_core::CryptoRng;
14use nibkeep_governance::Role as MemberRole;
15use nibkeep_log::ChangeId;
16use nibkeep_model::storage::Statements;
17use nibkeep_model::{FieldName, Value, fields};
18use nibkeep_sync::Synced;
19
20use super::Library;
21use super::members::users_and_owners;
22use crate::NodeError;
23
24/// An entity that a move left behind, whose mover asked that the rest of it be purged, as an
25/// admin's replica lists it: where the new entity counts with the same values.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct PurgeRequest {
28	/// The entity left behind.
29	pub entity: EntityId,
30	/// The space it is in now, and the entity it is there.
31	pub moved_into: (SpaceId, EntityId),
32}
33
34/// What a member may purge of an entity left behind, of one kind, secret or ordinary: the
35/// statements, and the content that no statement that stays holds.
36#[derive(Default)]
37struct Part {
38	statements: Vec<StatementId>,
39	contents: Vec<Hash>,
40}
41
42/// A move of this replica's whose leftovers hold content, which waits for that content's
43/// copies in the new space to be proven before it is purged.
44pub(crate) struct WaitingMove {
45	/// The old space, and the entity left there.
46	pub(crate) space: SpaceId,
47	pub(crate) entity: EntityId,
48	/// The space it moved into.
49	pub(crate) now_in: SpaceId,
50	/// The contents that the leftovers hold which moved, each with whether it is secret.
51	pub(crate) contents: Vec<(Hash, bool)>,
52}
53
54/// What a member may purge of an entity left behind: its ordinary values, and its secret
55/// values, sealed or of a field secret in the space, each with their content.
56#[derive(Default)]
57struct Remains {
58	ordinary: Part,
59	secret: Part,
60}
61
62impl Remains {
63	/// How many values it purges.
64	fn len(&self) -> usize {
65		self.ordinary.statements.len() + self.secret.statements.len()
66	}
67
68	/// Whether it purges no value.
69	fn is_empty(&self) -> bool {
70		self.len() == 0
71	}
72}
73
74/// Leaves out of `contents`, ordinary and secret, what a statement that stays holds in a
75/// field of the same kind, of the entity left behind or another: one that none of
76/// `statements` is. A purge of content destroys only the keys of its kind, so a secret
77/// file's content stays readable through the secrets, and the other way round, as a purge
78/// of a value says.
79fn keep_held<S: Statements>(
80	storage: &S,
81	secret_here: &BTreeSet<FieldName>,
82	statements: &[BTreeSet<StatementId>; 2],
83	contents: &mut [BTreeSet<Hash>; 2],
84) -> Result<(), S::Error> {
85	if contents.iter().all(BTreeSet::is_empty) {
86		return Ok(());
87	}
88	for other in storage.described()? {
89		for (field, ids) in storage.of_entity(other)? {
90			for id in ids {
91				if statements.iter().any(|kind| kind.contains(&id)) {
92					continue;
93				}
94				// What a thumbnail was made of, it names without holding it.
95				if let Some(recorded) = storage.get(id)?
96					&& let Value::Blob(content) = &recorded.statement.value
97					&& !nibkeep_std::names_content_only(&field)
98				{
99					let kind = secret_here.contains(&field) || storage.is_secret(id)?;
100					contents[usize::from(kind)].remove(content);
101				}
102			}
103		}
104	}
105	Ok(())
106}
107
108/// The fields whose statements a purge of what stays behind leaves: the marks.
109pub(crate) fn is_mark(field: &FieldName) -> bool {
110	*field == fields::MOVED_INTO || *field == fields::PURGE_ASKED || *field == fields::MERGED_INTO
111}
112
113/// Who purges: a member who may purge anything, as in the personal space or as an admin; an
114/// editor, who purges only the changes their member's replicas signed; or nobody, as a
115/// replica that its space does not list, or revoked.
116enum Purger {
117	All,
118	Own(EntityId, BTreeMap<[u8; 32], EntityId>),
119	Nobody,
120}
121
122impl Library {
123	/// The members of `from` who are no members of `to`, by name, sorted, and whether this
124	/// replica's member may purge all that a move from `from` leaves behind, as
125	/// [`crate::MovePreview`] says.
126	pub(crate) fn losing_and_purging(
127		&self,
128		(from, to): (SpaceId, SpaceId),
129	) -> Result<(Vec<String>, bool), NodeError> {
130		if from == self.info.personal || !self.has_members(from)? {
131			return Ok((Vec::new(), true));
132		}
133		let users_of = |space: SpaceId| -> Result<BTreeSet<EntityId>, NodeError> {
134			if space == self.info.personal || !self.has_members(space)? {
135				return Ok(BTreeSet::from([self.info.user]));
136			}
137			Ok(self
138				.members(space)?
139				.into_iter()
140				.filter(|member| member.role != MemberRole::None)
141				.filter_map(|member| member.user)
142				.collect())
143		};
144		let staying = users_of(to)?;
145		let members = self.members(from)?;
146		let mut losing: Vec<String> = members
147			.iter()
148			.filter(|member| member.role != MemberRole::None)
149			.filter(|member| member.user.is_none_or(|user| !staying.contains(&user)))
150			.map(|member| member.name.clone().unwrap_or_default())
151			.collect();
152		losing.sort();
153		losing.dedup();
154		let purges_all = members
155			.iter()
156			.any(|member| member.this_user && member.role == MemberRole::Admin);
157		Ok((losing, purges_all))
158	}
159
160	/// Purges what moves that this replica made left behind, where a sync that started at
161	/// `started`, after the move, just synced the new entity's space with another device,
162	/// which then holds it: what this replica's member may purge in the old space, its own
163	/// changes as an editor, everything but the marks as an admin or in the personal space.
164	/// Leftovers that hold content, which the old space's replicas would lose, wait for the
165	/// planner, which purges them once that content's copies in the new space are proven
166	/// ([`Library::remove_proven`]). Called after each sync; returns the copies of this
167	/// device's checkouts that it deleted.
168	///
169	/// # Errors
170	///
171	/// Returns an error if a space cannot be read, or a purge cannot be saved.
172	pub fn settle_moves(
173		&mut self,
174		synced: &Synced,
175		started: u64,
176		wall_millis: u64,
177		rng: &mut impl CryptoRng,
178	) -> Result<Vec<PathBuf>, NodeError> {
179		// Not where the other device was revoked or removed, which is sent nothing new, nor
180		// in a space that this device dropped and deleted after the sync.
181		let mut held = BTreeSet::new();
182		for space in synced.spaces.iter().map(|space| space.space) {
183			if !self.spaces.contains_key(&space) {
184				continue;
185			}
186			let open = self.space(space)?;
187			let log = open.stored.log();
188			if !log.is_revoked(&synced.peer, &open.keys)?
189				&& !log.is_removed(&synced.peer, &open.keys)?
190			{
191				held.insert(space);
192			}
193		}
194		let synced = held;
195		if synced.is_empty() || self.is_ai_agent()? {
196			return Ok(Vec::new());
197		}
198		let own = self.replica.signing.verifying_key();
199		let mut due = Vec::new();
200		for space in self.spaces() {
201			if self.check_not_revoked(space).is_err() {
202				continue;
203			}
204			for entity in self.asked(space)? {
205				// Only this replica's own moves, made before the sync started.
206				if !self.asked_by(space, entity, (&own, started))? {
207					continue;
208				}
209				if let Some((now_in, _)) = self.moved_into(space, entity)?
210					&& synced.contains(&now_in)
211				{
212					due.push((space, entity, now_in));
213				}
214			}
215		}
216		let mut deleted = Vec::new();
217		for (space, entity, now_in) in due {
218			// Leftovers that hold content that moved wait for the planner, which purges them
219			// once the copies of that content in the new space are proven.
220			if let Some(remains) = self.remains(space, entity)?
221				&& !remains.is_empty()
222				&& self.moved_contents(now_in, &remains).is_empty()
223			{
224				deleted.extend(self.purge_remains(space, &remains, wall_millis, rng)?);
225			}
226		}
227		Ok(deleted)
228	}
229
230	/// This replica's own moves whose leftovers hold content that moved, which wait for the
231	/// planner: each with its old space and entity, the new space, and those contents, with
232	/// whether each is secret ([technical design: the planner]).
233	///
234	/// [technical design: the planner]: ../../../../docs/Technical-design.md#99-the-planner
235	pub(crate) fn moves_waiting_for_copies(&self) -> Result<Vec<WaitingMove>, NodeError> {
236		if self.is_ai_agent()? {
237			return Ok(Vec::new());
238		}
239		let own = self.replica.signing.verifying_key();
240		let mut waiting = Vec::new();
241		for space in self.spaces() {
242			if self.check_not_revoked(space).is_err() {
243				continue;
244			}
245			for entity in self.asked(space)? {
246				if !self.asked_by(space, entity, (&own, u64::MAX))? {
247					continue;
248				}
249				let Some((now_in, _)) = self.moved_into(space, entity)? else {
250					continue;
251				};
252				if !self.spaces.contains_key(&now_in) {
253					continue;
254				}
255				let Some(remains) = self.remains(space, entity)? else {
256					continue;
257				};
258				if remains.is_empty() {
259					continue;
260				}
261				let contents = self.moved_contents(now_in, &remains);
262				if contents.is_empty() {
263					continue;
264				}
265				waiting.push(WaitingMove {
266					space,
267					entity,
268					now_in,
269					contents,
270				});
271			}
272		}
273		Ok(waiting)
274	}
275
276	/// Adds to what a move left behind of a file, `taken`, where its plain copies were: its
277	/// origins and checkouts that stayed, as those of other members' devices, deleted ones
278	/// too, so that nothing that stays holds its content; those that moved are left behind
279	/// themselves.
280	fn with_plain_copies(
281		&self,
282		space: SpaceId,
283		taken: &mut Vec<EntityId>,
284	) -> Result<(), NodeError> {
285		let files: BTreeSet<EntityId> = taken.iter().copied().collect();
286		for (record, moved, _) in self.plain_copies_of(space, &files)? {
287			if !moved {
288				taken.push(record);
289			}
290		}
291		Ok(())
292	}
293
294	/// The contents that leftovers hold which moved into `now_in`, as a key of a sealed copy
295	/// there says, each with whether it is secret: those whose copies there are to be proven
296	/// before the leftovers go. What did not move, as the old versions that a move without
297	/// history leaves, goes as the mover chose.
298	fn moved_contents(&self, now_in: SpaceId, remains: &Remains) -> Vec<(Hash, bool)> {
299		let Some(there) = self.spaces.get(&now_in) else {
300			return Vec::new();
301		};
302		let log = there.stored.log();
303		remains
304			.ordinary
305			.contents
306			.iter()
307			.map(|content| (*content, false))
308			.chain(
309				remains
310					.secret
311					.contents
312					.iter()
313					.map(|content| (*content, true)),
314			)
315			.filter(|(content, secret)| {
316				log.blob_keys(content)
317					.any(|(sealed, _)| log.is_secret_blob(sealed) == *secret)
318			})
319			.collect()
320	}
321
322	/// Purges what this replica's move of an entity left behind, as [`Library::settle_moves`]
323	/// does, once the planner has proven the copies in the new space of the content it holds;
324	/// returns the copies of this device's checkouts that it deleted, or `None` if nothing
325	/// was left to purge.
326	pub(crate) fn purge_left_behind(
327		&mut self,
328		space: SpaceId,
329		entity: EntityId,
330		wall_millis: u64,
331		rng: &mut impl CryptoRng,
332	) -> Result<Option<Vec<PathBuf>>, NodeError> {
333		match self.remains(space, entity)? {
334			Some(remains) if !remains.is_empty() => self
335				.purge_remains(space, &remains, wall_millis, rng)
336				.map(Some),
337			_ => Ok(None),
338		}
339	}
340
341	/// Purges what a member may purge of an entity left behind, in a purge for each kind of
342	/// content, secret or ordinary, as a purge destroys keys of one kind; returns the copies
343	/// of this device's checkouts that it deleted. If the second purge fails, the first
344	/// stays, and the next purge of what stays behind takes the rest.
345	fn purge_remains(
346		&mut self,
347		space: SpaceId,
348		remains: &Remains,
349		wall_millis: u64,
350		rng: &mut impl CryptoRng,
351	) -> Result<Vec<PathBuf>, NodeError> {
352		let mut deleted = Vec::new();
353		for (part, of_secrets) in [(&remains.ordinary, false), (&remains.secret, true)] {
354			if part.statements.is_empty() {
355				continue;
356			}
357			deleted.extend(self.purge_statements(
358				space,
359				&part.statements,
360				(&part.contents, of_secrets),
361				wall_millis,
362				rng,
363			)?);
364		}
365		Ok(deleted)
366	}
367
368	/// The entities of a space that moves left behind and whose movers asked that the rest
369	/// be purged, which this replica's member, an admin there, may purge: those whose new
370	/// entity counts in a space this replica holds, with the same values, and that still hold
371	/// more than their marks. Empty for a member who is no admin, and for the personal space,
372	/// where the mover purges all.
373	///
374	/// # Errors
375	///
376	/// Returns an error if the space cannot be read.
377	pub fn purge_requests(&self, space: SpaceId) -> Result<Vec<PurgeRequest>, NodeError> {
378		if space == self.info.personal || !self.has_members(space)? {
379			return Ok(Vec::new());
380		}
381		if self.check_settled_admin(space, "purge").is_err() {
382			return Ok(Vec::new());
383		}
384		let mut requests = Vec::new();
385		for entity in self.asked(space)? {
386			if let Some(moved_into) = self.purgeable_behind(space, entity)?
387				&& self
388					.remains(space, entity)?
389					.is_some_and(|remains| !remains.is_empty())
390			{
391				requests.push(PurgeRequest { entity, moved_into });
392			}
393		}
394		Ok(requests)
395	}
396
397	/// How many values [`Library::purge_behind`] would purge of an entity that a move left
398	/// behind: what this replica's member may purge there. `None` if no move asked for a
399	/// purge of it.
400	///
401	/// # Errors
402	///
403	/// Returns an error if the space cannot be read.
404	pub fn behind(&self, space: SpaceId, entity: EntityId) -> Result<Option<usize>, NodeError> {
405		Ok(self.remains(space, entity)?.map(|remains| remains.len()))
406	}
407
408	/// Purges what a move left behind of an entity, as asked: what this replica's member may
409	/// purge there, as [`Library::settle_moves`] says, once the new entity counts in a space
410	/// this replica holds with the values that the old one shows; returns how many values it
411	/// purged.
412	///
413	/// # Errors
414	///
415	/// Returns [`NodeError::NoPurgeAsked`] if no move asked for a purge of the entity,
416	/// [`NodeError::MovedDiffers`] if what moved is not here or differs, and an error if the
417	/// space cannot be read or the purge saved.
418	pub fn purge_behind(
419		&mut self,
420		space: SpaceId,
421		entity: EntityId,
422		wall_millis: u64,
423		rng: &mut impl CryptoRng,
424	) -> Result<usize, NodeError> {
425		self.check_not_revoked(space)?;
426		self.check_not_ai_agent("purge")?;
427		let Some(remains) = self.remains(space, entity)? else {
428			return Err(NodeError::NoPurgeAsked(entity.to_string()));
429		};
430		if remains.is_empty() {
431			return Ok(0);
432		}
433		if self.purgeable_behind(space, entity)?.is_none() {
434			return Err(NodeError::MovedDiffers(entity.to_string()));
435		}
436		self.purge_remains(space, &remains, wall_millis, rng)?;
437		Ok(remains.len())
438	}
439
440	/// Where the entity that a move made of one left behind counts, in a space this replica
441	/// holds, if it counts there with the values that the one left behind shows.
442	fn purgeable_behind(
443		&self,
444		space: SpaceId,
445		entity: EntityId,
446	) -> Result<Option<(SpaceId, EntityId)>, NodeError> {
447		let Some(moved_into) = self.moved_into(space, entity)? else {
448			return Ok(None);
449		};
450		Ok(self
451			.same_values((space, entity), moved_into)?
452			.then_some(moved_into))
453	}
454
455	/// The entities of a space whose moves asked that what stays of them be purged.
456	fn asked(&self, space: SpaceId) -> Result<Vec<EntityId>, NodeError> {
457		Ok(self
458			.space(space)?
459			.stored
460			.find(&fields::PURGE_ASKED, &Value::Boolean(true))?)
461	}
462
463	/// The changes of the marks that ask for a purge of an entity, with when each was made.
464	fn asking_changes(
465		&self,
466		space: SpaceId,
467		entity: EntityId,
468	) -> Result<Vec<(ChangeId, u64)>, NodeError> {
469		let state = self.space(space)?.stored.log().state();
470		let mut changes = Vec::new();
471		for statement in state.current(entity, &fields::PURGE_ASKED)? {
472			if let Some(recorded) = state.storage().get(statement.id)?
473				&& let Some(change) = recorded.change
474			{
475				changes.push((ChangeId::from_hash(change), recorded.at.millis()));
476			}
477		}
478		Ok(changes)
479	}
480
481	/// Whether a key signed a mark that asks for a purge of an entity, before `before`:
482	/// whether its replica made the move, before a sync that started then.
483	fn asked_by(
484		&self,
485		space: SpaceId,
486		entity: EntityId,
487		(key, before): (&VerifyingKey, u64),
488	) -> Result<bool, NodeError> {
489		let log = self.space(space)?.stored.log();
490		for (change, at) in self.asking_changes(space, entity)? {
491			if at < before
492				&& log
493					.change(change)?
494					.is_some_and(|change| change.author() == key)
495			{
496				return Ok(true);
497			}
498		}
499		Ok(false)
500	}
501
502	/// Who this replica's member is, as one who purges what moves leave in a space.
503	fn purger(&self, space: SpaceId) -> Result<Purger, NodeError> {
504		if space == self.info.personal || !self.has_members(space)? {
505			return Ok(Purger::All);
506		}
507		if self.check_not_revoked(space).is_err() {
508			return Ok(Purger::Nobody);
509		}
510		let Some(own) = self.member_in(space)? else {
511			return Ok(Purger::Nobody);
512		};
513		let open = self.space(space)?;
514		let roles = open.stored.log().member_roles(&open.keys)?;
515		Ok(match roles.get(&own) {
516			Some(MemberRole::Admin) => Purger::All,
517			Some(MemberRole::Editor) => {
518				Purger::Own(own, users_and_owners(&open.stored, &open.keys)?.1)
519			}
520			_ => Purger::Nobody,
521		})
522	}
523
524	/// What this replica's member may purge of an entity that a move left behind, as asked:
525	/// every statement, current or past, but the marks, of it and of the entities merged into
526	/// it before the move, that the move's mark builds on; of a secret value, sealed or of a
527	/// field secret in the space, only one that moved, as this replica sees the new entity
528	/// hold the same value in the same field, which needs the secrets of both spaces unlocked,
529	/// so that a value left behind, or one sealed out of sight, stays; of those, as an editor
530	/// of a shared space, only the ones its member's replicas signed; and, but for an editor,
531	/// the content of its files that no statement that stays holds. `None` if no move asked
532	/// for a purge of it.
533	fn remains(&self, space: SpaceId, entity: EntityId) -> Result<Option<Remains>, NodeError> {
534		let marks: Vec<ChangeId> = self
535			.asking_changes(space, entity)?
536			.into_iter()
537			.map(|(change, _)| change)
538			.collect();
539		if marks.is_empty() {
540			return Ok(None);
541		}
542		let purger = self.purger(space)?;
543		if matches!(purger, Purger::Nobody) {
544			return Ok(Some(Remains::default()));
545		}
546		// What the new entity holds, read once a secret value is met.
547		let mut moved: Option<Vec<(FieldName, Value)>> = None;
548		let open = self.space(space)?;
549		let secret_here = open.stored.secret_fields();
550		let log = open.stored.log();
551		let state = log.state();
552		let storage = state.storage();
553		let is_before = |change: ChangeId| -> Result<bool, NodeError> {
554			for mark in &marks {
555				if change != *mark && log.is_ancestor_of(change, *mark)? {
556					return Ok(true);
557				}
558			}
559			Ok(false)
560		};
561		// The entity, and those merged into it before the move, which the move took; never
562		// one merged with it since, which the move did not take.
563		let mut taken = vec![entity];
564		for other in state.merged(state.canonical(entity)?)? {
565			if other == entity {
566				continue;
567			}
568			for merge in state.current(other, &fields::MERGED_INTO)? {
569				if merge.value.as_reference() == Some(entity)
570					&& let Some(recorded) = storage.get(merge.id)?
571					&& let Some(change) = recorded.change
572					&& is_before(ChangeId::from_hash(change))?
573				{
574					taken.push(other);
575				}
576			}
577		}
578		self.with_plain_copies(space, &mut taken)?;
579		// The statements, and the contents, of each kind: ordinary, then secret.
580		let mut statements = [BTreeSet::new(), BTreeSet::new()];
581		let mut contents = [BTreeSet::new(), BTreeSet::new()];
582		for &each in &taken {
583			for (field, ids) in storage.of_entity(each)? {
584				if is_mark(&field) {
585					continue;
586				}
587				for id in ids {
588					let Some(recorded) = storage.get(id)? else {
589						continue;
590					};
591					let secret = secret_here.contains(&field) || storage.is_secret(id)?;
592					// A secret value only where it moved, as far as this replica sees.
593					let value = &recorded.statement.value;
594					if secret && !self.secret_moved((space, entity), (&field, value), &mut moved)? {
595						continue;
596					}
597					let kind = usize::from(secret);
598					let Some(change) = recorded.change.map(ChangeId::from_hash) else {
599						continue;
600					};
601					// An editor purges only the changes their own replicas signed, which is
602					// cheaper to tell than whether the move took it.
603					if let Purger::Own(own, owners) = &purger {
604						let signer = log
605							.change(change)?
606							.and_then(|change| owners.get(change.author().as_bytes()).copied());
607						if signer != Some(*own) {
608							continue;
609						}
610					}
611					// Only what the move took: what its mark builds on.
612					if !is_before(change)? {
613						continue;
614					}
615					// What a thumbnail was made of, it names without holding it.
616					if matches!(purger, Purger::All)
617						&& let Value::Blob(content) = &recorded.statement.value
618						&& !nibkeep_std::names_content_only(&field)
619					{
620						contents[kind].insert(*content);
621					}
622					statements[kind].insert(id);
623				}
624			}
625		}
626		keep_held(storage, secret_here, &statements, &mut contents)?;
627		self.take_thumbnails_staying(space, &mut statements, &mut contents)?;
628		let [ordinary, secret] = statements;
629		let [ordinary_contents, secret_contents] = contents;
630		Ok(Some(Remains {
631			ordinary: Part {
632				statements: ordinary.into_iter().collect(),
633				contents: ordinary_contents.into_iter().collect(),
634			},
635			secret: Part {
636				statements: secret.into_iter().collect(),
637				contents: secret_contents.into_iter().collect(),
638			},
639		}))
640	}
641
642	/// Adds to what a purge of what a move left behind takes, ordinary and secret, the
643	/// thumbnails made of the ordinary content it takes that stayed, as of a version the move
644	/// did not take: each one's statements, but its marks, and its own content, unless a
645	/// statement that stays holds that. Those that moved are left behind themselves, and
646	/// purged so.
647	fn take_thumbnails_staying(
648		&self,
649		space: SpaceId,
650		statements: &mut [BTreeSet<StatementId>; 2],
651		contents: &mut [BTreeSet<Hash>; 2],
652	) -> Result<(), NodeError> {
653		let open = self.space(space)?;
654		let state = open.stored.log().state();
655		let storage = state.storage();
656		let mut pictures = BTreeSet::new();
657		for content in &contents[0] {
658			for thumbnail in open
659				.stored
660				.find(&nibkeep_std::THUMBNAIL_OF, &Value::Blob(*content))?
661			{
662				if !state.current(thumbnail, &fields::MOVED_INTO)?.is_empty() {
663					continue;
664				}
665				for (field, ids) in storage.of_entity(thumbnail)? {
666					if is_mark(&field) {
667						continue;
668					}
669					for id in ids {
670						if field == nibkeep_std::CONTENT
671							&& let Some(recorded) = storage.get(id)?
672							&& let Value::Blob(picture) = recorded.statement.value
673						{
674							pictures.insert(picture);
675						}
676						statements[0].insert(id);
677					}
678				}
679			}
680		}
681		if !pictures.is_empty() {
682			let mut theirs = [pictures, BTreeSet::new()];
683			keep_held(
684				storage,
685				open.stored.secret_fields(),
686				statements,
687				&mut theirs,
688			)?;
689			let [pictures, _] = theirs;
690			contents[0].extend(pictures);
691		}
692		Ok(())
693	}
694
695	/// Whether a secret value of an entity that a move left behind moved, as this replica
696	/// sees the new entity hold the same value in the same field, a reference leading where
697	/// what it refers to moved, as a move carries it. Reads what the new entity holds into
698	/// `moved` the first time.
699	fn secret_moved(
700		&self,
701		(space, entity): (SpaceId, EntityId),
702		(field, value): (&FieldName, &Value),
703		moved: &mut Option<Vec<(FieldName, Value)>>,
704	) -> Result<bool, NodeError> {
705		if moved.is_none() {
706			*moved = Some(self.moved_values(space, entity)?);
707		}
708		let carried = match value {
709			Value::Reference(target) => {
710				let target = self.space(space)?.stored.log().state().canonical(*target)?;
711				self.moved_into(space, target)?
712					.map_or_else(|| value.clone(), |(_, now)| Value::Reference(now))
713			}
714			_ => value.clone(),
715		};
716		Ok(moved
717			.as_deref()
718			.unwrap_or_default()
719			.iter()
720			.any(|(moved_field, moved_value)| {
721				moved_field == field && (*moved_value == carried || moved_value == value)
722			}))
723	}
724
725	/// The values, current or past, that the entity a move made of one left behind holds,
726	/// each with its field, as far as this replica sees them: none where it does not hold the
727	/// space of the new entity, and no secret value of it while that space's secrets are
728	/// locked.
729	fn moved_values(
730		&self,
731		space: SpaceId,
732		entity: EntityId,
733	) -> Result<Vec<(FieldName, Value)>, NodeError> {
734		let Some((now_in, new)) = self.moved_into(space, entity)? else {
735			return Ok(Vec::new());
736		};
737		let state = self.space(now_in)?.stored.log().state();
738		let storage = state.storage();
739		let mut values = Vec::new();
740		for member in state.merged(state.canonical(new)?)? {
741			for (field, ids) in storage.of_entity(member)? {
742				for id in ids {
743					if let Some(recorded) = storage.get(id)? {
744						values.push((field.clone(), recorded.statement.into_owned().value));
745					}
746				}
747			}
748		}
749		Ok(values)
750	}
751
752	/// Whether the entity a move made counts with the values that the one it left behind
753	/// shows now: each of the old entity's fields that a move carries has, on the new one, a
754	/// value equal to one of the old one's, a reference leading where the old one's moved, if
755	/// it moved; one, as a field whose last writer wins carries only the value it shows.
756	fn same_values(
757		&self,
758		(space, entity): (SpaceId, EntityId),
759		(now_in, new): (SpaceId, EntityId),
760	) -> Result<bool, NodeError> {
761		let old_state = self.space(space)?.stored.log().state();
762		let new_state = self.space(now_in)?.stored.log().state();
763		let entity = old_state.canonical(entity)?;
764		for field in old_state.storage().current_fields(entity)? {
765			if is_mark(&field) || field == fields::DELETED {
766				continue;
767			}
768			let theirs = new_state.current(new, &field)?;
769			let (mut carried, mut matched) = (false, false);
770			for statement in old_state.current(entity, &field)? {
771				let value = match &statement.value {
772					Value::Reference(target) => match self.moved_into(space, *target)? {
773						Some((_, moved)) => Value::Reference(moved),
774						// A folder that stays holds what moved through its mark alone.
775						None if field == nibkeep_std::IN_FOLDER => continue,
776						None => statement.value.clone(),
777					},
778					value => value.clone(),
779				};
780				carried = true;
781				matched |= theirs.iter().any(|their| their.value == value);
782			}
783			if carried && !matched {
784				return Ok(false);
785			}
786		}
787		Ok(true)
788	}
789}