1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
|
"""
A root that goes away freezes; it never empties.
This is the property the whole per-root availability design exists for. Unplug a
drive while the node is running and the filesystem watcher either reports every
file under it as deleted, or the next scan sees an empty directory. Acting on
either propagates deletions for a whole library, to every member, as though the
owner had erased it — and the index is what the node serves, so the loss is not
local.
Every test here is written as "the entries are still there". They fail against
an indexer that treats a vanished root as a set of deletions, which is what the
straightforward implementation does.
"""
import asyncio
import os
from pathlib import Path
import pytest
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from meshbay_node.indexer.indexer import DirectoryIndexer
from meshbay_node.roots import RootSet
pytestmark = pytest.mark.asyncio
def _roots(*paths: Path, removable: bool = False) -> RootSet:
specs = [{"path": str(p)} for p in paths]
specs[0]["writable"] = True
if removable:
for spec in specs:
spec["removable"] = True
return RootSet.build(specs)
async def _indexer(roots: RootSet) -> DirectoryIndexer:
idx = DirectoryIndexer(roots=roots, group_id="g" * 32,
sk_node=Ed25519PrivateKey.generate(), gek=None)
await idx.initial_scan()
return idx
def _names(idx: DirectoryIndexer) -> set[str]:
return {e.name for e in idx.index.entries}
# ── The freeze ───────────────────────────────────────────────────────────────
async def test_a_vanished_root_does_not_empty_the_index(tmp_path):
films = tmp_path / "Films"
films.mkdir()
(films / "a.mkv").write_bytes(b"a")
(films / "b.mkv").write_bytes(b"b")
idx = await _indexer(_roots(films))
assert _names(idx) == {"a.mkv", "b.mkv"}
# The volume goes away. Watchdog would now report both files as deleted.
for f in films.iterdir():
f.unlink()
films.rmdir()
for f in ("a.mkv", "b.mkv"):
await idx._update_entry(films / f, deleted=True)
assert _names(idx) == {"a.mkv", "b.mkv"}, (
"an unplugged drive emptied the index — every member would see the "
"library as deleted")
assert idx.roots.roots[0].available is False
async def test_reconcile_does_not_delete_from_an_unavailable_root(tmp_path):
"""The sweep must skip roots it cannot read: there is nothing to compare
against, and comparing anyway deletes everything."""
films = tmp_path / "Films"
films.mkdir()
(films / "a.mkv").write_bytes(b"a")
idx = await _indexer(_roots(films))
(films / "a.mkv").unlink()
films.rmdir()
await idx.reconcile()
assert _names(idx) == {"a.mkv"}
assert idx.roots.roots[0].available is False
async def test_one_root_going_away_leaves_the_others_alone(tmp_path):
films = tmp_path / "Films"
music = tmp_path / "Music"
films.mkdir()
music.mkdir()
(films / "a.mkv").write_bytes(b"a")
# Above the tiny-audio-file cutoff (indexer.py's MIN_AUDIO_SIZE_BYTES) —
# this test is about root availability, not that gate, so the content
# just needs to actually get indexed as an entry.
(music / "b.mp3").write_bytes(os.urandom(60 * 1024))
idx = await _indexer(_roots(films, music))
assert _names(idx) == {"a.mkv", "b.mp3"}
(music / "b.mp3").unlink()
music.rmdir()
await idx.reconcile()
assert _names(idx) == {"a.mkv", "b.mp3"}
by_name = {r.name: r.available for r in idx.roots}
assert by_name == {"Films": True, "Music": False}
async def test_members_are_told_which_roots_are_unavailable(tmp_path):
"""Frozen entries stay listed, so without this a member cannot tell
"temporarily unavailable" from "still there"."""
films = tmp_path / "Films"
films.mkdir()
(films / "a.mkv").write_bytes(b"a")
idx = await _indexer(_roots(films))
assert idx.index.roots == [
{"name": "Films", "kind": "generic", "available": True,
"writable": True, "removable": False, "ejected": False}]
(films / "a.mkv").unlink()
films.rmdir()
await idx.reconcile()
assert idx.index.roots[0]["available"] is False
# ── The counter-property ─────────────────────────────────────────────────────
async def test_a_file_deleted_from_a_live_root_is_removed(tmp_path):
"""
The freeze must not become "deletions never happen". A root that is readable
and a file that is genuinely gone is an ordinary deletion.
"""
films = tmp_path / "Films"
films.mkdir()
(films / "a.mkv").write_bytes(b"a")
(films / "b.mkv").write_bytes(b"b")
idx = await _indexer(_roots(films))
(films / "a.mkv").unlink()
await idx._update_entry(films / "a.mkv", deleted=True)
assert _names(idx) == {"b.mkv"}
async def test_reconcile_removes_what_is_genuinely_gone(tmp_path):
films = tmp_path / "Films"
films.mkdir()
(films / "a.mkv").write_bytes(b"a")
(films / "b.mkv").write_bytes(b"b")
idx = await _indexer(_roots(films))
(films / "a.mkv").unlink()
await idx.reconcile()
assert _names(idx) == {"b.mkv"}
async def test_reconcile_picks_up_a_file_the_watcher_missed(tmp_path):
"""
`ReadDirectoryChangesW` drops events under load and inotify on a FUSE mount
misses changes made outside it. Both are the common case here, so the sweep
is the only thing that recovers.
"""
films = tmp_path / "Films"
films.mkdir()
idx = await _indexer(_roots(films))
(films / "late.mkv").write_bytes(b"x") # no event delivered
await idx.reconcile()
assert _names(idx) == {"late.mkv"}
async def test_a_returning_root_is_rescanned(tmp_path):
films = tmp_path / "Films"
films.mkdir()
(films / "a.mkv").write_bytes(b"a")
idx = await _indexer(_roots(films))
(films / "a.mkv").unlink()
films.rmdir()
await idx.reconcile()
assert _names(idx) == {"a.mkv"} # frozen
films.mkdir()
(films / "a.mkv").write_bytes(b"a")
(films / "c.mkv").write_bytes(b"c")
await idx.reconcile()
assert _names(idx) == {"a.mkv", "c.mkv"}
assert idx.roots.roots[0].available is True
async def test_a_root_absent_at_startup_is_not_an_error(tmp_path):
"""
Someone starts the node with the drive unplugged. The group still exists and
the other roots still serve; this one fills in when it returns.
"""
films = tmp_path / "Films"
music = tmp_path / "Music"
films.mkdir()
music.mkdir()
(films / "a.mkv").write_bytes(b"a")
roots = _roots(films, music)
music.rmdir()
idx = await _indexer(roots)
assert _names(idx) == {"a.mkv"}
assert {r.name: r.available for r in idx.roots} == {"Films": True, "Music": False}
# ── Paths carry their root ───────────────────────────────────────────────────
async def test_every_path_starts_with_its_root_name(tmp_path):
films = tmp_path / "Films"
(films / "2024").mkdir(parents=True)
(films / "top.mkv").write_bytes(b"t")
(films / "2024" / "deep.mkv").write_bytes(b"d")
idx = await _indexer(_roots(films))
by_name = {e.name: e.path for e in idx.index.entries}
assert by_name == {"top.mkv": "Films", "deep.mkv": "Films/2024"}
async def test_a_single_root_group_is_not_a_special_case(tmp_path):
"""One path shape has to be got right once; two have to be kept right
forever. A lone root prefixes exactly like any other."""
only = tmp_path / "Shared"
only.mkdir()
(only / "x.txt").write_bytes(b"x")
idx = await _indexer(_roots(only))
assert [e.path for e in idx.index.entries] == ["Shared"]
async def test_same_relative_path_in_two_roots_stays_distinct(tmp_path):
films = tmp_path / "Films"
music = tmp_path / "Music"
(films / "2024").mkdir(parents=True)
(music / "2024").mkdir(parents=True)
(films / "2024" / "same.dat").write_bytes(b"film")
(music / "2024" / "same.dat").write_bytes(b"music")
idx = await _indexer(_roots(films, music))
paths = sorted(e.path for e in idx.index.entries)
assert paths == ["Films/2024", "Music/2024"]
assert len(idx.index.entries) == 2
# ── Duplicate content ────────────────────────────────────────────────────────
async def test_identical_files_do_not_churn_the_index(tmp_path):
"""
The index is keyed by content hash, so the same bytes at two paths are one
entry. Reconciliation compares paths, so without care it decides the second
path is a missed event **every cycle** — rewriting that entry, bumping the
version, and pushing an index update to every connected peer once a minute.
Found on a live node: `clip.mp4` sat at the root of a shared directory and
in `uploads/` with identical bytes.
"""
films = tmp_path / "Films"
(films / "uploads").mkdir(parents=True)
(films / "clip.mp4").write_bytes(b"same bytes")
(films / "uploads" / "clip.mp4").write_bytes(b"same bytes")
idx = await _indexer(_roots(films))
assert len(idx.index.entries) == 1, "content-addressed index, so one entry"
await idx.reconcile()
first = (idx.index.version, idx.index.entries[0].path)
await idx.reconcile()
second = (idx.index.version, idx.index.entries[0].path)
assert first == second, (
"reconciliation rewrote the entry for a duplicate it cannot represent — "
"every peer would receive an index update every cycle")
async def test_deleting_one_copy_keeps_the_other_listed(tmp_path):
"""
The mirror case: the recorded path goes, identical content stays. Dropping
the entry would delist a file that is still on disk and still servable.
"""
films = tmp_path / "Films"
(films / "uploads").mkdir(parents=True)
(films / "clip.mp4").write_bytes(b"same bytes")
(films / "uploads" / "clip.mp4").write_bytes(b"same bytes")
idx = await _indexer(_roots(films))
recorded = idx.index.entries[0].path
survivor = "Films/uploads" if recorded == "Films" else "Films"
(films / "clip.mp4").unlink() if recorded == "Films" else \
(films / "uploads" / "clip.mp4").unlink()
await idx.reconcile()
assert len(idx.index.entries) == 1, "the surviving copy was delisted"
assert idx.index.entries[0].path == survivor
# ── A directory that leaves the root ─────────────────────────────────────────
#
# Moving a folder out of the root arrives from the watcher as one "directory
# deleted" event, with nothing for the files it held. Found live: a season moved
# out of a shared folder stayed listed, every episode "File not on disk", until
# the reconcile backstop came round. These are the same freeze rules as above,
# applied to that event.
def _season(root: Path, name: str, *episodes: str) -> Path:
d = root / "Show" / name
d.mkdir(parents=True)
for ep in episodes:
(d / ep).write_bytes(ep.encode())
return d
async def test_a_directory_moved_out_of_a_live_root_is_removed(tmp_path):
shows = tmp_path / "Shows"
low = _season(shows, "S3.LQ", "e1.mp4", "e2.mp4")
_season(shows, "S3", "e1.hd.mkv")
idx = await _indexer(_roots(shows))
low.rename(tmp_path / "S3.LQ")
await idx._update_entry(low, deleted=True, directory=True)
# S3 shares a prefix with S3.LQ and must survive it.
assert _names(idx) == {"e1.hd.mkv"}
async def test_a_directory_event_from_a_vanished_root_freezes(tmp_path):
shows = tmp_path / "Shows"
season = _season(shows, "S1", "e1.mp4", "e2.mp4")
idx = await _indexer(_roots(shows))
os.rename(shows, tmp_path / "elsewhere")
await idx._update_entry(season, deleted=True, directory=True)
assert _names(idx) == {"e1.mp4", "e2.mp4"}
assert idx.roots.roots[0].available is False
async def test_a_directory_whose_parent_is_gone_waits_for_the_parent(tmp_path):
"""The parent going too is what a volume vanishing looks like below the
root. The parent's own event, when it comes, is the one that acts."""
shows = tmp_path / "Shows"
season = _season(shows, "S1", "e1.mp4")
_season(shows, "S2", "e2.mp4")
idx = await _indexer(_roots(shows))
os.rename(shows / "Show", tmp_path / "Show")
await idx._update_entry(season, deleted=True, directory=True)
assert _names(idx) == {"e1.mp4", "e2.mp4"}
await idx._update_entry(shows / "Show", deleted=True, directory=True)
assert _names(idx) == set()
async def test_a_directory_that_is_back_is_left_alone(tmp_path):
shows = tmp_path / "Shows"
season = _season(shows, "S1", "e1.mp4")
idx = await _indexer(_roots(shows))
# Moved out and back within the debounce: the event is stale.
await idx._update_entry(season, deleted=True, directory=True)
assert _names(idx) == {"e1.mp4"}
async def test_the_root_itself_is_never_removed_as_a_directory(tmp_path):
shows = tmp_path / "Shows"
_season(shows, "S1", "e1.mp4")
idx = await _indexer(_roots(shows))
await idx._update_entry(shows, deleted=True, directory=True)
assert _names(idx) == {"e1.mp4"}
async def test_the_watcher_reports_a_directory_moved_out(tmp_path):
"""End to end, with the real observer: the event is the one watchdog emits."""
shows = tmp_path / "Shows"
low = _season(shows, "S3.LQ", "e1.mp4")
_season(shows, "S3", "e1.hd.mkv")
idx = DirectoryIndexer(roots=_roots(shows), group_id="g" * 32,
sk_node=Ed25519PrivateKey.generate(), gek=None,
debounce_secs=0.05)
await idx.start()
try:
low.rename(tmp_path / "S3.LQ")
for _ in range(100):
if _names(idx) == {"e1.hd.mkv"}:
break
await asyncio.sleep(0.05)
assert _names(idx) == {"e1.hd.mkv"}
finally:
await idx.stop()
|