Skip to main content

nibkeep_node/library/
removal.rs

1//! Removing the copies that this replica no longer keeps, once copies on other disks have
2//! proven, right then, that they stand for them ([technical design: the planner]): a pass
3//! plans the removals and the challenges to put to replicas found on the network, the syncs
4//! with those replicas put them, and the copies whose proofs came in time go.
5//!
6//! [technical design: the planner]: ../../../../docs/Technical-design.md#99-the-planner
7
8use std::collections::{BTreeMap, BTreeSet};
9use std::fs::File;
10use std::io::{self, Read, Seek, SeekFrom};
11use std::path::PathBuf;
12use std::time::{Duration, Instant};
13
14use nibkeep_base::{EntityId, Hash, SpaceId};
15use nibkeep_crypto::rand_core::CryptoRng;
16use nibkeep_crypto::{BlobReader, VerifyingKey};
17use nibkeep_model::storage::Statements;
18use nibkeep_model::{Value, fields};
19use nibkeep_std::{CONTENT, FILE};
20use nibkeep_sync::Challenge;
21
22use super::Library;
23use super::accounts::{Checked, disk_id};
24use super::behind::WaitingMove;
25use super::checking::COUNTS_FOR_MILLIS;
26use super::planner::Keeps;
27use super::policies::{Kept, facts_of, own_choices};
28use crate::role::Records;
29use crate::{DeviceRole, Needs, NodeError, Replica};
30
31/// How long the proofs of a replica stand after it was asked for them: 8 minutes, short of
32/// the 10 for which it holds what it proved, so that it holds them still when the copies
33/// here go, even if the clocks of the two run a little apart.
34const PROOFS_STAND: Duration = Duration::from_secs(480);
35
36/// How many copies a pass removes at most, so that a device removes a little at a time.
37pub const REMOVALS_AT_ONCE: usize = 1024;
38
39/// A copy that a pass is to remove: a sealed blob of a space that this replica holds and no
40/// longer keeps.
41struct Candidate {
42	space: SpaceId,
43	sealed: Hash,
44	content: Hash,
45	/// Its size in bytes.
46	size: u64,
47	/// For each disk that may stand for it, the replica there asked to prove its copy, with
48	/// whether the disk is an archive node's.
49	provers: Vec<(Prover, bool)>,
50	/// How many of those are to prove their copies, how many of those archive nodes', and
51	/// how many kept away from home.
52	needed: usize,
53	archived: usize,
54	away: usize,
55	/// How many copies this replica's own disk keeps besides: one where it holds an
56	/// unchanged original of a content that its policy keeps in place.
57	own: usize,
58	/// The sealed copy of its content with a smaller sealed hash that this replica holds,
59	/// if it is that copy's twin: one that goes without proofs, as the disk keeps the
60	/// content in the other.
61	twin_of: Option<Hash>,
62}
63
64/// The challenges put to a replica in a space, by the hash each names and whether it is
65/// plain, each with the answer expected.
66type ChallengesOf = BTreeMap<(Hash, bool), (Challenge, [u8; 32])>;
67
68/// What a pass asks of one replica: the challenges to put to it in each space, each with
69/// the answer that this replica's own copy gives; when they were put; and which it proved.
70#[derive(Default)]
71struct Asking {
72	challenges: BTreeMap<SpaceId, ChallengesOf>,
73	asked: Option<Instant>,
74	proven: BTreeSet<(SpaceId, Hash, bool)>,
75}
76
77/// A pass of removals, as [`Library::plan_removals`] plans it: the copies to remove, and
78/// what to ask the replicas that are to prove theirs, which a sync with each of
79/// [`Removals::provers`] puts to them ([`crate::Syncing::proving`]).
80#[derive(Default)]
81pub struct Removals {
82	candidates: Vec<Candidate>,
83	asking: BTreeMap<[u8; 32], Asking>,
84	provers: Vec<Replica>,
85	/// How many copies that it no longer keeps stay for now: no disks found on the network
86	/// can stand for them, their policy needs a copy away from home, or the pass had room for
87	/// no more.
88	waiting: usize,
89	/// Whether more copies could be removed than the pass had room for.
90	more: bool,
91	/// This replica's moves whose leftovers wait for their content's copies in the new space
92	/// to be proven.
93	moves: Vec<MovePurge>,
94	/// The backups plugged into this computer that may stand for copies, by the key that
95	/// stands for each among the provers, with their folders: this replica reads them itself.
96	backups: BTreeMap<[u8; 32], PathBuf>,
97	/// Of those, the ones kept away from home.
98	away: BTreeSet<[u8; 32]>,
99}
100
101/// A move of this replica's whose leftovers a pass purges once the copies in the new space
102/// of the content they hold are proven: the old space and entity, and for each content, the
103/// new space, the sealed copy there that this replica holds, and the replicas chosen to
104/// prove theirs.
105struct MovePurge {
106	space: SpaceId,
107	entity: EntityId,
108	/// The space it moved into, as the pass planned.
109	now_in: SpaceId,
110	proofs: Vec<(SpaceId, Hash, Hash, Vec<Prover>)>,
111}
112
113/// A replica asked to prove a copy, by its key, and whether it proves an original, by the
114/// content's own bytes, rather than a sealed copy.
115type Prover = ([u8; 32], bool);
116
117/// What the copies of a content of a space need, as `needs` gives the strictest policy of
118/// the files that hold or held each content: where this replica keeps nothing of the space,
119/// as it drops it, a content that no file holds, as a thumbnail's or a secret file's, needs
120/// one copy elsewhere, as every replica keeps it; elsewhere, what a file needs that no rule
121/// chooses for.
122fn needs_of(needs: &BTreeMap<Hash, Needs>, content: &Hash, keeps: &Keeps) -> Needs {
123	needs
124		.get(content)
125		.copied()
126		.unwrap_or(if *keeps == Keeps::Nothing {
127			Needs::ONE
128		} else {
129			Needs::FALLBACK
130		})
131}
132
133impl Removals {
134	/// The replicas to sync with, so that they prove their copies.
135	#[must_use]
136	pub fn provers(&self) -> &[Replica] {
137		&self.provers
138	}
139
140	/// The challenges to put to `peer` in a space, noting when they were first put to it.
141	pub(crate) fn challenges(&mut self, space: SpaceId, peer: &VerifyingKey) -> Vec<Challenge> {
142		let Some(asking) = self.asking.get_mut(peer.as_bytes()) else {
143			return Vec::new();
144		};
145		let Some(challenges) = asking.challenges.get(&space) else {
146			return Vec::new();
147		};
148		asking.asked.get_or_insert_with(Instant::now);
149		challenges
150			.values()
151			.map(|(challenge, _)| challenge.clone())
152			.collect()
153	}
154
155	/// Takes `peer`'s answers to the challenges put to it in a space: those that its own
156	/// copy also gives prove its copies.
157	pub(crate) fn proved(
158		&mut self,
159		space: SpaceId,
160		peer: &VerifyingKey,
161		challenges: &[Challenge],
162		answers: &[Option<[u8; 32]>],
163	) {
164		let Some(asking) = self.asking.get_mut(peer.as_bytes()) else {
165			return;
166		};
167		let Some(expected) = asking.challenges.get(&space) else {
168			return;
169		};
170		for (challenge, answer) in challenges.iter().zip(answers) {
171			if expected
172				.get(&(challenge.sealed, challenge.plain))
173				.is_some_and(|(put, answered)| put == challenge && *answer == Some(*answered))
174			{
175				asking
176					.proven
177					.insert((space, challenge.sealed, challenge.plain));
178			}
179		}
180	}
181
182	/// Whether enough of the replicas asked for a candidate proved their copies, while their
183	/// proofs stand: as many as it needs, and as many of them archive nodes' as it needs;
184	/// one that proved an original only where `in_place` says that an original counts.
185	fn proven(&self, candidate: &Candidate, in_place: bool) -> bool {
186		let proved: Vec<&(Prover, bool)> = candidate
187			.provers
188			.iter()
189			.filter(|(prover, _)| in_place || !prover.1)
190			.filter(|(prover, _)| {
191				self.all_proved(
192					candidate.space,
193					(&candidate.sealed, &candidate.content),
194					std::slice::from_ref(prover),
195				)
196			})
197			.collect();
198		proved.len() >= candidate.needed
199			&& proved.iter().filter(|(_, archive)| *archive).count() >= candidate.archived
200			&& proved
201				.iter()
202				.filter(|((key, _), _)| self.away.contains(key))
203				.count()
204				>= candidate.away
205	}
206
207	/// Whether each of `provers` proved its copy, of a sealed blob of a space or of its
208	/// content as an original, while its proofs stand.
209	fn all_proved(
210		&self,
211		space: SpaceId,
212		(sealed, content): (&Hash, &Hash),
213		provers: &[Prover],
214	) -> bool {
215		provers.iter().all(|(prover, plain)| {
216			let of = if *plain { *content } else { *sealed };
217			self.asking.get(prover).is_some_and(|asking| {
218				asking
219					.asked
220					.is_some_and(|asked| asked.elapsed() < PROOFS_STAND)
221					&& asking.proven.contains(&(space, of, *plain))
222			})
223		})
224	}
225
226	/// Notes a challenge to put to a replica of a sealed blob of a space, with the answer
227	/// expected; one put to it already for that blob stands, and serves both. A backup
228	/// plugged in here answers at once, as this replica reads its copy itself.
229	fn ask(&mut self, prover: [u8; 32], space: SpaceId, challenge: Challenge, expected: [u8; 32]) {
230		let folder = self.backups.get(&prover).cloned();
231		let asking = self.asking.entry(prover).or_default();
232		let key = (challenge.sealed, challenge.plain);
233		if let Some(folder) = folder
234			&& !challenge.plain
235		{
236			let answered = File::open(folder.join(crate::backup::blob_path(&challenge.sealed)))
237				.ok()
238				.and_then(|mut file| answer_from_file(&challenge, &mut file).ok());
239			if answered == Some(expected) {
240				asking.asked.get_or_insert_with(Instant::now);
241				asking.proven.insert((space, challenge.sealed, false));
242			}
243		}
244		asking
245			.challenges
246			.entry(space)
247			.or_default()
248			.entry(key)
249			.or_insert((challenge, expected));
250	}
251}
252
253/// What a pass of removals did.
254#[derive(Clone, Debug, Default, PartialEq, Eq)]
255pub struct Removed {
256	/// How many copies it removed.
257	pub copies: usize,
258	/// Their bytes.
259	pub bytes: u64,
260	/// How many copies that this replica no longer keeps stay for now: their copies
261	/// elsewhere were not all found or proven, their policy needs a copy away from home,
262	/// another replica holds them for its own removal, or the pass had room for no more.
263	pub waiting: usize,
264	/// Whether more could be removed than the pass had room for, so that another pass
265	/// soon removes more.
266	pub more: bool,
267	/// How many of this replica's moves it purged what they left behind, once the copies
268	/// in the new space of the content they held were proven.
269	pub moves: usize,
270	/// The copies of this device's checkouts that those purges deleted.
271	pub deleted: Vec<std::path::PathBuf>,
272	/// Why purges that it tried failed, which the next pass tries again.
273	pub failed: Vec<String>,
274}
275
276/// The replicas found on each disk other than this replica's, in the order of their keys:
277/// each with the sealed blobs, and the contents of unchanged originals, that its latest
278/// account lists, and whether the disk is an archive node's.
279type OnDisks = BTreeMap<Hash, Vec<OnDisk>>;
280
281/// What may stand for copies elsewhere: the keys of the replicas found on the network, and
282/// the backups plugged in here.
283type Standing<'a> = (&'a BTreeSet<[u8; 32]>, &'a [BackupHere]);
284
285/// A backup plugged into this computer, as a pass of removals reads it.
286struct BackupHere {
287	/// The key that stands for it among the provers.
288	prover: [u8; 32],
289	/// What names its disk.
290	disk: Vec<u8>,
291	/// The spaces whose items it holds here.
292	spaces: Vec<SpaceId>,
293	/// Whether it is kept away from home.
294	away: bool,
295	/// The sealed blobs it holds in files of their own, with when each was last checked.
296	sealed: Checked,
297	/// Its folder.
298	folder: PathBuf,
299}
300
301/// The key that stands for a backup among the provers of a pass: no replica's, as it is
302/// derived from the backup's ID.
303fn backup_prover(backup: EntityId) -> [u8; 32] {
304	let mut hasher = blake3::Hasher::new_derive_key("nibkeep 2026-11 backup prover");
305	hasher.update(backup.as_bytes());
306	*hasher.finalize().as_bytes()
307}
308
309/// A replica found on a disk, or a backup plugged in here, as [`OnDisks`] holds it.
310struct OnDisk {
311	key: [u8; 32],
312	sealed: Checked,
313	plain: Checked,
314	archive: bool,
315	/// Whether it is kept away from home: only a backup can be, as no replica away is on the
316	/// home network until relays.
317	away: bool,
318}
319
320/// The disks that may stand for a copy of a sealed blob of a content whose policy asks for
321/// `needs`, if enough can, besides `own` copies on this replica's disk: on each, the first
322/// replica found, or backup plugged in here, whose account lists, checked since `since`, an
323/// unchanged original of the content, where the policy keeps it in place, or else the sealed
324/// blob. At least one other disk unless `own` copies are enough. Returns each disk's prover,
325/// with whether it is to prove an original and whether the disk is an archive node's, in
326/// the order they are chosen in: those away from home that the policy asks for first, then
327/// the archive nodes' that it asks for, then originals, then archive nodes', then any; and
328/// how many of them are to prove their copies, how many of those archive nodes', and how
329/// many away. `None` if too few disks can: copies away from home only backups plugged in
330/// here stand for, as no replica away is on the home network until relays.
331fn choose_disks(
332	(sealed, content): (&Hash, &Hash),
333	(needs, own): (Needs, usize),
334	disks: &OnDisks,
335	since: u64,
336) -> Option<Chosen> {
337	let in_place = needs.kept == Kept::InPlace;
338	let counts = |checked: Option<&u64>| checked.is_some_and(|checked| *checked >= since);
339	// For each disk, the prover there, whether the disk is an archive node's, and whether it
340	// is away from home.
341	let mut found: Vec<(Prover, bool, bool)> = Vec::new();
342	for replicas in disks.values() {
343		let original = replicas
344			.iter()
345			.find(|replica| in_place && counts(replica.plain.get(content)))
346			.map(|replica| ((replica.key, true), replica.archive, replica.away));
347		if let Some(prover) = original.or_else(|| {
348			replicas
349				.iter()
350				.find(|replica| counts(replica.sealed.get(sealed)))
351				.map(|replica| ((replica.key, false), replica.archive, replica.away))
352		}) {
353			found.push(prover);
354		}
355	}
356	let away_needed = needs.away as usize;
357	let archived_needed = needs.archived as usize;
358	let total = (needs.copies as usize)
359		.max(archived_needed)
360		.max(away_needed)
361		.max(1)
362		.saturating_sub(own);
363	let away_found = found.iter().filter(|(_, _, away)| *away).count();
364	let archive_found = found.iter().filter(|(_, archive, _)| *archive).count();
365	if away_found < away_needed || archive_found < archived_needed || found.len() < total {
366		return None;
367	}
368	// Those away from home that the policy asks for first, archive nodes' first among them;
369	// then the archive nodes' that it asks for, originals first among them; then originals,
370	// where the policy keeps the content in place, as they are its copies; then archive
371	// nodes'; then any.
372	found.sort_by_key(|((_, original), archive, away)| (!*away, !*archive, !*original));
373	let mut chosen: Vec<(Prover, bool, bool)> = found
374		.iter()
375		.filter(|(_, _, away)| *away)
376		.take(away_needed)
377		.copied()
378		.collect();
379	let archived_chosen = chosen.iter().filter(|(_, archive, _)| *archive).count();
380	let mut by_archive = found.clone();
381	by_archive.sort_by_key(|((_, original), archive, _)| (!*archive, !*original));
382	chosen.extend(
383		by_archive
384			.into_iter()
385			.filter(|candidate| candidate.1 && !chosen.contains(candidate))
386			.take(archived_needed.saturating_sub(archived_chosen))
387			.collect::<Vec<_>>(),
388	);
389	let mut rest: Vec<(Prover, bool, bool)> = found
390		.into_iter()
391		.filter(|candidate| !chosen.contains(candidate))
392		.collect();
393	rest.sort_by_key(|((_, original), archive, _)| (!*original, !*archive));
394	// All are asked, the first `total` chosen, and any that prove make up for those that do
395	// not, as an original edited since its account was issued.
396	chosen.extend(rest);
397	Some(Chosen {
398		provers: chosen
399			.into_iter()
400			.map(|(prover, archive, _)| (prover, archive))
401			.collect(),
402		needed: total,
403		archived: archived_needed,
404		away: away_needed,
405	})
406}
407
408/// The replicas that may stand for a copy, as [`choose_disks`] chooses them.
409struct Chosen {
410	provers: Vec<(Prover, bool)>,
411	needed: usize,
412	archived: usize,
413	away: usize,
414}
415
416/// A challenge to put to a replica, by its key, with the answer expected.
417type Put = ([u8; 32], Challenge, [u8; 32]);
418
419/// The challenges to put to `provers` of a sealed blob of `size` bytes, each with the answer
420/// that this replica's copy, `file`, gives, or, to a replica that proves an original, the
421/// answer that the content gives, as `plain` reads it opened from that copy; `None` if that
422/// copy cannot be read, which is no copy to check others against.
423fn challenges_for(
424	(sealed, size, file): (Hash, u64, &mut File),
425	plain: Option<(Hash, &mut BlobReader<File>)>,
426	provers: &[(Prover, bool)],
427	rng: &mut impl CryptoRng,
428) -> Option<Vec<Put>> {
429	let mut put = Vec::new();
430	let mut plain = plain;
431	for ((prover, original), _) in provers {
432		let (challenge, expected) = if *original {
433			let (content, reader) = plain.as_mut()?;
434			let len = reader.seek(SeekFrom::End(0)).ok()?;
435			let challenge = Challenge::random_plain(*content, len, rng);
436			let expected = challenge
437				.answer(|offset, out| {
438					reader.seek(SeekFrom::Start(offset))?;
439					reader.read_exact(out)
440				})
441				.ok()?;
442			(challenge, expected)
443		} else {
444			let challenge = Challenge::random(sealed, size, rng);
445			let expected = answer_from_file(&challenge, file).ok()?;
446			(challenge, expected)
447		};
448		put.push((*prover, challenge, expected));
449	}
450	Some(put)
451}
452
453/// The answer to a challenge from the bytes of a sealed blob's file.
454pub(crate) fn answer_from_file(challenge: &Challenge, file: &mut File) -> io::Result<[u8; 32]> {
455	challenge.answer(|offset, out| {
456		file.seek(SeekFrom::Start(offset))?;
457		file.read_exact(out)
458	})
459}
460
461/// On a device that waits before purging, its sync records, which keep since when it no
462/// longer keeps each copy, and its waits; `None` on one that never waited.
463type DeviceWaits<'a> = Option<(&'a Records, &'a [(u64, u64)])>;
464
465impl Library {
466	/// Plans a pass of removals, as of `wall_millis`: the sealed blobs that this replica
467	/// holds and no longer keeps, as the planner says, at most [`REMOVALS_AT_ONCE`] of them,
468	/// and for each, other disks whose copies together meet the strictest policy of the files
469	/// that hold or held its content without this replica's, each with a replica on it found
470	/// on the network, whose `found` endpoints say, whose latest account lists a copy checked
471	/// in the last 8 weeks, or a backup plugged into this computer, which this replica reads
472	/// itself and proves at once; the challenges to put to those replicas, with the answers
473	/// that this replica's copies give. A copy whose policy needs a copy away from home waits
474	/// for relays, as no replica away is on the home network, unless a backup kept away is
475	/// plugged in; so does one that another space of the replica keeps a key for, which that
476	/// space may keep. So does one that this replica
477	/// holds for another, as `records` say, which is about to remove its own: asking that one
478	/// to prove its copy would hold it there in turn, and the two would keep each other from
479	/// removing for as long as both try.
480	///
481	/// # Errors
482	///
483	/// Returns an error if the library or the records cannot be read.
484	pub fn plan_removals(
485		&self,
486		records: &Records,
487		found: &BTreeSet<[u8; 32]>,
488		wall_millis: u64,
489		rng: &mut impl CryptoRng,
490	) -> Result<Removals, NodeError> {
491		let plan = self.plan(wall_millis)?;
492		let held = records.holds(wall_millis)?;
493		let mut removals = Removals::default();
494		let found_replicas = self.found_replicas(found)?;
495		let found_keys: BTreeSet<[u8; 32]> = found_replicas.keys().copied().collect();
496		// The backups plugged in here, which this replica reads itself: looked for only if
497		// anything may go.
498		let anything = plan.values().any(|keeps| *keeps != Keeps::All)
499			|| !self.moves_waiting_for_copies()?.is_empty();
500		let local = if anything {
501			self.backups_here(records)?
502		} else {
503			Vec::new()
504		};
505		removals.backups = local
506			.iter()
507			.map(|here| (here.prover, here.folder.clone()))
508			.collect();
509		removals.away = local
510			.iter()
511			.filter(|here| here.away)
512			.map(|here| here.prover)
513			.collect();
514		let mut eligible = Vec::new();
515		let moving = self.contents_moving()?;
516		// A device that waits before purging lets nothing go on another device's word before
517		// its wait has passed since it stopped keeping it.
518		let waits = self.space(self.info.personal)?.stored.waits()?;
519		let waiting = waits.iter().any(|(_, wait)| *wait > 0);
520		let mut unkept_now = BTreeSet::new();
521		for (&space, keeps) in &plan {
522			let twins = self.twins(space)?;
523			if *keeps != Keeps::All {
524				let waits = waiting.then_some((records, waits.as_slice()));
525				eligible.extend(self.eligible_in(
526					(space, keeps, &twins),
527					((&found_keys, &local), &held, moving.get(&space)),
528					(wall_millis, waits, &mut unkept_now),
529					&mut removals.waiting,
530				)?);
531			}
532			for &(sealed, content, smaller) in &twins {
533				if held.contains(&sealed) {
534					removals.waiting += 1;
535					continue;
536				}
537				eligible.push(Candidate {
538					space,
539					sealed,
540					content,
541					size: 0,
542					provers: Vec::new(),
543					needed: 0,
544					archived: 0,
545					away: 0,
546					own: 0,
547					twin_of: Some(smaller),
548				});
549			}
550		}
551		records.forget_unkept_but(&unkept_now)?;
552		// A window of the eligible from a random place, so that copies whose proofs keep
553		// failing do not take every pass's room.
554		if eligible.len() > REMOVALS_AT_ONCE {
555			let mut bytes = [0; 8];
556			rng.fill_bytes(&mut bytes);
557			let start =
558				usize::try_from(u64::from_le_bytes(bytes) % eligible.len() as u64).unwrap_or(0);
559			eligible.rotate_left(start);
560			removals.waiting += eligible.len() - REMOVALS_AT_ONCE;
561			eligible.truncate(REMOVALS_AT_ONCE);
562			removals.more = true;
563		}
564		for candidate in eligible {
565			self.put_challenges(&mut removals, candidate, rng)?;
566		}
567		for waiting in self.moves_waiting_for_copies()? {
568			let found = (&found_keys, local.as_slice());
569			self.plan_move_purge(&mut removals, waiting, found, wall_millis, rng)?;
570		}
571		removals.provers = removals
572			.asking
573			.keys()
574			.filter_map(|prover| found_replicas.get(prover).cloned())
575			.collect();
576		Ok(removals)
577	}
578
579	/// The other replicas, neither revoked nor deleted, whose endpoints were `found` on the
580	/// network, by their keys.
581	fn found_replicas(
582		&self,
583		found: &BTreeSet<[u8; 32]>,
584	) -> Result<BTreeMap<[u8; 32], Replica>, NodeError> {
585		let mut replicas = BTreeMap::new();
586		for replica in self.replicas()?.into_iter().chain(self.peers()?) {
587			if replica.this || replica.revoked || replica.deleted {
588				continue;
589			}
590			if let (Some(key), Some(endpoint)) = (replica.signing, replica.endpoint)
591				&& found.contains(&endpoint)
592			{
593				replicas.entry(*key.as_bytes()).or_insert(replica);
594			}
595		}
596		Ok(replicas)
597	}
598
599	/// The copies of a space that this replica could remove now, those it no longer keeps
600	/// as `keeps` says, each with the disks chosen to stand for it, as
601	/// [`Library::plan_removals`] says; `waiting` counts those that cannot go yet.
602	fn eligible_in(
603		&self,
604		(space, keeps, twins): (SpaceId, &Keeps, &[(Hash, Hash, Hash)]),
605		((found, local), held, moving): (Standing<'_>, &BTreeSet<Hash>, Option<&BTreeSet<Hash>>),
606		(wall_millis, waits, unkept_now): (u64, DeviceWaits<'_>, &mut BTreeSet<Hash>),
607		waiting: &mut usize,
608	) -> Result<Vec<Candidate>, NodeError> {
609		let mut unkept = self.unkept(space, keeps, twins)?;
610		// A copy that this replica's own move waits for stays until the move's leftovers go,
611		// as the replica checks the others' proofs against it.
612		if let Some(moving) = moving {
613			unkept.retain(|(_, content)| !moving.contains(content));
614		}
615		// On a device that waits, a copy goes only once its wait has passed since the device
616		// first found that it no longer keeps it, as when its policy took it out of the store,
617		// or the device is no longer an archive node.
618		if let Some((records, waits)) = waits {
619			let sealed: Vec<Hash> = unkept.iter().map(|(sealed, _)| *sealed).collect();
620			unkept_now.extend(sealed.iter().copied());
621			let since = records.unkept_since(&sealed, wall_millis)?;
622			unkept.retain(|(sealed, _)| {
623				let at = since.get(sealed).copied().unwrap_or(wall_millis);
624				let due = at.saturating_add(super::waiting::wait_at(waits, at)) <= wall_millis;
625				if !due {
626					*waiting += 1;
627				}
628				due
629			});
630		}
631		if unkept.is_empty() {
632			return Ok(Vec::new());
633		}
634		let needs = self.needs_of_contents(space)?;
635		let since = wall_millis.saturating_sub(COUNTS_FOR_MILLIS);
636		// Originals stand for copies of a content only where its policy keeps it in place:
637		// read only if such a content is to go.
638		let in_place = unkept.iter().any(|(_, content)| {
639			needs
640				.get(content)
641				.is_some_and(|needs| needs.kept == Kept::InPlace)
642		});
643		let disks = self.disks_of(space, (found, local), in_place)?;
644		// A device that drops the space counts none of its originals, which stay its person's
645		// files, no longer counted, once the space is gone.
646		let originals = if in_place && *keeps != Keeps::Nothing {
647			self.own_originals(space, since)?
648		} else {
649			BTreeSet::new()
650		};
651		let mut eligible = Vec::new();
652		for (sealed, content) in unkept {
653			if held.contains(&sealed) {
654				*waiting += 1;
655				continue;
656			}
657			let needs = needs_of(&needs, &content, keeps);
658			let own = usize::from(needs.kept == Kept::InPlace && originals.contains(&content));
659			let Some(chosen) = choose_disks((&sealed, &content), (needs, own), &disks, since)
660			else {
661				*waiting += 1;
662				continue;
663			};
664			eligible.push(Candidate {
665				space,
666				sealed,
667				content,
668				size: 0,
669				provers: chosen.provers,
670				needed: chosen.needed,
671				archived: chosen.archived,
672				away: chosen.away,
673				own,
674				twin_of: None,
675			});
676		}
677		Ok(eligible)
678	}
679
680	/// Adds a copy to a pass, with a challenge for each replica that is to prove its own,
681	/// and the answer that this replica's copy gives; one that cannot be read here waits.
682	fn put_challenges(
683		&self,
684		removals: &mut Removals,
685		mut candidate: Candidate,
686		rng: &mut impl CryptoRng,
687	) -> Result<(), NodeError> {
688		let stored = &self.space(candidate.space)?.stored;
689		let Some((size, mut file)) = stored.open_sealed_blob(&candidate.sealed)? else {
690			// Gone meanwhile, as a check moved it aside: it is to come again first.
691			removals.waiting += 1;
692			return Ok(());
693		};
694		candidate.size = size;
695		let mut reader = if candidate.provers.iter().any(|((_, original), _)| *original) {
696			let Ok(reader) = stored.open_blob(&candidate.content) else {
697				removals.waiting += 1;
698				return Ok(());
699			};
700			Some(reader)
701		} else {
702			None
703		};
704		let plain = reader.as_mut().map(|reader| (candidate.content, reader));
705		let Some(put) = challenges_for(
706			(candidate.sealed, size, &mut file),
707			plain,
708			&candidate.provers,
709			rng,
710		) else {
711			removals.waiting += 1;
712			return Ok(());
713		};
714		for (prover, challenge, expected) in put {
715			removals.ask(prover, candidate.space, challenge, expected);
716		}
717		removals.candidates.push(candidate);
718		Ok(())
719	}
720
721	/// Removes the copies of a pass whose proofs came while they stand, as of `wall_millis`,
722	/// those that this replica still does not keep and whose policy the proven copies still
723	/// meet: marked first in `records` as being removed, so that this replica proves none of
724	/// them to another meanwhile, and none that it holds for another, which it proved. Its
725	/// account then says that it no longer holds them. Then it purges what this replica's
726	/// moves left behind, of those whose content's copies in the new space were proven while
727	/// they stand, and this replica holds still; and moves on the drops of spaces that this
728	/// replica makes ([`Library::drop_space`]).
729	///
730	/// # Errors
731	///
732	/// Returns an error if the library cannot be read, the records cannot be written, or a
733	/// file cannot be removed; those removed before stay removed.
734	pub fn remove_proven(
735		&mut self,
736		removals: &Removals,
737		records: &Records,
738		wall_millis: u64,
739		rng: &mut impl CryptoRng,
740	) -> Result<Removed, NodeError> {
741		let mut removed = self.remove_copies(removals, records, wall_millis, rng)?;
742		for purge in &removals.moves {
743			let proved = purge
744				.proofs
745				.iter()
746				.all(|(space, sealed, content, provers)| {
747					self.spaces
748						.get(space)
749						.is_some_and(|open| open.stored.holds_sealed(sealed))
750						&& removals.all_proved(*space, (sealed, content), provers)
751				});
752			// The move counts still, as the syncs of the pass may have brought it set aside, or
753			// this replica revoked.
754			let stands = || -> Result<bool, NodeError> {
755				Ok(self.check_not_revoked(purge.space).is_ok()
756					&& self
757						.moved_into(purge.space, purge.entity)?
758						.is_some_and(|(now_in, _)| now_in == purge.now_in))
759			};
760			if !proved || !stands()? {
761				continue;
762			}
763			// A purge that fails waits for the next pass, and the pass goes on.
764			match self.purge_left_behind(purge.space, purge.entity, wall_millis, rng) {
765				Ok(Some(deleted)) => {
766					removed.moves += 1;
767					removed.deleted.extend(deleted);
768				}
769				Ok(None) => {}
770				Err(error) => removed.failed.push(error.to_string()),
771			}
772		}
773		// The drops whose last copies went now state their choices, to sync next.
774		if let Err(error) = self.settle_drops(wall_millis, rng) {
775			removed.failed.push(error.to_string());
776		}
777		Ok(removed)
778	}
779
780	/// Removes the copies of a pass whose proofs came while they stand, as
781	/// [`Library::remove_proven`] says.
782	fn remove_copies(
783		&mut self,
784		removals: &Removals,
785		records: &Records,
786		wall_millis: u64,
787		rng: &mut impl CryptoRng,
788	) -> Result<Removed, NodeError> {
789		let mut removed = Removed {
790			waiting: removals.waiting,
791			more: removals.more,
792			..Removed::default()
793		};
794		if removals.candidates.is_empty() {
795			return Ok(removed);
796		}
797		let kept_back = self.still_due(removals, wall_millis, &mut removed.waiting)?;
798		let all: Vec<Hash> = kept_back
799			.iter()
800			.map(|(candidate, _)| candidate.sealed)
801			.collect();
802		if all.is_empty() {
803			return Ok(removed);
804		}
805		let marked = records.begin_removing(&all, wall_millis)?;
806		// Whether the proofs stand is asked last, just before the copies go, so that the
807		// provers hold theirs still.
808		let mut by_space: BTreeMap<SpaceId, Vec<&Candidate>> = BTreeMap::new();
809		for (candidate, in_place) in kept_back {
810			if marked.contains(&candidate.sealed) && removals.proven(candidate, in_place) {
811				by_space.entry(candidate.space).or_default().push(candidate);
812			} else {
813				removed.waiting += 1;
814			}
815		}
816		let mut failed = None;
817		let mut touched = Vec::new();
818		for (space, candidates) in by_space {
819			let picked: Vec<Hash> = candidates
820				.iter()
821				.map(|candidate| candidate.sealed)
822				.collect();
823			let gone = match self.spaces.get(&space) {
824				Some(open) => open.stored.remove_sealed_blobs(&picked),
825				None => Err(nibkeep_store::StoreError::Io(io::Error::from(
826					io::ErrorKind::NotFound,
827				))),
828			};
829			let gone: BTreeSet<Hash> = match gone {
830				Ok(gone) => gone.into_iter().collect(),
831				Err(error) => {
832					failed.get_or_insert(error);
833					BTreeSet::new()
834				}
835			};
836			for candidate in candidates {
837				if gone.contains(&candidate.sealed) {
838					removed.copies += 1;
839					removed.bytes = removed.bytes.saturating_add(candidate.size);
840				} else {
841					removed.waiting += 1;
842				}
843			}
844			if !gone.is_empty() {
845				touched.push(space);
846			}
847		}
848		// The marks go whatever happened, so that no blob stays unproved for others.
849		let ended = records.end_removing(&all);
850		for space in touched {
851			// Its account says so now, rather than at a sync a minute later.
852			self.accounts_refreshed.borrow_mut().remove(&space);
853			let _ = self.refresh_account(space, wall_millis, rng);
854		}
855		ended?;
856		match failed {
857			Some(error) => Err(error.into()),
858			None => Ok(removed),
859		}
860	}
861
862	/// The contents of this device's originals of a space, kept where they were found, that
863	/// stand for copies where a policy keeps them in place: those of origins that recorded the
864	/// content they found, unchanged by their size and modification time, and found holding
865	/// it by a check since `since`; never a checkout, which NibKeep deletes and the person
866	/// edits.
867	fn own_originals(&self, space: SpaceId, since: u64) -> Result<BTreeSet<Hash>, NodeError> {
868		let checks: BTreeMap<(String, Hash), (u64, bool)> = self
869			.space(space)?
870			.stored
871			.place_checks()?
872			.into_iter()
873			.map(|check| ((check.path, check.content), (check.checked, check.held)))
874			.collect();
875		Ok(self
876			.origin_places_here(space)?
877			.into_iter()
878			.filter(|place| place.untouched)
879			.filter(|place| {
880				checks
881					.get(&(place.path.clone(), place.content))
882					.is_some_and(|(checked, held)| *held && *checked >= since)
883			})
884			.map(|place| place.content)
885			.collect())
886	}
887
888	/// The contents that this replica's own moves wait to purge what they left behind of, by
889	/// the spaces they moved into, whose copies there it keeps meanwhile.
890	fn contents_moving(&self) -> Result<BTreeMap<SpaceId, BTreeSet<Hash>>, NodeError> {
891		let mut moving: BTreeMap<SpaceId, BTreeSet<Hash>> = BTreeMap::new();
892		for waiting in self.moves_waiting_for_copies()? {
893			moving
894				.entry(waiting.now_in)
895				.or_default()
896				.extend(waiting.contents.iter().map(|(content, _)| *content));
897		}
898		Ok(moving)
899	}
900
901	/// The replicas found on each disk of a space other than this replica's, whose `found`
902	/// keys say, with what their latest accounts list there.
903	fn disks_of(
904		&self,
905		space: SpaceId,
906		(found, local): (&BTreeSet<[u8; 32]>, &[BackupHere]),
907		originals: bool,
908	) -> Result<OnDisks, NodeError> {
909		let archive = self.archive_disks(space)?;
910		let own_disk = self.own_disk(space);
911		let mut disks = OnDisks::new();
912		for (key, listed) in self.listed_by(space, found, originals)? {
913			if listed.disk != own_disk {
914				disks.entry(listed.disk).or_default().push(OnDisk {
915					key,
916					sealed: listed.sealed,
917					plain: listed.plain,
918					archive: archive.get(&listed.disk).copied().unwrap_or(false),
919					away: false,
920				});
921			}
922		}
923		// The backups plugged in here that hold the space, each keeping what an archive node
924		// keeps.
925		let own = self.replica.signing.verifying_key();
926		for here in local {
927			if !here.spaces.contains(&space) {
928				continue;
929			}
930			let disk = disk_id(space, Some(&here.disk), &own);
931			if disk != own_disk {
932				disks.entry(disk).or_default().push(OnDisk {
933					key: here.prover,
934					sealed: here.sealed.clone(),
935					plain: Checked::new(),
936					archive: true,
937					away: here.away,
938				});
939			}
940		}
941		// A disk is an archive node's, or away from home, only if all on it are, as counting
942		// says.
943		for on_disk in disks.values_mut() {
944			let archive = on_disk.iter().all(|each| each.archive);
945			let away = on_disk.iter().all(|each| each.away);
946			for each in on_disk.iter_mut() {
947				each.archive = archive;
948				each.away = away;
949			}
950		}
951		Ok(disks)
952	}
953
954	/// The backups plugged into this computer, found where `records` say they were last found
955	/// or at their folders' paths on the drives mounted, each with what its folder says it
956	/// holds in files of its own, with when each was last checked.
957	fn backups_here(&self, records: &Records) -> Result<Vec<BackupHere>, NodeError> {
958		let remembered = records
959			.backup_folders()?
960			.into_iter()
961			.map(|(backup, found)| (backup, found.folder))
962			.collect();
963		let mut here = Vec::new();
964		for (backup, folder) in self.find_backups(&remembered)? {
965			// One being updated, or cut short while it was, stands for nothing until an update
966			// has read it back; one that cannot be read now stands for nothing either, and the
967			// pass goes on.
968			let in_folder = crate::backup::InFileSystem::new(&folder);
969			if crate::backup::marked_in_use(&in_folder) {
970				continue;
971			}
972			let Ok(files) = crate::backup::blob_files_in(&in_folder) else {
973				continue;
974			};
975			let record = crate::backup::read_record(&in_folder);
976			let sealed: Checked = files
977				.into_keys()
978				.map(|sealed| (sealed, record.checks.get(&sealed).copied().unwrap_or(0)))
979				.collect();
980			here.push(BackupHere {
981				prover: backup_prover(backup.id),
982				disk: crate::backup::disk_name(&in_folder, backup.id),
983				spaces: self.backup_spaces(&backup)?,
984				away: backup.away,
985				sealed,
986				folder,
987			});
988		}
989		Ok(here)
990	}
991
992	/// Adds to a pass a move of this replica's whose leftovers hold content: for each
993	/// content, the sealed copy in the new space that this replica holds, and replicas on
994	/// other disks found on the network whose accounts there list it, as many as make, with
995	/// this replica's disk, the copies that the new entity's policy asks for, archive nodes'
996	/// among them only once the new space has an archive node, and none away from home until
997	/// relays; with challenges for them. A move with a content that this replica holds no
998	/// sealed copy of in the new space, or that too few disks hold, waits.
999	fn plan_move_purge(
1000		&self,
1001		removals: &mut Removals,
1002		waiting: WaitingMove,
1003		(found, local): (&BTreeSet<[u8; 32]>, &[BackupHere]),
1004		wall_millis: u64,
1005		rng: &mut impl CryptoRng,
1006	) -> Result<(), NodeError> {
1007		let new_space = waiting.now_in;
1008		let needs = self.needs_of_contents(new_space)?;
1009		let archive_counts = self.has_archive_node(new_space)?;
1010		let own_archive = self.device_marks(self.info.device)?.role == DeviceRole::Archive;
1011		let disks = self.disks_of(new_space, (found, local), false)?;
1012		let since = wall_millis.saturating_sub(COUNTS_FOR_MILLIS);
1013		let stored = &self.space(new_space)?.stored;
1014		let log = stored.log();
1015		let mut proofs = Vec::new();
1016		let mut put = Vec::new();
1017		for (content, secret) in waiting.contents {
1018			let Some(sealed) = log
1019				.blob_keys(&content)
1020				.map(|(copy, _)| *copy)
1021				.filter(|copy| log.is_secret_blob(copy) == secret && stored.holds_sealed(copy))
1022				.min()
1023			else {
1024				return Ok(());
1025			};
1026			let policy = needs.get(&content).copied().unwrap_or(Needs::FALLBACK);
1027			// This replica's copy is one of them; at least one other, so that another device
1028			// holds the new entity, as the purge always waited for.
1029			let others = Needs {
1030				copies: policy.copies.saturating_sub(1).max(1),
1031				away: 0,
1032				archived: if archive_counts {
1033					policy.archived.saturating_sub(u32::from(own_archive))
1034				} else {
1035					0
1036				},
1037				kept: policy.kept,
1038			};
1039			// Sealed copies alone, as an original kept in place holds no copy of the new space.
1040			let sealed_only = Needs {
1041				kept: Kept::Store,
1042				..others
1043			};
1044			let Some(chosen) = choose_disks((&sealed, &content), (sealed_only, 0), &disks, since)
1045			else {
1046				return Ok(());
1047			};
1048			let Some((size, mut file)) = stored.open_sealed_blob(&sealed)? else {
1049				return Ok(());
1050			};
1051			// Those chosen alone, as each must prove: the others make up for none.
1052			let provers: Vec<(Prover, bool)> =
1053				chosen.provers.into_iter().take(chosen.needed).collect();
1054			let Some(challenges) = challenges_for((sealed, size, &mut file), None, &provers, rng)
1055			else {
1056				return Ok(());
1057			};
1058			put.extend(challenges);
1059			proofs.push((
1060				new_space,
1061				sealed,
1062				content,
1063				provers.into_iter().map(|(prover, _)| prover).collect(),
1064			));
1065		}
1066		for (prover, challenge, expected) in put {
1067			removals.ask(prover, new_space, challenge, expected);
1068		}
1069		removals.moves.push(MovePurge {
1070			space: waiting.space,
1071			entity: waiting.entity,
1072			now_in: new_space,
1073			proofs,
1074		});
1075		Ok(())
1076	}
1077
1078	/// The copies of a pass that are still to go, as of `wall_millis`: twins whose smaller
1079	/// copy is here still, and copies that this replica still does not keep and whose policy
1080	/// the disks chosen, with this replica's original where it counts, still meet, each with
1081	/// whether the policy keeps it in place, so that originals proved count; `waiting` counts
1082	/// the others but those kept now.
1083	fn still_due<'r>(
1084		&self,
1085		removals: &'r Removals,
1086		wall_millis: u64,
1087		waiting: &mut usize,
1088	) -> Result<Vec<(&'r Candidate, bool)>, NodeError> {
1089		let plan = self.plan(wall_millis)?;
1090		let since = wall_millis.saturating_sub(COUNTS_FOR_MILLIS);
1091		let mut needs: BTreeMap<SpaceId, BTreeMap<Hash, Needs>> = BTreeMap::new();
1092		let mut originals: BTreeMap<SpaceId, BTreeSet<Hash>> = BTreeMap::new();
1093		let mut kept_back = Vec::new();
1094		for candidate in &removals.candidates {
1095			// A twin goes while its smaller copy is here, whatever the replica keeps.
1096			if let Some(smaller) = candidate.twin_of {
1097				let open = self.space(candidate.space)?;
1098				if open.stored.holds_sealed(&smaller)
1099					&& !open.stored.log().wrapped_blob_keys_of(&smaller).is_empty()
1100				{
1101					kept_back.push((candidate, false));
1102				} else {
1103					*waiting += 1;
1104				}
1105				continue;
1106			}
1107			// One that the replica keeps now, as a sync brought a pin, stays and waits for
1108			// nothing.
1109			if plan
1110				.get(&candidate.space)
1111				.is_none_or(|keeps| keeps.keeps(&candidate.content))
1112			{
1113				continue;
1114			}
1115			if let std::collections::btree_map::Entry::Vacant(entry) = needs.entry(candidate.space)
1116			{
1117				entry.insert(self.needs_of_contents(candidate.space)?);
1118			}
1119			let keeps = plan.get(&candidate.space).unwrap_or(&Keeps::All);
1120			let now_needs = needs
1121				.get(&candidate.space)
1122				.map_or(Needs::FALLBACK, |needs| {
1123					needs_of(needs, &candidate.content, keeps)
1124				});
1125			let in_place = now_needs.kept == Kept::InPlace;
1126			// An original here counts while the policy keeps the content in place, and it is
1127			// unchanged and checked still.
1128			let own = if in_place && candidate.own > 0 {
1129				if let std::collections::btree_map::Entry::Vacant(entry) =
1130					originals.entry(candidate.space)
1131				{
1132					entry.insert(self.own_originals(candidate.space, since)?);
1133				}
1134				usize::from(
1135					originals
1136						.get(&candidate.space)
1137						.is_some_and(|here| here.contains(&candidate.content)),
1138				)
1139			} else {
1140				0
1141			};
1142			let met = now_needs.away as usize <= candidate.away
1143				&& candidate.needed + own >= now_needs.copies.max(1) as usize;
1144			if met {
1145				kept_back.push((candidate, in_place));
1146			} else {
1147				*waiting += 1;
1148			}
1149		}
1150		Ok(kept_back)
1151	}
1152
1153	/// The sealed blobs of a space that this replica holds and does not keep, with their
1154	/// contents: ordinary ones, whose contents it can tell, or any where it keeps nothing of
1155	/// the space, and that no other space of the replica keeps a key for.
1156	fn unkept(
1157		&self,
1158		space: SpaceId,
1159		keeps: &Keeps,
1160		twins: &[(Hash, Hash, Hash)],
1161	) -> Result<Vec<(Hash, Hash)>, NodeError> {
1162		let stored = &self.space(space)?.stored;
1163		let log = stored.log();
1164		// A space that this device drops keeps no blob, a secret one neither: one whose
1165		// content cannot be read here, as while the secrets are locked, stands for its content
1166		// by its sealed hash, and needs one copy elsewhere, as every replica keeps it.
1167		let nothing = *keeps == Keeps::Nothing;
1168		let unkept: Vec<(Hash, Hash)> = stored
1169			.sealed_blobs()?
1170			.into_iter()
1171			.filter(|sealed| nothing || !log.is_secret_blob(sealed))
1172			.filter_map(|sealed| match log.content_of_sealed(&sealed) {
1173				Some(content) => (!keeps.keeps(&content)).then_some((sealed, content)),
1174				None => nothing.then_some((sealed, sealed)),
1175			})
1176			.collect();
1177		if unkept.is_empty() {
1178			return Ok(unkept);
1179		}
1180		let sealed: Vec<Hash> = unkept.iter().map(|(sealed, _)| *sealed).collect();
1181		let elsewhere = stored.keyed_elsewhere(&sealed);
1182		let twins: BTreeSet<Hash> = twins.iter().map(|(sealed, _, _)| *sealed).collect();
1183		Ok(unkept
1184			.into_iter()
1185			.filter(|(sealed, _)| !elsewhere.contains(sealed) && !twins.contains(sealed))
1186			.collect())
1187	}
1188
1189	/// The sealed blobs of a space that this replica holds beside another ordinary sealed
1190	/// copy of the same content, of the space too, with a smaller sealed hash: each with its
1191	/// content and the smallest such copy. One that another space of the replica keeps a key
1192	/// for is left out, as that space may lack the smaller copy's key.
1193	fn twins(&self, space: SpaceId) -> Result<Vec<(Hash, Hash, Hash)>, NodeError> {
1194		let stored = &self.space(space)?.stored;
1195		let log = stored.log();
1196		let held: BTreeSet<Hash> = stored
1197			.sealed_blobs()?
1198			.into_iter()
1199			.filter(|sealed| !log.is_secret_blob(sealed))
1200			.collect();
1201		let mut twins = Vec::new();
1202		for sealed in &held {
1203			let Some(content) = log.content_of_sealed(sealed) else {
1204				continue;
1205			};
1206			if let Some(smaller) = log
1207				.blob_keys(&content)
1208				.map(|(copy, _)| *copy)
1209				.filter(|copy| copy < sealed && held.contains(copy))
1210				.min()
1211			{
1212				twins.push((*sealed, content, smaller));
1213			}
1214		}
1215		if twins.is_empty() {
1216			return Ok(twins);
1217		}
1218		let sealed: Vec<Hash> = twins.iter().map(|(sealed, _, _)| *sealed).collect();
1219		let elsewhere = stored.keyed_elsewhere(&sealed);
1220		Ok(twins
1221			.into_iter()
1222			.filter(|(sealed, _, _)| !elsewhere.contains(sealed))
1223			.collect())
1224	}
1225
1226	/// How many of the sealed blobs of a space that this replica holds, and that no other
1227	/// space of it keeps a key for, other disks' accounts, as `copies` gives them, show
1228	/// fewer copies of than they need where this replica keeps nothing of the space, as
1229	/// [`Library::drop_space`] counts them: those a drop could never remove. A content that a
1230	/// policy keeps in place is left to the check of files, as originals stand for it.
1231	pub(crate) fn blobs_short_elsewhere(
1232		&self,
1233		space: SpaceId,
1234		copies: &super::accounts::Copies,
1235	) -> Result<usize, NodeError> {
1236		let unkept = self.unkept(space, &Keeps::Nothing, &[])?;
1237		if unkept.is_empty() {
1238			return Ok(0);
1239		}
1240		let needs = self.needs_of_contents(space)?;
1241		let mut short = 0;
1242		for (sealed, content) in unkept {
1243			let needs = needs_of(&needs, &content, &Keeps::Nothing);
1244			if needs.kept == Kept::InPlace {
1245				continue;
1246			}
1247			let (mut disks, _) = copies.holding(&[sealed], (&[], None));
1248			disks.remove(&super::accounts::Copies::OWN);
1249			let (away, archived) = copies.marked(&disks);
1250			short += usize::from(needs.lacks(disks.len(), away, archived).any());
1251		}
1252		Ok(short)
1253	}
1254
1255	/// What the copies of each content that a file of a space holds or held need: the
1256	/// strictest of the policies chosen for those files.
1257	fn needs_of_contents(&self, space: SpaceId) -> Result<BTreeMap<Hash, Needs>, NodeError> {
1258		let policies = self.read_policies(space)?;
1259		let open = self.space(space)?;
1260		let state = open.stored.log().state();
1261		let storage = state.storage();
1262		let mut needs: BTreeMap<Hash, Needs> = BTreeMap::new();
1263		let mut seen = BTreeSet::new();
1264		for file in open
1265			.stored
1266			.find(&fields::TYPE, &Value::Text(FILE.to_string()))?
1267		{
1268			let file = state.canonical(file)?;
1269			if !seen.insert(file) {
1270				continue;
1271			}
1272			let chosen = policies
1273				.choose(&own_choices(state, file)?, &facts_of(state, file)?)
1274				.needs;
1275			for member in state.merged(file)? {
1276				for id in storage.of_field(member, &CONTENT)? {
1277					if let Some(recorded) = storage.get(id)?
1278						&& let Value::Blob(content) = recorded.statement.value
1279					{
1280						let entry = needs.entry(content).or_insert(chosen);
1281						*entry = entry.strictest(chosen);
1282					}
1283				}
1284			}
1285		}
1286		Ok(needs)
1287	}
1288}