]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - docs/proposed/magic-folder/remote-to-local-sync.rst
remote-to-local-sync.rst: fix an inconsistency in the representation option table.
[tahoe-lafs/tahoe-lafs.git] / docs / proposed / magic-folder / remote-to-local-sync.rst
1 Magic Folder design for remote-to-local sync
2 ============================================
3
4 Scope
5 -----
6
7 In this Objective we will design remote-to-local synchronization:
8
9 * How to efficiently determine which objects (files and directories) have
10   to be downloaded in order to bring the current local filesystem into sync
11   with the newly-discovered version of the remote filesystem.
12 * How to distinguish overwrites, in which the remote side was aware of
13   your most recent version and overwrote it with a new version, from
14   conflicts, in which the remote side was unaware of your most recent
15   version when it published its new version. The latter needs to be raised
16   to the user as an issue the user will have to resolve and the former must
17   not bother the user.
18 * How to overwrite the (stale) local versions of those objects with the
19   newly acquired objects, while preserving backed-up versions of those
20   overwritten objects in case the user didn't want this overwrite and wants
21   to recover the old version.
22
23 Tickets on the Tahoe-LAFS trac with the `otf-magic-folder-objective4`_
24 keyword are within the scope of the remote-to-local synchronization
25 design.
26
27 .. _otf-magic-folder-objective4: https://tahoe-lafs.org/trac/tahoe-lafs/query?status=!closed&keywords=~otf-magic-folder-objective4
28
29
30 Glossary
31 ''''''''
32
33 Object: a file or directory
34
35 DMD: distributed mutable directory
36
37 Folder: an abstract directory that is synchronized between clients.
38 (A folder is not the same as the directory corresponding to it on
39 any particular client, nor is it the same as a DMD.)
40
41 Collective: the set of clients subscribed to a given Magic Folder.
42
43 Descendant: a direct or indirect child in a directory or folder tree
44
45 Subfolder: a folder that is a descendant of a magic folder
46
47 Subpath: the path from a magic folder to one of its descendants
48
49 Write: a modification to a local filesystem object by a client
50
51 Read: a read from a local filesystem object by a client
52
53 Upload: an upload of a local object to the Tahoe-LAFS file store
54
55 Download: a download from the Tahoe-LAFS file store to a local object
56
57 Pending notification: a local filesystem change that has been detected
58 but not yet processed.
59
60
61 Representing the Magic Folder in Tahoe-LAFS
62 -------------------------------------------
63
64 Unlike the local case where we use inotify or ReadDirectoryChangesW to
65 detect filesystem changes, we have no mechanism to register a monitor for
66 changes to a Tahoe-LAFS directory. Therefore, we must periodically poll
67 for changes.
68
69 An important constraint on the solution is Tahoe-LAFS' "`write
70 coordination directive`_", which prohibits concurrent writes by different
71 storage clients to the same mutable object:
72
73     Tahoe does not provide locking of mutable files and directories. If
74     there is more than one simultaneous attempt to change a mutable file
75     or directory, then an UncoordinatedWriteError may result. This might,
76     in rare cases, cause the file or directory contents to be accidentally
77     deleted.  The user is expected to ensure that there is at most one
78     outstanding write or update request for a given file or directory at
79     a time.  One convenient way to accomplish this is to make a different
80     file or directory for each person or process that wants to write.
81
82 .. _`write coordination directive`: ../../write_coordination.rst
83
84 Since it is a goal to allow multiple users to write to a Magic Folder,
85 if the write coordination directive remains the same as above, then we
86 will not be able to implement the Magic Folder as a single Tahoe-LAFS
87 DMD. In general therefore, we will have multiple DMDs —spread across
88 clients— that together represent the Magic Folder. Each client in a
89 Magic Folder collective polls the other clients' DMDs in order to detect
90 remote changes.
91
92 Six possible designs were considered for the representation of subfolders
93 of the Magic Folder:
94
95 1. All subfolders written by a given Magic Folder client are collapsed
96 into a single client DMD, containing immutable files. The child name of
97 each file encodes the full subpath of that file relative to the Magic
98 Folder.
99
100 2. The DMD tree under a client DMD is a direct copy of the folder tree
101 written by that client to the Magic Folder. Not all subfolders have
102 corresponding DMDs; only those to which that client has written files or
103 child subfolders.
104
105 3. The directory tree under a client DMD is a ``tahoe backup`` structure
106 containing immutable snapshots of the folder tree written by that client
107 to the Magic Folder. As in design 2, only objects written by that client
108 are present.
109
110 4. *Each* client DMD contains an eventually consistent mirror of all
111 files and folders written by *any* Magic Folder client. Thus each client
112 must also copy changes made by other Magic Folder clients to its own
113 client DMD.
114
115 5. *Each* client DMD contains a ``tahoe backup`` structure containing
116 immutable snapshots of all files and folders written by *any* Magic
117 Folder client. Thus each client must also create another snapshot in its
118 own client DMD when changes are made by another client. (It can potentially
119 batch changes, subject to latency requirements.)
120
121 6. The write coordination problem is solved by implementing `two-phase
122 commit`_. Then, the representation consists of a single DMD tree which is
123 written by all clients.
124
125 .. _`two-phase commit`: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1755
126
127 Here is a summary of advantages and disadvantages of each design:
128
129 +----------------------------+
130 | Key                        |
131 +=======+====================+
132 | \+\+  | major advantage    |
133 +-------+--------------------+
134 | \+    | minor advantage    |
135 +-------+--------------------+
136 | ‒     | minor disadvantage |
137 +-------+--------------------+
138 | ‒ ‒   | major disadvantage |
139 +-------+--------------------+
140 | ‒ ‒ ‒ | showstopper        |
141 +-------+--------------------+
142
143
144 123456+: All designs have the property that a recursive add-lease
145 operation starting from a *collective directory* containing all of
146 the client DMDs, will find all of the files and directories used in
147 the Magic Folder representation. Therefore the representation is
148 compatible with `garbage collection`_, even when a pre-Magic-Folder
149 client does the lease marking.
150
151 .. _`garbage collection`: https://tahoe-lafs.org/trac/tahoe-lafs/browser/trunk/docs/garbage-collection.rst
152
153 123456+: All designs avoid "breaking" pre-Magic-Folder clients that read
154 a directory or file that is part of the representation.
155
156 456++: Only these designs allow a readcap to one of the client
157 directories —or one of their subdirectories— to be directly shared
158 with other Tahoe-LAFS clients (not necessarily Magic Folder clients),
159 so that such a client sees all of the contents of the Magic Folder.
160 Note that this was not a requirement of the OTF proposal, although it
161 is useful.
162
163 135+: A Magic Folder client has only one mutable Tahoe-LAFS object to
164 monitor per other client. This minimizes communication bandwidth for
165 polling, or alternatively the latency possible for a given polling
166 bandwidth.
167
168 1236+: A client does not need to make changes to its own DMD that repeat
169 changes that another Magic Folder client had previously made. This reduces
170 write bandwidth and complexity.
171
172 1‒: If the Magic Folder has many subfolders, their files will all be
173 collapsed into the same DMD, which could get quite large. In practice a
174 single DMD can easily handle the number of files expected to be written
175 by a client, so this is unlikely to be a significant issue.
176
177 123‒ ‒: In these designs, the set of files in a Magic Folder is
178 represented as the union of the files in all client DMDs. However,
179 when a file is modified by more than one client, it will be linked
180 from multiple client DMDs. We therefore need a mechanism, such as a
181 version number or a monotonically increasing timestamp, to determine
182 which copy takes priority.
183
184 35‒ ‒: When a Magic Folder client detects a remote change, it must
185 traverse an immutable directory structure to see what has changed.
186 Completely unchanged subtrees will have the same URI, allowing some of
187 this traversal to be shortcutted.
188
189 24‒ ‒ ‒: When a Magic Folder client detects a remote change, it must
190 traverse a mutable directory structure to see what has changed. This is
191 more complex and less efficient than traversing an immutable structure,
192 because shortcutting is not possible (each DMD retains the same URI even
193 if a descendant object has changed), and because the structure may change
194 while it is being traversed. Also the traversal needs to be robust
195 against cycles, which can only occur in mutable structures.
196
197 45‒ ‒: When a change occurs in one Magic Folder client, it will propagate
198 to all the other clients. Each client will therefore see multiple
199 representation changes for a single logical change to the Magic Folder
200 contents, and must suppress the duplicates. This is particularly
201 problematic for design 4 where it interacts with the preceding issue.
202
203 4‒ ‒ ‒, 5‒ ‒: There is the potential for client DMDs to get "out of sync"
204 with each other, potentially for long periods if errors occur. Thus each
205 client must be able to "repair" its client directory (and its
206 subdirectory structure) concurrently with performing its own writes. This
207 is a significant complexity burden and may introduce failure modes that
208 could not otherwise happen.
209
210 6‒ ‒ ‒: While two-phase commit is a well-established protocol, its
211 application to Tahoe-LAFS requires significant design work, and may still
212 leave some corner cases of the write coordination problem unsolved.
213
214
215 +------------------------------------------------+-----------------------------------------+
216 | Design Property                                | Designs Proposed                        |
217 +================================================+======+======+======+======+======+======+
218 | **advantages**                                 | *1*  | *2*  | *3*  | *4*  | *5*  | *6*  |
219 +------------------------------------------------+------+------+------+------+------+------+
220 | Compatible with garbage collection             |\+    |\+    |\+    |\+    |\+    |\+    |
221 +------------------------------------------------+------+------+------+------+------+------+
222 | Does not break old clients                     |\+    |\+    |\+    |\+    |\+    |\+    |
223 +------------------------------------------------+------+------+------+------+------+------+
224 | Allows direct sharing                          |      |      |      |\+\+  |\+\+  |\+\+  |
225 +------------------------------------------------+------+------+------+------+------+------+
226 | Efficient use of bandwidth                     |\+    |      |\+    |      |\+    |      |
227 +------------------------------------------------+------+------+------+------+------+------+
228 | No repeated changes                            |\+    |\+    |\+    |      |      |\+    |
229 +------------------------------------------------+------+------+------+------+------+------+
230 | **disadvantages**                              | *1*  | *2*  | *3*  | *4*  | *5*  | *6*  |
231 +------------------------------------------------+------+------+------+------+------+------+
232 | Can result in large DMDs                       |‒     |      |      |      |      |      |
233 +------------------------------------------------+------+------+------+------+------+------+
234 | Need version number to determine priority      |‒ ‒   |‒ ‒   |‒ ‒   |      |      |      |
235 +------------------------------------------------+------+------+------+------+------+------+
236 | Must traverse immutable directory structure    |      |      |‒ ‒   |      |‒ ‒   |      |
237 +------------------------------------------------+------+------+------+------+------+------+
238 | Must traverse mutable directory structure      |      |‒ ‒   |      |‒ ‒   |      |      |
239 +------------------------------------------------+------+------+------+------+------+------+
240 | Must suppress duplicate representation changes |      |      |      |‒ ‒   |‒ ‒   |      |
241 +------------------------------------------------+------+------+------+------+------+------+
242 | "Out of sync" problem                          |      |      |      |‒ ‒ ‒ |‒ ‒   |      |
243 +------------------------------------------------+------+------+------+------+------+------+
244 | Unsolved design problems                       |      |      |      |      |      |‒ ‒ ‒ |
245 +------------------------------------------------+------+------+------+------+------+------+
246
247
248 Evaluation of designs
249 '''''''''''''''''''''
250
251 Designs 2 and 3 have no significant advantages over design 1, while
252 requiring higher polling bandwidth and greater complexity due to the need
253 to create subdirectories. These designs were therefore rejected.
254
255 Design 4 was rejected due to the out-of-sync problem, which is severe
256 and possibly unsolvable for mutable structures.
257
258 For design 5, the out-of-sync problem is still present but possibly
259 solvable. However, design 5 is substantially more complex, less efficient
260 in bandwidth/latency, and less scalable in number of clients and
261 subfolders than design 1. It only gains over design 1 on the ability to
262 share directory readcaps to the Magic Folder (or subfolders), which was
263 not a requirement. It would be possible to implement this feature in
264 future by switching to design 6.
265
266 For the time being, however, design 6 was considered out-of-scope for
267 this project.
268
269 Therefore, design 1 was chosen. That is:
270
271     All subfolders written by a given Magic Folder client are collapsed
272     into a single client DMD, containing immutable files. The child name
273     of each file encodes the full subpath of that file relative to the
274     Magic Folder.
275
276 Each directory entry in a DMD also stores a version number, so that the
277 latest version of a file is well-defined when it has been modified by
278 multiple clients.
279
280 To enable representing empty directories, a client that creates a
281 directory should link a corresponding zero-length file in its DMD,
282 at a name that ends with the encoded directory separator character.
283
284 We want to enable dynamic configuration of the membership of a Magic
285 Folder collective, without having to reconfigure or restart each client
286 when another client joins. To support this, we have a single collective
287 directory that links to all of the client DMDs, named by their client
288 nicknames. If the collective directory is mutable, then it is possible
289 to change its contents in order to add clients. Note that a client DMD
290 should not be unlinked from the collective directory unless all of its
291 files are first copied to some other client DMD.
292
293 A client needs to be able to write to its own DMD, and read from other DMDs.
294 To be consistent with the `Principle of Least Authority`_, each client's
295 reference to its own DMD is a write capability, whereas its reference
296 to the collective directory is a read capability. The latter transitively
297 grants read access to all of the other client DMDs and the files linked
298 from them, as required.
299
300 .. _`Principle of Least Authority`: http://www.eros-os.org/papers/secnotsep.pdf
301
302 Design and implementation of the user interface for maintaining this
303 DMD structure and configuration will be addressed in Objectives 5 and 6.
304
305 During operation, each client will poll for changes on other clients
306 at a predetermined frequency. On each poll, it will reread the collective
307 directory (to allow for added or removed clients), and then read each
308 client DMD linked from it.
309
310 "Hidden" files, and files with names matching the patterns used for backup,
311 temporary, and conflicted files, will be ignored, i.e. not synchronized
312 in either direction. A file is hidden if it has a filename beginning with
313 "." (on any platform), or has the hidden or system attribute on Windows.
314
315
316 Conflict Detection and Resolution
317 ---------------------------------
318
319 The combination of local filesystems and distributed objects is
320 an example of shared state concurrency, which is highly error-prone
321 and can result in race conditions that are complex to analyze.
322 Unfortunately we have no option but to use shared state in this
323 situation.
324
325 We call the resulting design issues "dragons" (as in "Here be dragons"),
326 which as a convenient mnemonic we have named after the classical
327 Greek elements Earth, Fire, Air, and Water.
328
329 Note: all filenames used in the following sections are examples,
330 and the filename patterns we use in the actual implementation may
331 differ. The actual patterns will probably include timestamps, and
332 for conflicted files, the nickname of the client that last changed
333 the file.
334
335
336 Earth Dragons: Collisions between local filesystem operations and downloads
337 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
338
339 Write/download collisions
340 ~~~~~~~~~~~~~~~~~~~~~~~~~
341
342 Suppose that Alice's Magic Folder client is about to write a
343 version of ``foo`` that it has downloaded in response to a remote
344 change.
345
346 The criteria for distinguishing overwrites from conflicts are
347 described later in the `Fire Dragons`_ section. Suppose that the
348 remote change has been initially classified as an overwrite.
349 (As we will see, it may be reclassified in some circumstances.)
350
351 .. _`Fire Dragons`: #fire-dragons-distinguishing-conflicts-from-overwrites
352
353 A *write/download collision* occurs when another program writes
354 to ``foo`` in the local filesystem, concurrently with the new
355 version being written by the Magic Folder client. We need to
356 ensure that this does not cause data loss, as far as possible.
357
358 An important constraint on the design is that on Windows, it is
359 not possible to rename a file to the same name as an existing
360 file in that directory. Also, on Windows it may not be possible to
361 delete or rename a file that has been opened by another process
362 (depending on the sharing flags specified by that process).
363 Therefore we need to consider carefully how to handle failure
364 conditions.
365
366 In our proposed design, Alice's Magic Folder client follows
367 this procedure for an overwrite in response to a remote change:
368
369 1. Write a temporary file, say ``.foo.tmp``.
370 2. Use the procedure described in the `Fire Dragons_` section
371    to obtain an initial classification as an overwrite or a
372    conflict. (This takes as input the ``last_downloaded_uri``
373    field from the directory entry of the changed ``foo``.)
374 3. Set the ``mtime`` of the replacement file to be *T* seconds
375    before the current local time.
376 4. Perform a ''file replacement'' operation (explained below)
377    with backup filename ``foo.backup``, replaced file ``foo``,
378    and replacement file ``.foo.tmp``. If any step of this
379    operation fails, reclassify as a conflict and stop.
380
381 To reclassify as a conflict, attempt to rename ``.foo.tmp`` to
382 ``foo.conflicted``, suppressing errors.
383
384 The implementation of file replacement differs between Unix
385 and Windows. On Unix, it can be implemented as follows:
386
387 * 4a. Set the permissions of the replacement file to be the
388   same as the replaced file, bitwise-or'd with octal 600
389   (``rw-------``).
390 * 4b. Attempt to move the replaced file (``foo``) to the
391   backup filename (``foo.backup``).
392 * 4c. Attempt to create a hard link at the replaced filename
393   (``foo``) pointing to the replacement file (``.foo.tmp``).
394 * 4d. Attempt to unlink the replacement file (``.foo.tmp``),
395   suppressing errors.
396
397 Note that, if there is no conflict, the entry for ``foo``
398 recorded in the `magic folder db`_ will reflect the ``mtime``
399 set in step 3. The move operation in step 4b will cause a
400 ``MOVED_FROM`` event for ``foo``, and the link operation in
401 step 4c will cause an ``IN_CREATE`` event for ``foo``.
402 However, these events will not trigger an upload, because they
403 are guaranteed to be processed only after the file replacement
404 has finished, at which point the metadata recorded in the
405 database entry will exactly match the metadata for the file's
406 inode on disk. (The two hard links — ``foo`` and,  while it
407 still exists, ``.foo.tmp`` — share the same inode and
408 therefore the same metadata.)
409
410 .. _`magic folder db`: filesystem_integration.rst#local-scanning-and-database
411
412 On Windows, file replacement can be implemented as a single
413 call to the `ReplaceFileW`_ API (with the
414 ``REPLACEFILE_IGNORE_MERGE_ERRORS`` flag).
415
416 Similar to the Unix case, the `ReplaceFileW`_ operation will
417 cause one or more change notifications for ``foo``. The replaced
418 ``foo`` has the same ``mtime`` as the replacement file, and so any
419 such notification(s) will not trigger an unwanted upload.
420
421 .. _`ReplaceFileW`: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365512%28v=vs.85%29.aspx
422
423 To determine whether this procedure adequately protects against data
424 loss, we need to consider what happens if another process attempts to
425 update ``foo``, for example by renaming ``foo.other`` to ``foo``.
426 This requires us to analyze all possible interleavings between the
427 operations performed by the Magic Folder client and the other process.
428 (Note that atomic operations on a directory are totally ordered.)
429 The set of possible interleavings differs between Windows and Unix.
430
431 On Unix, we have:
432
433 * Interleaving A: the other process' rename precedes our rename in
434   step 4b, and we get an ``IN_MOVED_TO`` event for its rename by
435   step 2. Then we reclassify as a conflict; its changes end up at
436   ``foo`` and ours end up at ``foo.conflicted``. This avoids data
437   loss.
438
439 * Interleaving B: its rename precedes ours in step 4b, and we do
440   not get an event for its rename by step 2. Its changes end up at
441   ``foo.backup``, and ours end up at ``foo`` after being linked there
442   in step 4c. This avoids data loss.
443
444 * Interleaving C: its rename happens between our rename in step 4b,
445   and our link operation in step 4c of the file replacement. The
446   latter fails with an ``EEXIST`` error because ``foo`` already
447   exists. We reclassify as a conflict; the old version ends up at
448   ``foo.backup``, the other process' changes end up at ``foo``, and
449   ours at ``foo.conflicted``. This avoids data loss.
450
451 * Interleaving D: its rename happens after our link in step 4c,
452   and causes an ``IN_MOVED_TO`` event for ``foo``. Its rename also
453   changes the ``mtime`` for ``foo`` so that it is different from
454   the ``mtime`` calculated in step 3, and therefore different
455   from the metadata recorded for ``foo`` in the magic folder db.
456   (Assuming no system clock changes, its rename will set an ``mtime``
457   timestamp corresponding to a time after step 4c, which is not
458   equal to the timestamp *T* seconds before step 4a, provided that
459   *T* seconds is sufficiently greater than the timestamp granularity.)
460   Therefore, an upload will be triggered for ``foo`` after its
461   change, which is correct and avoids data loss.
462
463 On Windows, the internal implementation of `ReplaceFileW`_ is similar
464 to what we have described above for Unix; it works like this:
465
466 * 4a′. Copy metadata (which does not include ``mtime``) from the
467   replaced file (``foo``) to the replacement file (``.foo.tmp``).
468
469 * 4b′. Attempt to move the replaced file (``foo``) onto the
470   backup filename (``foo.backup``), deleting the latter if it
471   already exists.
472
473 * 4c′. Attempt to move the replacement file (``.foo.tmp``) to the
474   replaced filename (``foo``); fail if the destination already
475   exists.
476
477 Notice that this is essentially the same as the algorithm we use
478 for Unix, but steps 4c and 4d on Unix are combined into a single
479 step 4c′. (If there is a failure at steps 4c′ after step 4b′ has
480 completed, the `ReplaceFileW`_ call will fail with return code
481 ``ERROR_UNABLE_TO_MOVE_REPLACEMENT_2``. However, it is still
482 preferable to use this API over two `MoveFileExW`_ calls, because
483 it retains the attributes and ACLs of ``foo`` where possible.)
484
485 However, on Windows the other application will not be able to
486 directly rename ``foo.other`` onto ``foo`` (which would fail because
487 the destination already exists); it will have to rename or delete
488 ``foo`` first. Without loss of generality, let's say ``foo`` is
489 deleted. This complicates the interleaving analysis, because we
490 have two operations done by the other process interleaving with
491 three done by the magic folder process (rather than one operation
492 interleaving with four as on Unix). The cases are:
493
494 * Interleaving A′: the other process' deletion of ``foo`` and its
495   rename of ``foo.other`` to ``foo`` both precede our rename in
496   step 4b. We get an event corresponding to its rename by step 2.
497   Then we reclassify as a conflict; its changes end up at ``foo``
498   and ours end up at ``foo.conflicted``. This avoids data loss.
499
500 * Interleaving B′: the other process' deletion of ``foo`` and its
501   rename of ``foo.other`` to ``foo`` both precede our rename in
502   step 4b. We do not get an event for its rename by step 2.
503   Its changes end up at ``foo.backup``, and ours end up at ``foo``
504   after being moved there in step 4c′. This avoids data loss.
505
506 * Interleaving C′: the other process' deletion of ``foo`` precedes
507   our rename of ``foo`` to ``foo.backup`` done by `ReplaceFileW`_,
508   but its rename of ``foo.other`` to ``foo`` does not, so we get
509   an ``ERROR_FILE_NOT_FOUND`` error from `ReplaceFileW`_ indicating
510   that the replaced file does not exist. Then we reclassify as a
511   conflict; the other process' changes end up at ``foo`` (after
512   it has renamed ``foo.other`` to ``foo``) and our changes end up
513   at ``foo.conflicted``. This avoids data loss.
514
515 * Interleaving D′: the other process' deletion and/or rename happen
516   during the call to `ReplaceFileW`_, causing the latter to fail.
517   There are two subcases:
518
519   * if the error is ``ERROR_UNABLE_TO_MOVE_REPLACEMENT_2``, then
520     ``foo`` is renamed to ``foo.backup`` and ``.foo.tmp`` remains
521     at its original name after the call.
522   * for all other errors, ``foo`` and ``.foo.tmp`` both remain at
523     their original names after the call.
524
525   In both subcases, we reclassify as a conflict and rename ``.foo.tmp``
526   to ``foo.conflicted``. This avoids data loss.
527
528 * Interleaving E′: the other process' deletion of ``foo`` and attempt
529   to rename ``foo.other`` to ``foo`` both happen after all internal
530   operations of `ReplaceFileW`_ have completed. This causes deletion
531   and rename events for ``foo`` (which will in practice be merged due
532   to the pending delay, although we don't rely on that for correctness).
533   The rename also changes the ``mtime`` for ``foo`` so that it is
534   different from the ``mtime`` calculated in step 3, and therefore
535   different from the metadata recorded for ``foo`` in the magic folder
536   db. (Assuming no system clock changes, its rename will set an
537   ``mtime`` timestamp corresponding to a time after the internal
538   operations of `ReplaceFileW`_ have completed, which is not equal to
539   the timestamp *T* seconds before `ReplaceFileW`_ is called, provided
540   that *T* seconds is sufficiently greater than the timestamp
541   granularity.) Therefore, an upload will be triggered for ``foo``
542   after its change, which is correct and avoids data loss.
543
544 .. _`MoveFileExW`: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365240%28v=vs.85%29.aspx
545
546 We also need to consider what happens if another process opens ``foo``
547 and writes to it directly, rather than renaming another file onto it:
548
549 * On Unix, open file handles refer to inodes, not paths. If the other
550   process opens ``foo`` before it has been renamed to ``foo.backup``,
551   and then closes the file, changes will have been written to the file
552   at the same inode, even if that inode is now linked at ``foo.backup``.
553   This avoids data loss.
554
555 * On Windows, we have two subcases, depending on whether the sharing
556   flags specified by the other process when it opened its file handle
557   included ``FILE_SHARE_DELETE``. (This flag covers both deletion and
558   rename operations.)
559
560   i.  If the sharing flags *do not* allow deletion/renaming, the
561       `ReplaceFileW`_ operation will fail without renaming ``foo``.
562       In this case we will end up with ``foo`` changed by the other
563       process, and the downloaded file still in ``foo.tmp``.
564       This avoids data loss.
565
566   ii. If the sharing flags *do* allow deletion/renaming, then
567       data loss or corruption may occur. This is unavoidable and
568       can be attributed to other process making a poor choice of
569       sharing flags (either explicitly if it used `CreateFile`_, or
570       via whichever higher-level API it used).
571
572 .. _`CreateFile`: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx
573
574 Note that it is possible that another process tries to open the file
575 between steps 4b and 4c (or 4b′ and 4c′ on Windows). In this case the
576 open will fail because ``foo`` does not exist. Nevertheless, no data
577 will be lost, and in many cases the user will be able to retry the
578 operation.
579
580 Above we only described the case where the download was initially
581 classified as an overwrite. If it was classed as a conflict, the
582 procedure is the same except that we choose a unique filename
583 for the conflicted file (say, ``foo.conflicted_unique``). We write
584 the new contents to ``.foo.tmp`` and then rename it to
585 ``foo.conflicted_unique`` in such a way that the rename will fail
586 if the destination already exists. (On Windows this is a simple
587 rename; on Unix it can be implemented as a link operation followed
588 by an unlink, similar to steps 4c and 4d above.) If this fails
589 because another process wrote ``foo.conflicted_unique`` after we
590 chose the filename, then we retry with a different filename.
591
592
593 Read/download collisions
594 ~~~~~~~~~~~~~~~~~~~~~~~~
595
596 A *read/download collision* occurs when another program reads
597 from ``foo`` in the local filesystem, concurrently with the new
598 version being written by the Magic Folder client. We want to
599 ensure that any successful attempt to read the file by the other
600 program obtains a consistent view of its contents.
601
602 On Unix, the above procedure for writing downloads is sufficient
603 to achieve this. There are three cases:
604
605 * A. The other process opens ``foo`` for reading before it is
606   renamed to ``foo.backup``. Then the file handle will continue to
607   refer to the old file across the rename, and the other process
608   will read the old contents.
609
610 * B. The other process attempts to open ``foo`` after it has been
611   renamed to ``foo.backup``, and before it is linked in step c.
612   The open call fails, which is acceptable.
613
614 * C. The other process opens ``foo`` after it has been linked to
615   the new file. Then it will read the new contents.
616
617 On Windows, the analysis is very similar, but case A′ needs to
618 be split into two subcases, depending on the sharing mode the other
619 process uses when opening the file for reading:
620
621 * A′. The other process opens ``foo`` before the Magic Folder
622   client's attempt to rename ``foo`` to ``foo.backup`` (as part
623   of the implementation of `ReplaceFileW`_). The subcases are:
624
625   i.  The other process uses sharing flags that deny deletion and
626       renames. The `ReplaceFileW`_ call fails, and the download is
627       reclassified as a conflict. The downloaded file ends up at
628       ``foo.conflicted``, which is correct.
629
630   ii. The other process uses sharing flags that allow deletion
631       and renames. The `ReplaceFileW`_ call succeeds, and the
632       other process reads inconsistent data. This can be attributed
633       to a poor choice of sharing flags by the other process.
634
635 * B′. The other process attempts to open ``foo`` at the point
636   during the `ReplaceFileW`_ call where it does not exist.
637   The open call fails, which is acceptable.
638
639 * C′. The other process opens ``foo`` after it has been linked to
640   the new file. Then it will read the new contents.
641
642
643 For both write/download and read/download collisions, we have
644 considered only interleavings with a single other process, and
645 only the most common possibilities for the other process'
646 interaction with the file. If multiple other processes are
647 involved, or if a process performs operations other than those
648 considered, then we cannot say much about the outcome in general;
649 however, we believe that such cases will be much less common.
650
651
652
653 Fire Dragons: Distinguishing conflicts from overwrites
654 ''''''''''''''''''''''''''''''''''''''''''''''''''''''
655
656 When synchronizing a file that has changed remotely, the Magic Folder
657 client needs to distinguish between overwrites, in which the remote
658 side was aware of your most recent version and overwrote it with a
659 new version, and conflicts, in which the remote side was unaware of
660 your most recent version when it published its new version. Those two
661 cases have to be handled differently — the latter needs to be raised
662 to the user as an issue the user will have to resolve and the former
663 must not bother the user.
664
665 For example, suppose that Alice's Magic Folder client sees a change
666 to ``foo`` in Bob's DMD. If the version it downloads from Bob's DMD
667 is "based on" the version currently in Alice's local filesystem at
668 the time Alice's client attempts to write the downloaded file, then
669 it is an overwrite. Otherwise it is initially classified as a
670 conflict.
671
672 This initial classification is used by the procedure for writing a
673 file described in the `Earth Dragons`_ section above. As explained
674 in that section, we may reclassify an overwrite as a conflict if an
675 error occurs during the write procedure.
676
677 .. _`Earth Dragons`: #earth-dragons-collisions-between-local-filesystem-operations-and-downloads
678
679 In order to implement this policy, we need to specify how the
680 "based on" relation between file versions is recorded and updated.
681
682 We propose to record this information:
683
684 * in the `magic folder db`_, for local files;
685 * in the Tahoe-LAFS directory metadata, for files stored in the
686   Magic Folder.
687
688 In the magic folder db we will add a *last-downloaded record*,
689 consisting of ``last_downloaded_uri`` and ``last_downloaded_timestamp``
690 fields, for each path stored in the database. Whenever a Magic Folder
691 client downloads a file, it stores the downloaded version's URI and
692 the current local timestamp in this record. Since only immutable
693 files are used, the URI will be an immutable file URI, which is
694 deterministically and uniquely derived from the file contents and
695 the Tahoe-LAFS node's `convergence secret`_.
696
697 (Note that the last-downloaded record is updated regardless of
698 whether the download is an overwrite or a conflict. The rationale
699 for this to avoid "conflict loops" between clients, where every
700 new version after the first conflict would be considered as another
701 conflict.)
702
703 .. _`convergence secret`: https://tahoe-lafs.org/trac/tahoe-lafs/browser/docs/convergence-secret.rst
704
705 Later, in response to a local filesystem change at a given path, the
706 Magic Folder client reads the last-downloaded record associated with
707 that path (if any) from the database and then uploads the current
708 file. When it links the uploaded file into its client DMD, it
709 includes the ``last_downloaded_uri`` field in the metadata of the
710 directory entry, overwriting any existing field of that name. If
711 there was no last-downloaded record associated with the path, this
712 field is omitted.
713
714 Note that ``last_downloaded_uri`` field does *not* record the URI of
715 the uploaded file (which would be redundant); it records the URI of
716 the last download before the local change that caused the upload.
717 The field will be absent if the file has never been downloaded by
718 this client (i.e. if it was created on this client and no change
719 by any other client has been detected).
720
721 A possible refinement also takes into account the
722 ``last_downloaded_timestamp`` field from the magic folder db, and
723 compares it to the timestamp of the change that caused the upload
724 (which should be later, assuming no system clock changes).
725 If the duration between these timestamps is very short, then we
726 are uncertain about whether the process on Bob's system that wrote
727 the local file could have taken into account the last download.
728 We can use this information to be conservative about treating
729 changes as conflicts. So, if the duration is less than a configured
730 threshold, we omit the ``last_downloaded_uri`` field from the
731 metadata. This will have the effect of making other clients treat
732 this change as a conflict whenever they already have a copy of the
733 file.
734
735 Now we are ready to describe the algorithm for determining whether a
736 download for the file ``foo`` is an overwrite or a conflict (refining
737 step 2 of the procedure from the `Earth Dragons`_ section).
738
739 Let ``last_downloaded_uri`` be the field of that name obtained from
740 the directory entry metadata for ``foo`` in Bob's DMD (this field
741 may be absent). Then the algorithm is:
742
743 * 2a. If Alice has no local copy of ``foo``, classify as an overwrite.
744
745 * 2b. Otherwise, "stat" ``foo`` to get its *current statinfo* (size
746   in bytes, ``mtime``, and ``ctime``).
747
748 * 2c. Read the following information for the path ``foo`` from the
749   local magic folder db:
750
751   * the *last-uploaded statinfo*, if any (this is the size in
752     bytes, ``mtime``, and ``ctime`` stored in the ``local_files``
753     table when the file was last uploaded);
754   * the ``filecap`` field of the ``caps`` table for this file,
755     which is the URI under which the file was last uploaded.
756     Call this ``last_uploaded_uri``.
757
758 * 2d. If any of the following are true, then classify as a conflict:
759
760   * there are pending notifications of changes to ``foo``;
761   * the last-uploaded statinfo is either absent, or different
762     from the current statinfo;
763   * either ``last_downloaded_uri`` or ``last_uploaded_uri``
764     (or both) are absent, or they are different.
765
766   Otherwise, classify as an overwrite.
767
768
769 Air Dragons: Collisions between local writes and uploads
770 ''''''''''''''''''''''''''''''''''''''''''''''''''''''''
771
772 Short of filesystem-specific features on Unix or the `shadow copy service`_
773 on Windows (which is per-volume and therefore difficult to use in this
774 context), there is no way to *read* the whole contents of a file
775 atomically. Therefore, when we read a file in order to upload it, we
776 may read an inconsistent version if it was also being written locally.
777
778 .. _`shadow copy service`: https://technet.microsoft.com/en-us/library/ee923636%28v=ws.10%29.aspx
779
780 A well-behaved application can avoid this problem for its writes:
781
782 * On Unix, if another process modifies a file by renaming a temporary
783   file onto it, then we will consistently read either the old contents
784   or the new contents.
785 * On Windows, if the other process uses sharing flags to deny reads
786   while it is writing a file, then we will consistently read either
787   the old contents or the new contents, unless a sharing error occurs.
788   In the case of a sharing error we should retry later, up to a
789   maximum number of retries.
790
791 In the case of a not-so-well-behaved application writing to a file
792 at the same time we read from it, the magic folder will still be
793 eventually consistent, but inconsistent versions may be visible to
794 other users' clients.
795
796 In Objective 2 we implemented a delay, called the *pending delay*,
797 after the notification of a filesystem change and before the file is
798 read in order to upload it (Tahoe-LAFS ticket `#1440`_). If another
799 change notification occurs within the pending delay time, the delay
800 is restarted. This helps to some extent because it means that if
801 files are written more quickly than the pending delay and less
802 frequently than the pending delay, we shouldn't encounter this
803 inconsistency.
804
805 .. _`#1440`: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1440
806
807 The likelihood of inconsistency could be further reduced, even for
808 writes by not-so-well-behaved applications, by delaying the actual
809 upload for a further period —called the *stability delay*— after the
810 file has finished being read. If a notification occurs between the
811 end of the pending delay and the end of the stability delay, then
812 the read would be aborted and the notification requeued.
813
814 This would have the effect of ensuring that no write notifications
815 have been received for the file during a time window that brackets
816 the period when it was being read, with margin before and after
817 this period defined by the pending and stability delays. The delays
818 are intended to account for asynchronous notification of events, and
819 caching in the filesystem.
820
821 Note however that we cannot guarantee that the delays will be long
822 enough to prevent inconsistency in any particular case. Also, the
823 stability delay would potentially affect performance significantly
824 because (unlike the pending delay) it is not overlapped when there
825 are multiple files on the upload queue. This performance impact
826 could be mitigated by uploading files in parallel where possible
827 (Tahoe-LAFS ticket `#1459`_).
828
829 We have not yet decided whether to implement the stability delay, and
830 it is not planned to be implemented for the OTF objective 4 milestone.
831 Ticket `#2431`_ has been opened to track this idea.
832
833 .. _`#1459`: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1459
834 .. _`#2431`: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/2431
835
836 Note that the situation of both a local process and the Magic Folder
837 client reading a file at the same time cannot cause any inconsistency.
838
839
840 Water Dragons: Handling deletion and renames
841 ''''''''''''''''''''''''''''''''''''''''''''
842
843 Deletion of a file
844 ~~~~~~~~~~~~~~~~~~
845
846 When a file is deleted from the filesystem of a Magic Folder client,
847 the most intuitive behavior is for it also to be deleted under that
848 name from other clients. To avoid data loss, the other clients should
849 actually rename their copies to a backup filename.
850
851 It would not be sufficient for a Magic Folder client that deletes
852 a file to implement this simply by removing the directory entry from
853 its DMD. Indeed, the entry may not exist in the client's DMD if it
854 has never previously changed the file.
855
856 Instead, the client links a zero-length file into its DMD and sets
857 ``deleted: true`` in the directory entry metadata. Other clients
858 take this as a signal to rename their copies to the backup filename.
859
860 Note that the entry for this zero-length file has a version number as
861 usual, and later versions may restore the file.
862
863 When a Magic Folder client restarts, we can detect files that had
864 been downloaded but were deleted while it was not running, because
865 their paths will have last-downloaded records in the magic folder db
866 without any corresponding local file.
867
868 Deletion of a directory
869 ~~~~~~~~~~~~~~~~~~~~~~~
870
871 Local filesystems (unlike a Tahoe-LAFS filesystem) normally cannot
872 unlink a directory that has any remaining children. Therefore a
873 Magic Folder client cannot delete local copies of directories in
874 general, because they will typically contain backup files. This must
875 be done manually on each client if desired.
876
877 Nevertheless, a Magic Folder client that deletes a directory should
878 set ``deleted: true`` on the metadata entry for the corresponding
879 zero-length file. This avoids the directory being recreated after
880 it has been manually deleted from a client.
881
882 Renaming
883 ~~~~~~~~
884
885 It is sufficient to handle renaming of a file by treating it as a
886 deletion and an addition under the new name.
887
888 This also applies to directories, although users may find the
889 resulting behavior unintuitive: all of the files under the old name
890 will be renamed to backup filenames, and a new directory structure
891 created under the new name. We believe this is the best that can be
892 done without imposing unreasonable implementation complexity.
893
894
895 Summary
896 -------
897
898 This completes the design of remote-to-local synchronization.
899 We realize that it may seem very complicated. Anecdotally, proprietary
900 filesystem synchronization designs we are aware of, such as Dropbox,
901 are said to incur similar or greater design complexity.