irsync 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
irsync/diff.py ADDED
@@ -0,0 +1,434 @@
1
+ """Diff two inode snapshots to recover the move/rename plan that produced the change."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import secrets
7
+ from collections.abc import Callable, Iterable
8
+ from dataclasses import dataclass, field
9
+ from pathlib import PurePosixPath
10
+ from typing import TypedDict
11
+
12
+ from irsync.snapshot import Row
13
+
14
+ _PathSubst = Callable[[str], str]
15
+
16
+
17
+ class NodeInfo(TypedDict):
18
+ """Aggregated info for a single inode (which may have multiple paths via hardlinks)."""
19
+
20
+ type: str
21
+ nlink: int
22
+ size: int
23
+ mtime_ns: int
24
+ btime_ns: int
25
+ paths: set[str]
26
+
27
+
28
+ def index_by_inode(rows: Iterable[Row]) -> dict[tuple[int, int], NodeInfo]:
29
+ """Group ``rows`` by ``(dev, ino)``, collecting all paths per inode.
30
+
31
+ Args:
32
+ rows: Snapshot rows from :func:`irsync.snapshot.snapshot_tree`.
33
+
34
+ Returns:
35
+ A dict mapping ``(dev, ino)`` to a :class:`NodeInfo` aggregate.
36
+ """
37
+ idx: dict[tuple[int, int], NodeInfo] = {}
38
+ for r in rows:
39
+ key = (r["dev"], r["ino"])
40
+ if key not in idx:
41
+ idx[key] = NodeInfo(
42
+ type=r["type"],
43
+ nlink=r["nlink"],
44
+ size=r["size"],
45
+ mtime_ns=r.get("mtime_ns", -1),
46
+ btime_ns=r.get("btime_ns", -1),
47
+ paths=set(),
48
+ )
49
+ idx[key]["paths"].add(r["path"])
50
+ return idx
51
+
52
+
53
+ def normalize_dir_pairs(
54
+ dir_moves: list[tuple[str, str]],
55
+ ) -> list[tuple[PurePosixPath, PurePosixPath]]:
56
+ """Convert ``(old, new)`` string pairs to :class:`PurePosixPath`, sorted deepest-first."""
57
+ pairs = [(PurePosixPath(o), PurePosixPath(n)) for o, n in dir_moves]
58
+ pairs.sort(key=lambda p: len(p[0].parts), reverse=True)
59
+ return pairs
60
+
61
+
62
+ def make_parent_substituter(
63
+ dir_moves: list[tuple[str, str]],
64
+ ) -> _PathSubst:
65
+ """Build a fast substituter that rewrites a path as if all ``dir_moves`` had been applied.
66
+
67
+ Args:
68
+ dir_moves: List of ``(old_dir, new_dir)`` pairs.
69
+
70
+ Returns:
71
+ A callable that maps a POSIX-relative path to its rewritten form.
72
+ """
73
+ if not dir_moves:
74
+ return _identity_subst
75
+ pairs = normalize_dir_pairs(dir_moves)
76
+
77
+ def subst(p: str) -> str:
78
+ pp = PurePosixPath(p)
79
+ for old_d, new_d in pairs:
80
+ if pp == old_d:
81
+ return new_d.as_posix()
82
+ if old_d in pp.parents:
83
+ rel = pp.relative_to(old_d)
84
+ return (new_d / rel).as_posix()
85
+ return p
86
+
87
+ return subst
88
+
89
+
90
+ def _identity_subst(p: str) -> str:
91
+ return p
92
+
93
+
94
+ def _suppress_file_moves_covered_by_dirs(
95
+ dir_moves: list[tuple[str, str]],
96
+ file_moves: list[tuple[str, str]],
97
+ ) -> list[tuple[str, str]]:
98
+ """Drop file moves that are already implied by an enclosing directory move."""
99
+ if not dir_moves:
100
+ return file_moves
101
+ subst = make_parent_substituter(dir_moves)
102
+ return [(o, n) for (o, n) in file_moves if subst(o) != n]
103
+
104
+
105
+ def prune_redundant_dir_moves(
106
+ dir_moves: list[tuple[str, str]],
107
+ ) -> list[tuple[str, str]]:
108
+ """Keep only top-level dir moves; drop child moves covered by an ancestor move."""
109
+ kept: list[tuple[str, str]] = []
110
+ for o, n in sorted(dir_moves, key=lambda p: len(PurePosixPath(p[0]).parts)):
111
+ if kept:
112
+ subst = make_parent_substituter(kept)
113
+ if subst(o) == n:
114
+ continue
115
+ kept.append((o, n))
116
+ return kept
117
+
118
+
119
+ def compute_moves(
120
+ before: dict[tuple[int, int], NodeInfo],
121
+ after: dict[tuple[int, int], NodeInfo],
122
+ *,
123
+ skip_hardlinks: bool = True,
124
+ include_symlinks: bool = False,
125
+ ) -> tuple[list[tuple[str, str]], list[tuple[str, str]], set[tuple[int, int]]]:
126
+ """Compare two inode indices and return ``(dir_moves, file_moves, consumed_keys)``.
127
+
128
+ ``consumed_keys`` is the set of ``(dev, ino)`` pairs that were turned into
129
+ moves; :func:`compute_changes` uses it to figure out which shared inodes
130
+ still need to be reflected as deleted/created/modified in the diff.
131
+
132
+ Args:
133
+ before: Inode index of the source tree at the time of the previous snapshot.
134
+ after: Inode index of the source tree now.
135
+ skip_hardlinks: If True, ignore inodes with multiple links on either side.
136
+ include_symlinks: If True, include symlinks in the comparison.
137
+
138
+ Returns:
139
+ ``(dir_moves, file_moves, consumed_keys)``.
140
+ """
141
+ dir_moves: list[tuple[str, str]] = []
142
+ file_moves: list[tuple[str, str]] = []
143
+ consumed: set[tuple[int, int]] = set()
144
+
145
+ shared = set(before.keys()).intersection(after.keys())
146
+ for key in shared:
147
+ b = before[key]
148
+ a = after[key]
149
+
150
+ if b["type"] == "l" and not include_symlinks:
151
+ continue
152
+ if b["type"] == "o":
153
+ continue
154
+ if b["type"] != a["type"]:
155
+ logging.warning(
156
+ "Type change for inode %s: %s -> %s; ignoring",
157
+ key,
158
+ b["type"],
159
+ a["type"],
160
+ )
161
+ continue
162
+
163
+ bpaths = b["paths"]
164
+ apaths = a["paths"]
165
+
166
+ if bpaths == apaths:
167
+ continue
168
+
169
+ if skip_hardlinks and (len(bpaths) != 1 or len(apaths) != 1):
170
+ logging.debug(
171
+ "Skipping inode with multiple links: %s -> %s",
172
+ sorted(bpaths),
173
+ sorted(apaths),
174
+ )
175
+ continue
176
+
177
+ if len(bpaths) == 1 and len(apaths) == 1:
178
+ (old_path,) = tuple(bpaths)
179
+ (new_path,) = tuple(apaths)
180
+ # Defend against inode reuse: a kernel that hands out a freed
181
+ # inode number to a brand-new file would otherwise look identical
182
+ # to a rename. The size+mtime_ns gate (H2 from pass 2) catches
183
+ # this on filesystems with nanosecond-precision mtime.
184
+ #
185
+ # The btime_ns tiebreaker (replacing the broken 5th-pass ctime
186
+ # attempt) closes the residual NFS hole: on second-granular FSes
187
+ # it's possible for an unrelated new file to land at the same
188
+ # inode with the same wall-clock-second mtime AND the same size.
189
+ # btime is set when the inode is allocated and never changes
190
+ # afterward, so a real rename preserves it while inode reuse
191
+ # always changes it. We only require btime to match WHEN both
192
+ # snapshots have it (>= 0); when either side reports -1 (statx
193
+ # unavailable, FS without btime support, or legacy snapshot),
194
+ # we fall back to the original size+mtime gate alone.
195
+ #
196
+ # mtime_ns == -1 sentinel (legacy snapshot pre-H2) still forces
197
+ # a conservative refuse-the-move — safe fallback, rsync re-
198
+ # transfers.
199
+ both_have_btime = b["btime_ns"] >= 0 and a["btime_ns"] >= 0
200
+ if (
201
+ b["mtime_ns"] == -1
202
+ or a["mtime_ns"] == -1
203
+ or b["size"] != a["size"]
204
+ or b["mtime_ns"] != a["mtime_ns"]
205
+ or (both_have_btime and b["btime_ns"] != a["btime_ns"])
206
+ ):
207
+ logging.debug(
208
+ "Inode %s path changed but size/mtime differ "
209
+ "(possible inode reuse); not treating as a move: %s -> %s",
210
+ key,
211
+ old_path,
212
+ new_path,
213
+ )
214
+ continue
215
+ if b["type"] == "d":
216
+ dir_moves.append((old_path, new_path))
217
+ else:
218
+ file_moves.append((old_path, new_path))
219
+ consumed.add(key)
220
+ else:
221
+ logging.debug(
222
+ "Complex hardlink mapping ignored: %s -> %s",
223
+ sorted(bpaths),
224
+ sorted(apaths),
225
+ )
226
+
227
+ dir_moves = sorted({(o, n) for (o, n) in dir_moves if o != n})
228
+ file_moves = sorted({(o, n) for (o, n) in file_moves if o != n})
229
+ return dir_moves, file_moves, consumed
230
+
231
+
232
+ def plan_directory_moves(dir_moves: list[tuple[str, str]]) -> list[tuple[str, str]]:
233
+ """Order directory moves so cycles are broken via temp paths.
234
+
235
+ Args:
236
+ dir_moves: List of ``(old, new)`` directory pairs.
237
+
238
+ Returns:
239
+ Ordered list of ``(src, dst)`` moves (possibly via intermediate temp paths)
240
+ that can be executed sequentially without clobbering.
241
+ """
242
+ if not dir_moves:
243
+ return []
244
+
245
+ move_map: dict[str, str] = {o: n for o, n in dir_moves}
246
+ old_set = set(move_map.keys())
247
+ sorted_old_set = sorted(old_set, key=lambda s: (len(PurePosixPath(s).parts), s))
248
+ color: dict[str, int] = {o: 0 for o in old_set}
249
+ temp_moves: list[tuple[str, str, str]] = []
250
+
251
+ def temp_name_for(p: str) -> str:
252
+ # Use a random suffix so a real file at the same path on the destination
253
+ # tree (e.g. a backup of in-progress work whose author happened to use
254
+ # this exact suffix) won't collide with a cycle-breaking temp move.
255
+ # 8 hex chars = 32 bits of entropy; collision probability vanishes.
256
+ while True:
257
+ candidate = f"{p}.__mvtmp__{secrets.token_hex(4)}"
258
+ if candidate not in old_set and candidate not in move_map.values():
259
+ return candidate
260
+
261
+ def dfs(u: str) -> None:
262
+ color[u] = 1
263
+ v = move_map[u]
264
+ if v in old_set:
265
+ if color.get(v, 0) == 0:
266
+ dfs(v)
267
+ elif color.get(v, 0) == 1:
268
+ tmp = temp_name_for(v)
269
+ final = move_map[v]
270
+ temp_moves.append((v, tmp, final))
271
+ move_map[v] = tmp
272
+ color[u] = 2
273
+
274
+ for o in sorted_old_set:
275
+ if color[o] == 0:
276
+ dfs(o)
277
+
278
+ ordered: list[tuple[str, str]] = []
279
+ visited: set[str] = set()
280
+
281
+ for start in sorted_old_set:
282
+ if start in visited:
283
+ continue
284
+ chain: list[str] = []
285
+ u = start
286
+ while u in move_map and u not in visited:
287
+ chain.append(u)
288
+ visited.add(u)
289
+ v = move_map[u]
290
+ if v in old_set and v not in visited:
291
+ u = v
292
+ else:
293
+ # Either the chain reached a non-old-set tail or a node we've
294
+ # already scheduled. Either way we stop walking.
295
+ break
296
+ for src in reversed(chain):
297
+ ordered.append((src, move_map[src]))
298
+
299
+ for _chosen, tmp, final in temp_moves:
300
+ ordered.append((tmp, final))
301
+
302
+ seen: set[tuple[str, str]] = set()
303
+ unique_ordered: list[tuple[str, str]] = []
304
+ for m in ordered:
305
+ if m not in seen and m[0] != m[1]:
306
+ seen.add(m)
307
+ unique_ordered.append(m)
308
+ return unique_ordered
309
+
310
+
311
+ @dataclass(frozen=True)
312
+ class Changes:
313
+ """The full delta between two snapshots: moves, modifications, creations, deletions."""
314
+
315
+ dir_moves: list[tuple[str, str]] = field(default_factory=list)
316
+ file_moves: list[tuple[str, str]] = field(default_factory=list)
317
+ modified: list[str] = field(default_factory=list)
318
+ created: list[str] = field(default_factory=list)
319
+ deleted: list[str] = field(default_factory=list)
320
+
321
+ def any_changes(self) -> bool:
322
+ """Return True if any moves, modifications, creations, or deletions are present."""
323
+ return bool(
324
+ self.dir_moves
325
+ or self.file_moves
326
+ or self.modified
327
+ or self.created
328
+ or self.deleted
329
+ )
330
+
331
+
332
+ def compute_changes(
333
+ before_rows: Iterable[Row],
334
+ after_rows: Iterable[Row],
335
+ *,
336
+ skip_hardlinks: bool = True,
337
+ include_symlinks: bool = False,
338
+ ) -> Changes:
339
+ """High-level diff: produce moves, prune redundant dir moves, and list created/deleted.
340
+
341
+ Args:
342
+ before_rows: Snapshot rows from the previous run.
343
+ after_rows: Snapshot rows from the current run.
344
+ skip_hardlinks: Forwarded to :func:`compute_moves`.
345
+ include_symlinks: Forwarded to :func:`compute_moves`.
346
+
347
+ Returns:
348
+ A :class:`Changes` aggregate ready for the orchestrator to act on.
349
+ """
350
+ before = index_by_inode(before_rows)
351
+ after = index_by_inode(after_rows)
352
+
353
+ dir_moves, file_moves, consumed_keys = compute_moves(
354
+ before, after, skip_hardlinks=skip_hardlinks, include_symlinks=include_symlinks
355
+ )
356
+ dir_moves = prune_redundant_dir_moves(dir_moves)
357
+ file_moves = _suppress_file_moves_covered_by_dirs(dir_moves, file_moves)
358
+
359
+ before_keys = set(before.keys())
360
+ after_keys = set(after.keys())
361
+ # Include every snapshotted inode type so brand-new and removed
362
+ # entries fire any_changes() and land in the rsync preview. Without
363
+ # "l" here (7th-NEW-H1), ln -s of a fresh link silently
364
+ # short-circuited the backup. Without "o" here (8th-M2), the same
365
+ # silent-skip pattern was latent for sockets / FIFOs / devices when
366
+ # include_other=True. Anything that snapshot_tree records belongs
367
+ # in the diff so rsync handles it.
368
+ deleted_paths = [
369
+ p
370
+ for k, e in before.items()
371
+ if k not in after_keys and e["type"] in ("d", "f", "l", "o")
372
+ for p in e["paths"]
373
+ ]
374
+ created_paths = [
375
+ p
376
+ for k, e in after.items()
377
+ if k not in before_keys and e["type"] in ("d", "f", "l", "o")
378
+ for p in e["paths"]
379
+ ]
380
+
381
+ # Inodes that exist in BOTH snapshots but weren't consumed by a move.
382
+ # This block closes the rename-and-edit invisibility (NEW-H3) plus the
383
+ # symlink/hardlink/type-change variants (NEW-H4): when compute_moves
384
+ # declines an inode for any reason, the inode's path-set difference
385
+ # still represents real changes the dest must reflect.
386
+ # - paths only in before → add to deleted (rsync removes from dest)
387
+ # - paths only in after → add to created (rsync transfers to dest)
388
+ # - paths in both with size/mtime change → add to modified (rsync
389
+ # re-transfers content). Skipped for directories, whose mtime ticks
390
+ # for any child-level change already reported elsewhere.
391
+ modified_paths: list[str] = []
392
+ for key in (before_keys & after_keys) - consumed_keys:
393
+ b = before[key]
394
+ a = after[key]
395
+ only_in_before = b["paths"] - a["paths"]
396
+ only_in_after = a["paths"] - b["paths"]
397
+ shared_paths = b["paths"] & a["paths"]
398
+ deleted_paths.extend(only_in_before)
399
+ created_paths.extend(only_in_after)
400
+ if shared_paths and b["type"] != a["type"]:
401
+ # 8th-pass defensive fix: NEW-H4 type-change at the SAME
402
+ # inode + path is physically impossible (changing inode
403
+ # type requires unlink+creat which gets a new inode), but
404
+ # compute_moves' defensive `continue` left the shared-loop
405
+ # to handle the case — and the modification gate below
406
+ # was skipping it whenever either side was a directory,
407
+ # leaving the path invisible. Force it through both
408
+ # deleted (under old type) and created (under new type)
409
+ # so rsync re-syncs it.
410
+ deleted_paths.extend(shared_paths)
411
+ created_paths.extend(shared_paths)
412
+ elif (
413
+ shared_paths
414
+ and b["type"] != "d"
415
+ and a["type"] != "d"
416
+ and (
417
+ b["size"] != a["size"]
418
+ or b["mtime_ns"] == -1
419
+ or a["mtime_ns"] == -1
420
+ or b["mtime_ns"] != a["mtime_ns"]
421
+ )
422
+ ):
423
+ modified_paths.extend(shared_paths)
424
+ deleted_paths = sorted(set(deleted_paths))
425
+ created_paths = sorted(set(created_paths))
426
+ modified_paths = sorted(set(modified_paths))
427
+
428
+ return Changes(
429
+ dir_moves=dir_moves,
430
+ file_moves=file_moves,
431
+ modified=modified_paths,
432
+ created=created_paths,
433
+ deleted=deleted_paths,
434
+ )